Lesson 209 of 296
Guards, interceptors, pipes and filters, and their order
What you will learn
- Middleware, guards, interceptors, pipes and exception filters
- What each one is for, with examples
- The exact order of the request pipeline
- Global, controller and route scope
- The ExecutionContext and custom decorators
On this page
The request pipeline
Before and after your controller method runs, a request passes through several layers. Each has one job:
| Layer | Job | Typical examples |
|---|---|---|
| Middleware | Raw request processing, before routing details are known | Logging, request IDs, cookies, Helmet security headers, CORS |
| Guard | Can this request continue? Returns true or false | Authentication, roles, permissions, feature flags |
| Interceptor (before) | Run code before the handler, and wrap it | Timing, caching, timeouts, request context |
| Pipe | Validate and transform arguments | Parse "42" to 42, validate the body against a DTO or schema |
| Controller method | The actual work | Call the service |
| Interceptor (after) | Change or observe the result | Wrap responses, serialise, log duration, map errors |
| Exception filter | Turn errors into responses | Consistent error format, logging, mapping database errors |
The order (asked constantly)
Request
→ Middleware (global, then module-bound)
→ Guards (global → controller → route)
→ Interceptors, before part (global → controller → route)
→ Pipes (global → controller → route → parameter)
→ Controller method
→ Interceptors, after part (route → controller → global: reverse order)
→ Exception filters (only if something threw; route → controller → global: the most specific first)
ResponseA memory aid: "My Great Interviewer Probably Can't Imagine Failure": Middleware, Guards, Interceptors, Pipes, Controller, Interceptors, Filters.
Why this order makes sense:
- Guards before pipes: do not waste effort validating a body for a user who is not allowed in.
- Interceptors wrap everything inside, so they can measure the full time including pipes and the handler.
- Filters last: an exception thrown anywhere after middleware (in a guard, pipe, handler or interceptor) is caught by the filters.
Guards
A guard implements canActivate and returns true (continue) or false (Nest responds 403 Forbidden), or throws its own exception (for example UnauthorizedException for 401):
import {
CanActivate,
ExecutionContext,
Injectable,
SetMetadata,
UnauthorizedException
} from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import type { Request } from "express";
export type AuthUser = { id: string; roles: string[] };
export type AuthedRequest = Request & { user?: AuthUser };
export const ROLES_KEY = "roles";
export const Roles = (...roles: string[]) => SetMetadata(ROLES_KEY, roles);
@Injectable()
export class AuthGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest<AuthedRequest>();
const header = request.headers.authorization ?? "";
const token = header.startsWith("Bearer ") ? header.slice(7) : "";
if (token === "admin-token") request.user = { id: "u1", roles: ["admin"] };
else if (token === "staff-token") request.user = { id: "u2", roles: ["staff"] };
else throw new UnauthorizedException("Sign in required");
return true;
}
}
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const required = this.reflector.getAllAndOverride<string[] | undefined>(ROLES_KEY, [
context.getHandler(),
context.getClass()
]);
if (!required || required.length === 0) return true;
const user = context.switchToHttp().getRequest<AuthedRequest>().user;
return !!user && required.some((role) => user.roles.includes(role));
}
}- The token check is simplified for the example. A real
AuthGuardverifies a JWT or a session (Lesson 200), often with@nestjs/passportor your own code. @Roles("admin")stores metadata on a route;RolesGuardreads it with the Reflector.getAllAndOverridechecks the method first, then the class.ExecutionContextgives access to the request, the handler and the class, and works for HTTP, WebSockets and microservices (switchToWs(),switchToRpc()).- Remember Lesson 203: guards check who and which role; ownership checks ("is this your invoice?") belong in the service, where the record is loaded.
Interceptors
An interceptor wraps the handler. It uses RxJS observables: next.handle() runs the rest of the pipeline and returns an observable of the result:
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from "@nestjs/common";
import { map, tap, type Observable } from "rxjs";
import type { Response } from "express";
@Injectable()
export class TimingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
const started = performance.now();
const response = context.switchToHttp().getResponse<Response>();
return next.handle().pipe(
tap(() => response.setHeader("Server-Timing", `app;dur=${(performance.now() - started).toFixed(1)}`))
);
}
}
@Injectable()
export class WrapDataInterceptor implements NestInterceptor {
intercept(_context: ExecutionContext, next: CallHandler): Observable<{ data: unknown }> {
return next.handle().pipe(map((data: unknown) => ({ data })));
}
}Uses: logging and timing, wrapping responses in { data }, caching (CacheInterceptor), timeouts (timeout() from RxJS), serialisation (removing fields such as password hashes).
Pipes
A pipe transforms a value or throws if it is invalid (Nest responds 400):
@Get(":id")
findOne(@Param("id", ParseIntPipe) id: number) {} "42" becomes 42; "abc" gives 400Built-in pipes: ParseIntPipe, ParseUUIDPipe, ParseBoolPipe, ParseEnumPipe, DefaultValuePipe, ValidationPipe (class-validator DTOs), and in NestJS 12 StandardSchemaValidationPipe (Zod and other Standard Schema libraries). Validation is Lesson 210.
Exception filters
Nest has a built-in global filter that turns HttpExceptions into JSON ({ "statusCode": 404, "message": "...", "error": "Not Found" }) and unknown errors into a generic 500 (without leaking details). A custom filter changes the format, for example to Problem Details (Lesson 196):
import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus } from "@nestjs/common";
import type { Request, Response } from "express";
@Catch()
export class ProblemDetailsFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const status = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;
const title =
exception instanceof HttpException && status < 500 ? exception.message : "Something went wrong";
if (status >= 500) console.error(exception);
response
.status(status)
.type("application/problem+json")
.json({ type: "about:blank", title, status, instance: request.url });
}
}@Catch() with no arguments catches everything; @Catch(PrismaClientKnownRequestError) would catch only that type (for example to turn a unique-constraint error into 409).
Binding: global, controller, route
app.useGlobalGuards(...); app.useGlobalInterceptors(...); app.useGlobalPipes(...); app.useGlobalFilters(...);
@UseGuards(AuthGuard, RolesGuard) on a controller class or a method
@UseInterceptors(TimingInterceptor)
@UsePipes(...)
@UseFilters(...)Global enhancers registered with app.useGlobal...() are created outside the DI container, so they cannot inject providers. To make a global guard that can inject (for example the Reflector), register it in a module: providers: [{ provide: APP_GUARD, useClass: RolesGuard }] (likewise APP_INTERCEPTOR, APP_PIPE, APP_FILTER).
Custom parameter decorators
Instead of reading req.user in every controller:
import { createParamDecorator, type ExecutionContext } from "@nestjs/common";
export const CurrentUser = createParamDecorator((_data: unknown, context: ExecutionContext) => {
return context.switchToHttp().getRequest<AuthedRequest>().user;
});Then getProfile(@CurrentUser() user: AuthUser).
Putting it together
import { Controller, Get, UseGuards, UseInterceptors } from "@nestjs/common";
@Controller("admin")
@UseGuards(AuthGuard, RolesGuard)
@UseInterceptors(TimingInterceptor, WrapDataInterceptor)
export class AdminController {
@Get("stats")
@Roles("admin")
stats(@CurrentUser() user: AuthUser) {
return { requestedBy: user.id, orders: 42 };
}
@Get("me")
me(@CurrentUser() user: AuthUser) {
return { id: user.id };
}
}| Request | Result |
|---|---|
| No token | 401 from AuthGuard (the handler never runs) |
staff-token to /admin/stats | 403 from RolesGuard |
staff-token to /admin/me | 200 { "data": { "id": "u2" } } (no @Roles, so any signed-in user) |
admin-token to /admin/stats | 200 { "data": { ... } } plus a Server-Timing header |
How to say it in an interview
"A Nest request goes through middleware, then guards, then the before part of interceptors, then pipes, then the controller, then the after part of interceptors in reverse order, and exception filters handle anything thrown along the way, most specific first. Guards decide whether a request may continue, for authentication and roles, usually reading route metadata with the Reflector. Interceptors wrap the handler with RxJS for timing, response mapping, caching and timeouts. Pipes validate and transform arguments, and filters turn exceptions into a consistent error format. Global enhancers registered with useGlobal cannot inject dependencies, so I register them with APP_GUARD and similar tokens when they need DI."
Key words
| Word | Meaning |
|---|---|
| Middleware | Code that runs on the raw request first |
| Guard | Decides whether a request may continue (canActivate) |
| Interceptor | Wraps the handler; runs before and after it |
| Pipe | Validates and transforms arguments |
| Exception filter | Turns exceptions into responses |
| ExecutionContext | Gives access to the request, handler and class |
| Reflector | Reads metadata set by decorators |
| APP_GUARD | Token to register a global guard that can use DI |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.