Lesson 11 / 33
Guards & Authentication
Protect routes and enforce access control with guards.
Create a guard
A guard is a class implementing CanActivate. Return true to allow, false to reject.
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
@Injectable()
export class JwtGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
const token = request.headers.authorization?.split(' ')[1];
if (!token) return false;
try {
// verify token
return true;
} catch {
return false;
}
}
}Apply a guard
Use @UseGuards() decorator on routes or controllers.
@UseGuards(JwtGuard)
@Get('profile')
getProfile(@Request() req) {
return req.user;
}
// or on the controller
@Controller('admin')
@UseGuards(JwtGuard)
export class AdminController { ... }Passport.js integration
NestJS ships with @nestjs/passport for seamless authentication—JWT, OAuth, local, etc.