CodePark/ questions / Guards & auth
START PRACTICINGPRACTICE
Backend question · NestJS › Guards & auth

What is a guard in Nest, and why is it a better place for authorization than middleware?

@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 CanActivate and returns a boolean, a Promise or an Observable.
  • Guards run after middleware and before interceptors and pipes.
  • The ExecutionContext tells 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.