skip to content

Guards and Interceptors

Guards read handler metadata through Reflector to answer canActivate; interceptors wrap the handler's observable to map, time or serialize. Interviewers ask what a guard sees that middleware cannot.

on this pageshow

explore

questions

5

In a NestJS 12 app, what does a guard's canActivate() receive and return, and what happens when it denies a request?

level: juniorimportance: must knowfreq 70%

answer

  1. one method, one yes-or-no
  2. ExecutionContext extends ArgumentsHost
  3. boolean, Promise or Observable
  4. falsy result becomes ForbiddenException

basics

~20 s

A NestJS guard implements CanActivate: canActivate() receives the ExecutionContext and returns a boolean, or a Promise or Observable of one. A truthy result lets the handler run; a falsy one makes Nest throw ForbiddenException, a 403 'Forbidden resource' response.

solid answer

~40 s

A guard is an `@Injectable()` class implementing `CanActivate`. Its `canActivate(context)` receives an `ExecutionContext`, which extends `ArgumentsHost`: `context.switchToHttp().getRequest()` gives the request, and `getHandler()` and `getClass()` name the exact method and controller about to run. That is what a guard sees and middleware does not, because middleware calls `next()` without knowing which handler comes next. The method may return a `boolean`, a `Promise<boolean>` or an `Observable<boolean>`. When the result is falsy, Nest throws `ForbiddenException('Forbidden resource')`, so the client gets a 403 and the handler never runs. For a different status, throw your own exception, such as `ServiceUnavailableException`, from the guard. Bind a guard with `@UseGuards()` on a controller or method, or globally through the `APP_GUARD` provider token so it can inject services.

code

typescript · 23 lines
typescript
import {
  CanActivate,
  ExecutionContext,
  Injectable,
  ServiceUnavailableException,
} from '@nestjs/common';
import { MaintenanceState } from './maintenance-state.js';

@Injectable()
export class MaintenanceGuard implements CanActivate {
  constructor(private readonly state: MaintenanceState) {}

  canActivate(context: ExecutionContext): boolean {
    if (!this.state.enabled) {
      return true;
    }
    const request = context.switchToHttp().getRequest();
    if (request.method === 'GET') {
      return true;
    }
    throw new ServiceUnavailableException('Writes are paused for maintenance');
  }
}

go deeper

for a junior

Recall the shape: one canActivate() method, an ExecutionContext in, a boolean (or a Promise or Observable of one) out, and false meaning a 403 Forbidden response.

for a middle

Explain what ExecutionContext adds over the raw request: getHandler() and getClass(). Show how throwing changes the status and why APP_GUARD beats useGlobalGuards() for a guard with dependencies.

for a senior

Be ready to diagnose a route that answers 403 for everyone: a guard with a missing return, an Observable that emits false last, or a global guard that never got its service injected.

for a principal

Talk about what a team lets guards do: one decision per guard, deny-by-default versus allow-by-default, and which guards are global so a new controller cannot ship unprotected by accident.

## What a guard is In NestJS, a **guard** is a class decorated with `@Injectable()` that implements the `CanActivate` interface from `@nestjs/common`. It has a single responsibility: deciding whether the current request may reach its route handler. The documentation frames that decision as authorization, but the contract itself is generic: a guard can just as well refuse writes during a maintenance window or hide an endpoint behind a feature flag. The interface has exactly one method: ```typescript canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean>; ``` ## The ExecutionContext it receives `ExecutionContext` extends `ArgumentsHost`, the wrapper around the arguments the handler will receive. On the default Express adapter those arguments are Express's `[request, response, next]`. What the guard can reach through it: - `context.switchToHttp().getRequest()` and `.getResponse()` return the native request and response objects. - `context.getHandler()` returns a **reference to the method** about to be invoked, for example `create` on a controller. - `context.getClass()` returns the **controller class** (the class, not an instance) that method belongs to. - `context.getType()` returns `'http'`, `'rpc'` or `'ws'`, so one guard can serve HTTP routes, microservice handlers and gateways. The last three are the point. Middleware runs with `(req, res, next)` and, when it calls `next()`, does not know which handler will run. A guard knows the handler and its class, so it can read the metadata that decorators put on them (through `Reflector`) and make a per-route decision declaratively. ## What it may return, and what Nest does with it Nest evaluates the route's guards one after another and stops at the first one that does not allow the request. | `canActivate()` result | What Nest does | |---|---| | `true` | continues to the next guard, then the handler | | `false` | throws `ForbiddenException` with message `Forbidden resource` | | `Promise<boolean>` | awaits it, then applies the same rule | | `Observable<boolean>` | takes the last emitted value (`lastValueFrom`) | | `undefined` (a forgotten `return`) | falsy, so the request is denied with a 403 | | a truthy non-boolean, such as an object | truthy, so the request is allowed | The default denial body is: ```json {"message":"Forbidden resource","error":"Forbidden","statusCode":403} ``` ## Denying with a different status A falsy return makes Nest throw `ForbiddenException`, a 403 unless an exception filter remaps it. When the right answer is something else, the guard **throws** instead of returning: 1. Throw a built-in exception such as `UnauthorizedException` (401) or `ServiceUnavailableException` (503). 2. Nest hands any exception thrown by a guard to the exceptions layer: the global exception filter and any filters bound to that route. 3. The handler does not run, because the guard never let the request through. ## Binding a guard Guards can be bound at three scopes: - **Method**: `@UseGuards(MaintenanceGuard)` on one handler. - **Controller**: the same decorator on the class applies it to every handler in it. `@UseGuards()` accepts one guard or a comma-separated list, as classes (Nest instantiates them and injects their dependencies) or as instances you construct yourself. - **Global**: either `app.useGlobalGuards(new MaintenanceGuard(...))` or a provider `{ provide: APP_GUARD, useClass: MaintenanceGuard }` in any module. The two global forms differ. `useGlobalGuards()` takes an instance created outside any module, so the container cannot inject its dependencies. An `APP_GUARD` provider is built by the container, can inject services, and is global whichever module registers it. You may register `APP_GUARD` several times and every registered guard runs; it is a pseudo-provider consumed at bootstrap, so `app.get()` cannot retrieve it later. In a hybrid application, `useGlobalGuards()` does not cover the connected microservices by default. ## A worked example The `MaintenanceGuard` in the code example shows the whole contract in a few lines: 1. It injects a `MaintenanceState` service, so it must be bound as a class (`@UseGuards(MaintenanceGuard)`) or through `APP_GUARD`; an instance passed to `useGlobalGuards()` would have no service. 2. When maintenance is off it returns `true` and the request continues. 3. During maintenance it reads the HTTP method from `context.switchToHttp().getRequest()` and lets reads through. 4. For a write it throws `ServiceUnavailableException`, so the client sees 503 with the guard's message rather than the generic 403 a `false` would produce. Swap step 4 for `return false` and the same route would answer `{"message":"Forbidden resource","error":"Forbidden","statusCode":403}`, which tells the client the wrong story about why it was refused. ## Habits that keep guards honest - Declare the return type as `boolean` (or its async forms) so the compiler catches a missing `return`. - Keep a guard to one decision; reading the user's identity and checking permissions are separate concerns built on this same surface. - Prefer `APP_GUARD` for a global guard that needs any service at all.

  • What happens if a NestJS guard's canActivate() forgets its return statement?
    It returns `undefined`. Nest awaits a non-boolean result and treats the falsy value as a denial, so the route answers 403 `Forbidden resource` on every call. The opposite slip is quieter: returning a truthy non-boolean, such as the request's user object, lets the request through. Declaring the return type as `boolean` lets the compiler catch both.
  • Why register a global NestJS guard through APP_GUARD rather than app.useGlobalGuards()?
    `useGlobalGuards()` takes an instance you construct outside any module, so Nest cannot inject the guard's dependencies. A provider registered with the `APP_GUARD` token from `@nestjs/core` is built by the container, can inject services, and is global whichever module declares it. Every registered `APP_GUARD` runs, and because it is a pseudo-provider consumed at bootstrap, `app.get()` cannot retrieve it.

Middleware is the receptionist at the building entrance: it checks everyone who walks in but has no idea which office they are heading to. A guard stands at the door of one office, holding that office's own rules, and can turn a visitor away before they reach the desk.

  • A guard returning false makes Nest send a 401 Unauthorized response.
  • A guard must return a plain boolean, so async checks belong in middleware.
  • A guard passed to useGlobalGuards(new Guard()) gets its constructor dependencies injected.
  • Middleware knows which controller method will run, so it can read handler metadata too.
  • An exception thrown inside a guard bypasses the app's exception filters.
open as a page

In a NestJS 12 interceptor, what does CallHandler.handle() return, and how do you time or reshape a handler's result with RxJS?

level: middleimportance: must knowfreq 62%

basics

~20 s

next.handle() returns an RxJS Observable of the route handler's result, and the handler runs only once Nest subscribes to the stream intercept() returns. Code before handle() runs first; operators such as map, finalize and timeout act on the result afterwards.

open as a page

In NestJS 12, how does a guard read metadata from a Reflector.createDecorator decorator, and when do getAllAndOverride and getAllAndMerge differ?

level: middleimportance: should knowfreq 50%

basics

~10 s

Inject Reflector and pass it the decorator plus targets from the ExecutionContext. getAllAndOverride(Dec, [context.getHandler(), context.getClass()]) returns the first defined value, so the method overrides the controller; getAllAndMerge concatenates arrays or shallow-merges objects from both.

open as a page

A NestJS 12 app binds ClassSerializerInterceptor globally and marks UserEntity.password with @Exclude(), yet one endpoint still returns the password; why?

level: seniorimportance: should knowfreq 38%

basics

~20 s

ClassSerializerInterceptor applies class-transformer metadata only to class instances. A handler that returns a plain object, such as a spread {...user} or a raw row, or one that writes through @Res(), escapes @Exclude(), so the password leaks.

open as a page

As a lead on a NestJS 12 codebase, would you standardise response shaping on ClassSerializerInterceptor or the new StandardSchemaSerializerInterceptor, and why?

level: principalimportance: nice to knowfreq 18%

basics

~20 s

Both read @SerializeOptions(). ClassSerializerInterceptor applies class-transformer decorators to class instances, a denylist by default; Nest 12's StandardSchemaSerializerInterceptor runs each response through a schema, and a mismatch is a 500. Choose by where the team's types already live.

open as a page