Protect a NestJS route with a guard
Decide whether a request may reach a NestJS 11 handler with a CanActivate guard, applied to a route with the UseGuards decorator.
Authorization checks belong before the handler, in a guard. It returns true to allow the request or false to reject it.
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import type { Request } from 'express';
@Injectable()
export class ApiKeyGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest<Request>();
return request.headers['x-api-key'] === process.env.API_KEY;
}
}import { Controller, Delete, Param, UseGuards } from '@nestjs/common';
import { ApiKeyGuard } from '../auth/api-key.guard';
@Controller('cats')
export class CatsController {
@Delete(':id')
@UseGuards(ApiKeyGuard)
remove(@Param('id') id: string) {
return { removed: id };
}
}DELETE /cats/1 -> 403 {"message":"Forbidden resource","error":"Forbidden","statusCode":403}
DELETE /cats/1 (x-api-key: <valid key>) -> 200 {"removed":"1"}A guard that returns false produces a 403. To get a 401 instead, throw UnauthorizedException from canActivate. Guards run after middleware and before pipes and the handler. @UseGuards works on a method, on a whole controller, or globally. See Guards.
Compare secrets in constant time in real code. Real apps usually build on Passport or a JWT strategy instead of a raw header check.