Guard
ELI5 — The Vibe Check
A guard in NestJS is a gatekeeper that decides if a request should be allowed through. Auth guards check if you're logged in. Role guards check if you're an admin. If the guard says no, the request is rejected before it ever reaches the handler. No guard, no entry.
Real Talk
In NestJS, guards are classes that implement the CanActivate interface to determine whether a request should be processed. They run after middleware but before interceptors and pipes, making them ideal for authentication and authorization logic. Guards have access to the execution context and can use decorators for role-based or permission-based access control.
Show Me The Code
@Injectable()
class RoleGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const roles = Reflect.getMetadata('roles', context.getHandler());
const user = context.switchToHttp().getRequest().user;
return roles.includes(user.role);
}
}
@UseGuards(RoleGuard)
@Roles('admin')
@Get('admin/dashboard')
async getDashboard() { /* ... */ }
When You'll Hear This
"The auth guard rejects requests without a valid JWT." / "Use role guards to restrict admin endpoints to admin users only."
Related Terms
Authentication (AuthN)
Authentication is proving you are who you say you are.
Authorization (AuthZ)
Authorization is deciding what you're allowed to do after you've proven who you are.
Interceptor
An interceptor catches requests and responses on the way in and out, letting you transform them.
NestJS
NestJS is Node.js with structure. Plain Express can get messy in large projects.