NestJS 11 · Validation, guards and interceptors

Protect routes with a guard

A guard decides whether a request may proceed. Throw or return false to deny it.

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    return Boolean(request.headers.authorization);
  }
}

@UseGuards(AuthGuard)
@Get('profile')
profile() {}

Official NestJS 11 documentation

More validation, guards and interceptors commands

All validation, guards and interceptors commands · NestJS 11 cheatsheet

Was this page helpful?