Skip to content
jshacks.dev
Frameworks

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.

1 min read
Summarize in AI

Authorization checks belong before the handler, in a guard. It returns true to allow the request or false to reject it.

src/auth/api-key.guard.tsTypeScript
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;
  }
}
src/cats/cats.controller.tsTypeScript
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 };
  }
}
Text
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.

Also inNode.js
Taggednestjs 11
Share

More snippets

Frameworks

Update state from the previous value

Pass an updater function to the React state setter when the next value depends on the last one, so batched updates do not overwrite each other.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.