@Injectable()
export class AuthGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const req = context.switchToHttp().getRequest();
return Boolean(req.user);
}
}
A guard is a class that decides if a request may reach the route handler. It implements the CanActivate interface. Its canActivate() method returns a boolean, a Promise<boolean> or an Observable<boolean>. true lets the request through, and false stops it.
Guards run after middleware and before interceptors and pipes. You bind them with @UseGuards() on a controller or on one handler, or you register them globally.
Why is a guard better than middleware for authorization? Middleware doesn't know which handler will run. A guard receives an ExecutionContext. This is an object that describes the current request and the code that will handle it. Through it, the guard can:
- see the target class and method
- read metadata attached to them, such as required roles or a
@Public()flag - work the same way for HTTP, WebSockets and microservices
So you can write authorization rules as decorators on each route, and the guard reads them. This style is called declarative.
- A guard implements
CanActivateand returns a boolean, a Promise or an Observable. - Guards run after middleware and before interceptors and pipes.
- The
ExecutionContexttells the guard which handler and class will run. - A guard can read route metadata through
Reflector. - You bind a guard with
@UseGuards()or register it globally.
- Guards (https://docs.nestjs.com/guards)docs.nestjs.com