A Guard is a class annotated with @Injectable() that implements the CanActivate interface. Its single responsibility is to determine whether a request will be handled by a route handler based on runtime conditions like permissions, roles, or ACLs (authorization).
Key differences from Middleware:
- Context Awareness: Unlike middleware, Guards have access to the
ExecutionContext, meaning they know exactly which handler will be executed next. - Execution Order: Guards are executed after all middleware, but before any interceptor or pipe.
Use Guards for authorization logic to keep your code declarative and DRY.
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Observable } from 'rxjs';
@Injectable()
export class AuthGuard implements CanActivate {
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
const request = context.switchToHttp().getRequest();
return validateRequest(request);
}
}