Guard (backend)
ELI5 — The Vibe Check
A guard is a checkpoint that decides whether a request should proceed or be rejected — like a bouncer with a guest list. It runs before the route handler and returns true (let them in) or false (kick them out). Guards handle authorization: 'you might be logged in, but are you ALLOWED to do this?'
Real Talk
In backend frameworks like NestJS, a guard is a class that implements a canActivate() method to determine if a request should be handled. Guards run after middleware but before interceptors and pipe validation. They're used for authentication, role-based access control (RBAC), and feature flags. They can be applied at the controller, method, or global level.
Show Me The Code
@Injectable()
export class RolesGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.get<string[]>('roles', context.getHandler());
const user = context.switchToHttp().getRequest().user;
return requiredRoles.some((role) => user.roles.includes(role));
}
}
@UseGuards(RolesGuard)
@Roles('admin')
@Get('users')
getUsers() { }
When You'll Hear This
"Add an admin guard to that endpoint — only admins should access it." / "The auth guard runs before the roles guard in NestJS."
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.
Middleware Chain
A middleware chain is a series of functions that requests pass through, one after another, like an assembly line.