CanActivate

Interface a guard implements to authorize whether a request may proceed.

Since NestJS 10/11 Spec ↗

Syntax

canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean>

Parameters

NameTypeRequiredDescription
context ExecutionContext No The execution context for the current request.

Returns

boolean | Promise<boolean> | Observable<boolean> — true allows the request; false denies it.

Throws

  • ForbiddenException — May be thrown to customize the denial response.

Examples

import {
  Injectable, CanActivate, ExecutionContext,
} from '@nestjs/common';

@Injectable()
export class ApiKeyGuard implements CanActivate {
  canActivate(ctx: ExecutionContext): boolean {
    const req = ctx.switchToHttp().getRequest();
    return req.headers['x-api-key'] === process.env.API_KEY;
  }
}

Notes

Returning false yields a 403 by default. Throw an HttpException subclass to control the status and message. Bind guards with @UseGuards() or app.useGlobalGuards().