Request lifecycle, guards, and interceptors
12.6.0
Nest runs different types of handlers before and after a controller. Put each job at the stage that fits it.
On this page
Follow a request to the controller
A typical request goes through middleware, guards, the incoming side of interceptors, and then pipes before the handler. The response returns through interceptors. An uncaught exception can be handled by exception filters.
import {
Controller, Get, Param, ParseIntPipe, UseGuards, UseInterceptors
} from "@nestjs/common";
import { SessionGuard } from "./session.guard";
import { TimingInterceptor } from "./timing.interceptor";
// Request: middleware -> guard -> interceptor -> pipe -> handler
// Response: handler -> interceptor -> client
@UseGuards(SessionGuard)
@UseInterceptors(TimingInterceptor)
@Controller("products")
export class ProductsController {
@Get(":id")
findOne(@Param("id", ParseIntPipe) id: number) {
return { id };
}
}
Parse a route parameter at the boundary
Use ParseIntPipe to turn a route parameter into an integer and reject invalid input. A guard decides whether a handler can run. Use an interceptor for logic that wraps the handler, such as timing or response mapping.
import { Controller, Get, Param, ParseIntPipe } from "@nestjs/common";
@Controller("products")
export class ProductsController {
@Get(":id")
read(@Param("id", ParseIntPipe) id: number) {
return { id };
}
}