Guards & Authorization
Who are you, and are you allowed? AuthGuard, RolesGuard, custom decorators with SetMetadata + Reflector, @Public(), @Roles(), @CurrentUser(), and 401 vs 403 done right.
Alright, you've got validation, error handling, and response wrapping. Your API is well-structured but has one massive hole — anyone can hit any endpoint. Right now, your task API is a public buffet. Anyone with your URL can create, read, update, and delete tasks. In production, that's not an API — that's a liability.
The Problem You Have Right Now
curl -X DELETE http://localhost:3000/tasks/1
# Task deleted. No questions asked. No identity checked.No authentication. No authorization. No "who are you?" or "are you allowed to do this?" Your API trusts every request like a golden retriever trusts every stranger. Adorable in a dog, catastrophic in a backend.
Analogy
Your API is currently an office building with no locks, no reception, and no badges — anyone off the street can walk into the server room and unplug things. This module installs the badge system: readers on every door, a public lobby, and floors that only certain badges open.
Guards vs Middleware — Why Not Just Use Middleware?
If you're coming from Express/Next.js, you're thinking "just slap a middleware that checks the JWT." You can, but here's why Guards are better:
Middleware runs before route matching is fully resolved. It has access to req, res, next — raw Express objects. It does NOT know which controller or method will handle the request. It can't read NestJS decorators or metadata.
Guards run after route matching, after middleware. They have access to the ExecutionContext — which means they know exactly which controller class and which method is about to execute. This means guards can read custom decorators like @Public() or @Roles('admin') and make decisions based on metadata you attach to specific routes.
Middleware: "Is there a valid token in the request?" (generic)
Guard: "Is there a valid token, AND does this user have the 'admin' role
required by @Roles('admin') on this specific route?" (contextual)Middleware is a bouncer checking IDs at the door. Guards are the bouncer who also checks if your name is on the VIP list for the specific room you're trying to enter.
Analogy
In badge terms: middleware is the street-level reception that checks you carry some badge at all — it has no idea where you're headed. A guard is the reader mounted on one specific door: it knows exactly which room is behind it and which access levels that room demands. That per-door knowledge is what ExecutionContext gives guards and middleware never gets.
Where Guards Sit in the Lifecycle
the guard decides at position ②
Guards run before interceptors and pipes. If the guard rejects, nothing downstream executes. No validation, no logging interceptor, no controller. Short-circuited. Efficient.
Analogy
When your badge fails at the door, you don't get partway into the building. The lights don't come on for you, nobody inspects your paperwork, no meeting starts — you're simply still in the hallway. That's the short-circuit: a rejected request never wakes anything downstream.
The Guard Interface
Every guard implements CanActivate with one method:
canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean>Return true → request proceeds. Return false → NestJS throws ForbiddenException (403) automatically. Throw an exception → your exception filter handles it (useful for throwing UnauthorizedException (401) instead of the default 403).
ExecutionContext extends ArgumentsHost (you've seen this in filters and interceptors) with two extra methods that make guards powerful:
context.getHandler() // → the route method about to execute (e.g., TasksController.create)
context.getClass() // → the controller class (e.g., TasksController)These let you read custom metadata/decorators attached to routes and controllers. This is how role-based access works.
Step 1: JWT Authentication Guard
We'll simulate JWT auth without an actual JWT library first — so you understand the guard mechanics, not the crypto. Then I'll show you what changes for real JWT.
src/common/guards/auth.guard.ts
import {
Injectable,
CanActivate,
ExecutionContext,
UnauthorizedException,
} from '@nestjs/common';
import { Request } from 'express';
import { Reflector } from '@nestjs/core';
import { IS_PUBLIC_KEY } from '../decorators/public.decorator';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
// ① Check if route is marked @Public()
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
context.getHandler(),
context.getClass(),
]);
if (isPublic) {
return true; // skip auth entirely
}
// ② Extract token from Authorization header
const request = context.switchToHttp().getRequest<Request>();
const token = this.extractToken(request);
if (!token) {
throw new UnauthorizedException('No token provided');
}
// ③ Validate token (simplified — no real JWT verification yet)
const user = this.validateToken(token);
if (!user) {
throw new UnauthorizedException('Invalid or expired token');
}
// ④ Attach user to request so controllers/services can access it
request['user'] = user;
return true;
}
private extractToken(request: Request): string | null {
const authHeader = request.headers.authorization;
if (!authHeader) return null;
const [type, token] = authHeader.split(' ');
return type === 'Bearer' ? token : null;
}
private validateToken(token: string): Record<string, any> | null {
// SIMULATED — in reality you'd use jsonwebtoken or @nestjs/jwt
// For learning: any token starting with "valid-" is accepted
if (token.startsWith('valid-')) {
return {
id: 1,
username: 'testuser',
roles: token.includes('admin') ? ['admin', 'user'] : ['user'],
};
}
return null;
}
}Breaking this down:
Reflector — This is NestJS's metadata reader. When you put @Public() on a route, it stores metadata. Reflector reads that metadata. It's injected through DI — this is why using the APP_GUARD registration approach matters (more on this soon).
reflector.getAllAndOverride() — Checks both the handler (route method) AND the class (controller) for the metadata key. If either has @Public(), it returns true. getAllAndOverride prioritizes the handler-level value over the class-level value. So you can mark an entire controller as @Public() but then override specific routes to require auth, or vice versa.
request['user'] = user — After validating the token, you attach the decoded user to the request object. This is the standard pattern. Downstream controllers and services access request.user to know who's making the request. We'll create a clean decorator for this.
Why throw UnauthorizedException instead of returning false? Returning false gives a generic ForbiddenException (403). But missing/invalid token is a 401 problem — "who are you?" not "you can't do this." Throwing the right exception gives the right status code and your exception filter formats it consistently.
Analogy
401 versus 403 is "no badge" versus "wrong floor". Arriving with no badge at all, or a forged one, gets you sent back to reception to prove who you are (401). Arriving with a perfectly valid intern badge at the executive floor gets a polite "we know exactly who you are — and no" (403).
Step 2: The @Public() Decorator
Custom decorators in NestJS are just metadata setters. They're one-liners.
src/common/decorators/public.decorator.ts
import { SetMetadata } from '@nestjs/common';
export const IS_PUBLIC_KEY = 'isPublic';
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);That's it. SetMetadata attaches a key-value pair to the route's metadata. The guard reads it with Reflector. Usage:
@Public()
@Get('health')
healthCheck() {
return { status: 'ok' };
}This route now bypasses authentication entirely. Every other route requires a token.
Analogy
@Public() marks a door as the lobby. Anyone can walk in off the street — no badge, no questions. Everything else in the building keeps its reader. You mark the lobby explicitly rather than unlocking doors one exception at a time, so "secured" stays the default.
Step 3: The @Roles() Decorator and RolesGuard
Authentication answers "who are you?" Authorization answers "are you allowed?" Two different questions, two different guards.
Analogy
Reception verifies your identity and hands you a badge — that's authentication. The reader on the finance floor doesn't re-verify who you are; it only checks whether your badge carries the "finance" access level — that's authorization. Same badge, two completely different questions asked of it.
src/common/decorators/roles.decorator.ts
import { SetMetadata } from '@nestjs/common';
export const ROLES_KEY = 'roles';
export const Roles = (...roles: string[]) => SetMetadata(ROLES_KEY, roles);src/common/guards/roles.guard.ts
import {
Injectable,
CanActivate,
ExecutionContext,
ForbiddenException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ROLES_KEY } from '../decorators/roles.decorator';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
// ① Get required roles from route metadata
const requiredRoles = this.reflector.getAllAndOverride<string[]>(
ROLES_KEY,
[context.getHandler(), context.getClass()],
);
// ② No @Roles() decorator on this route? No role restriction. Allow.
if (!requiredRoles || requiredRoles.length === 0) {
return true;
}
// ③ Get user from request (attached by AuthGuard earlier)
const request = context.switchToHttp().getRequest();
const user = request['user'];
if (!user) {
// This shouldn't happen if AuthGuard runs first
// but defensive coding never hurts
throw new ForbiddenException('No user context found');
}
// ④ Check if user has at least one required role
const hasRole = requiredRoles.some((role) => user.roles?.includes(role));
if (!hasRole) {
throw new ForbiddenException(
`Requires one of [${requiredRoles.join(', ')}] roles`,
);
}
return true;
}
}Critical point — Guard execution order:
AuthGuard must run before RolesGuard. AuthGuard attaches user to the request. RolesGuard reads user.roles. If they run in the wrong order, RolesGuard sees no user and everything fails.
When you register multiple global guards, they execute in registration order. So register AuthGuard first.
Analogy
Reception has to issue the badge before any floor reader can inspect it. Put the floor reader first and it's scanning an empty lanyard — that's exactly what RolesGuard running before AuthGuard looks like: checking roles on a user that was never attached.
Step 4: @CurrentUser() Decorator — Clean Request Access
Instead of doing request['user'] everywhere in controllers (ugly, untyped, fragile), create a parameter decorator:
src/common/decorators/current-user.decorator.ts
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
export const CurrentUser = createParamDecorator(
(data: string | undefined, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
const user = request['user'];
// if a specific property is requested, return just that
// @CurrentUser('id') → returns user.id
// @CurrentUser() → returns entire user object
return data ? user?.[data] : user;
},
);Usage in controller:
@Get('profile')
getProfile(@CurrentUser() user: any) {
return user; // { id: 1, username: 'testuser', roles: ['user'] }
}
@Get('my-id')
getMyId(@CurrentUser('id') userId: number) {
return { userId }; // { userId: 1 }
}Clean, typed, reusable. No reaching into request manually.
Analogy
@CurrentUser() is having your badge details printed on your meeting paperwork automatically. Instead of every office rummaging through your bag (request['user']) to find out who you are, the details arrive as a clean, labelled parameter — and you can ask for just the one field you need, like the badge number.
Step 5: Register Guards Globally
app.module.ts — DI-aware registration
import { Module } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { TasksModule } from './tasks/tasks.module';
import { AuthGuard } from './common/guards/auth.guard';
import { RolesGuard } from './common/guards/roles.guard';
@Module({
imports: [TasksModule],
providers: [
{
provide: APP_GUARD,
useClass: AuthGuard, // runs first — authenticates
},
{
provide: APP_GUARD,
useClass: RolesGuard, // runs second — authorizes
},
],
})
export class AppModule {}Why DI-aware (APP_GUARD) and not app.useGlobalGuards()? Both guards inject Reflector. If you use app.useGlobalGuards(new AuthGuard()), you'd have to manually pass Reflector — which you don't even have access to in main.ts. The APP_GUARD approach lets NestJS's DI container handle it. Use APP_GUARD for guards. Always.
Step 6: Update Your Tasks Controller
tasks.controller.ts — With auth and roles
import {
Controller, Get, Post, Patch, Delete,
Param, Body, ParseIntPipe,
} from '@nestjs/common';
import { TasksService } from './tasks.service';
import { CreateTaskDto } from './dto/create-task.dto';
import { UpdateTaskDto } from './dto/update-task.dto';
import { Task } from './interfaces/task.interface';
import { Public } from '../common/decorators/public.decorator';
import { Roles } from '../common/decorators/roles.decorator';
import { CurrentUser } from '../common/decorators/current-user.decorator';
@Controller('tasks')
export class TasksController {
constructor(private readonly tasksService: TasksService) {}
// Anyone can view tasks — no token needed
@Public()
@Get()
findAll(): Task[] {
return this.tasksService.findAll();
}
// Anyone can view a single task
@Public()
@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number): Task {
return this.tasksService.findOne(id);
}
// Authenticated users can create tasks
// No @Public() = AuthGuard enforces token
// No @Roles() = any authenticated user can do this
@Post()
create(
@Body() createTaskDto: CreateTaskDto,
@CurrentUser('username') username: string,
): Task {
console.log(`Task created by: ${username}`);
return this.tasksService.create(createTaskDto);
}
// Authenticated users can update tasks
@Patch(':id')
update(
@Param('id', ParseIntPipe) id: number,
@Body() updateTaskDto: UpdateTaskDto,
): Task {
return this.tasksService.update(id, updateTaskDto);
}
// Only admins can delete tasks
@Roles('admin')
@Delete(':id')
remove(@Param('id', ParseIntPipe) id: number): { deleted: boolean } {
this.tasksService.remove(id);
return { deleted: true };
}
}Let's Trace Every Scenario
Scenario 1: GET /tasks — Public route, no token
→ reflector reads @Public() on findAll() → isPublic = true
→ return true immediately (token not even checked)
→ reflector reads @Roles() on findAll() → no roles required
→ return true
{
"success": true,
"data": ["...tasks"],
"timestamp": "...",
"path": "/tasks"
}Scenario 2: POST /tasks — No token (should fail)
→ reflector reads @Public() on create() → isPublic = false
→ extractToken() → no header → null
→ throw UnauthorizedException('No token provided')
{
"success": false,
"statusCode": 401,
"error": "Unauthorized",
"message": "No token provided",
"timestamp": "...",
"path": "/tasks"
}Controller never executes. RolesGuard never executes. Pipes never execute. Short-circuited at the gate.
Scenario 3: POST /tasks — Valid token, regular user
Headers: Authorization: Bearer valid-user-token
→ not @Public() → extract token → "valid-user-token"
→ validateToken() → starts with "valid-" → user = { id:1, roles:['user'] }
→ request['user'] = user
→ return true
→ no @Roles() on create() → no role restriction → return true
{
"success": true,
"data": { "id": 1, "title": "...", "description": "...", "done": false },
"timestamp": "...",
"path": "/tasks"
}Scenario 4: DELETE /tasks/1 — Valid token, regular user (should fail — admin only)
Headers: Authorization: Bearer valid-user-token
→ not @Public() → token valid → user = { id:1, roles:['user'] }
→ request['user'] = user → return true
→ reflector reads @Roles('admin') on remove()
→ requiredRoles = ['admin']
→ user.roles = ['user']
→ 'user' does not include 'admin'
→ throw ForbiddenException('Requires one of [admin] roles')
{
"success": false,
"statusCode": 403,
"error": "Forbidden",
"message": "Requires one of [admin] roles",
"timestamp": "...",
"path": "/tasks/1"
}Authenticated but not authorized. 401 vs 403 — your API correctly distinguishes.
Scenario 5: DELETE /tasks/1 — Admin token
Headers: Authorization: Bearer valid-admin-token
→ token = "valid-admin-token" → contains "admin"
→ user = { id:1, roles:['admin', 'user'] }
→ return true
→ requiredRoles = ['admin']
→ user.roles includes 'admin' → hasRole = true
→ return true
{
"success": true,
"data": { "deleted": true },
"timestamp": "...",
"path": "/tasks/1"
}Scenario 6: POST /tasks — Expired/garbage token
Headers: Authorization: Bearer garbage-token-abc
→ not @Public() → token = "garbage-token-abc"
→ validateToken() → doesn't start with "valid-" → returns null
→ throw UnauthorizedException('Invalid or expired token')
{
"success": false,
"statusCode": 401,
"error": "Unauthorized",
"message": "Invalid or expired token",
"timestamp": "...",
"path": "/tasks"
}The Guard Decision Flow — Simplified
Each request passes through five gates. The first gate that produces a verdict ends the flow — otherwise it falls through to the next:
YES → skip auth entirely, ALLOW ✅
NO → next gate
NO → 401 No token ❌
YES → next gate
NO → 401 Invalid ❌
YES → attach user to request, next gate
NO → no restriction, ALLOW ✅
YES → next gate
NO → 403 Forbidden ❌
YES → ALLOW ✅
⚡ Quick lookup — the whole decision at a glance
Is route @Public()?
YES -> skip auth, ALLOW
NO -> Has Bearer token?
NO -> 401 No token
YES -> Token valid?
NO -> 401 Invalid
YES -> attach user -> Route has @Roles()?
NO -> ALLOW
YES -> User has role?
NO -> 403 Forbidden
YES -> ALLOWMoving to Real JWT — What Changes
When you're ready to use actual JWTs instead of the simulated validation, install:
npm install @nestjs/jwtYour AuthGuard changes minimally — the validateToken method gets replaced:
// BEFORE (simulated)
private validateToken(token: string): Record<string, any> | null {
if (token.startsWith('valid-')) {
return { id: 1, username: 'testuser', roles: ['user'] };
}
return null;
}
// AFTER (real JWT)
constructor(
private reflector: Reflector,
private jwtService: JwtService, // injected via DI
) {}
private validateToken(token: string): Record<string, any> | null {
try {
return this.jwtService.verify(token); // decodes + verifies signature + expiry
} catch {
return null;
}
}The guard structure, the @Public() decorator, the @Roles() decorator, the RolesGuard, the @CurrentUser() decorator — none of that changes. The architecture holds. You just swap the verification mechanism. That's what good separation of concerns looks like.
Updated Project Structure
The Full Pipeline — Everything Now
AuthGuard: checks @Public(), validates token, attaches user
RolesGuard: checks @Roles(), verifies user has required role
LoggingInterceptor: logs "→ GET /tasks"
TransformInterceptor: (nothing pre)
TimeoutInterceptor: starts clock
ValidationPipe validates DTOs@CurrentUser() extracts user, delegates to service
TimeoutInterceptor: (didn't timeout)
TransformInterceptor: wraps { success: true, data }
LoggingInterceptor: logs "← GET /tasks [5ms]"
If an exception is thrown at any stage:
→ { success: false, statusCode, message, ... }
⚡ Quick lookup — pipeline in one line
Request -> Middleware -> Guards(Auth, Roles) -> Interceptors(pre)
-> Pipes -> Controller -> Service -> Interceptors(post) -> Response
(exception anywhere -> Exception Filter)Every layer from the lifecycle diagram you saw in lesson one is now implemented. Middleware is the only one we haven't explicitly built — but NestJS applies Express defaults (body-parser, etc.) automatically.
Next up when you're ready: Middleware — the first thing that touches the request, Express-compatible, and when to use it vs guards/interceptors. Or if you want to go practical, we can jump to real JWT auth with login/register using @nestjs/jwt and @nestjs/passport. Your call.
