In a NestJS 12 app, in what order do middleware, guards, interceptors, pipes, the handler and exception filters run for one request?
answer
- middleware runs before Nest picks a handler
- authorization decided before anything wraps
- interceptors wrap both directions
- arguments shaped just before the call
- filters only on an uncaught throw
basics
~10 sMiddleware runs first, then guards, then the interceptors' before-phase, then pipes, then the route handler; interceptors then unwind in reverse, and exception filters run only when something along the way throws uncaught.
solid answer
~40 sNest documents a fixed order: middleware (global `app.use()` middleware first, then module-bound middleware applied through `MiddlewareConsumer`), then guards, then interceptors on the way in, then pipes that transform and validate the handler's arguments, then the controller method and whatever services it calls, then interceptors on the way out in reverse order. Exception filters are not a fixed step: they handle an exception nobody caught, and the rest of the pipeline is skipped. So a guard that denies the request means no interceptor, pipe or handler runs, while a `ParseIntPipe` failure happens after the interceptors have started, so they see the error before a filter writes the 400 response.
code
typescript · 52 linesimport {
CallHandler, CanActivate, Controller, ExecutionContext, Get, Injectable, MiddlewareConsumer,
Module, NestInterceptor, NestMiddleware, NestModule, Param, ParseIntPipe, UseGuards, UseInterceptors,
} from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { tap } from 'rxjs';
@Injectable()
class LogMiddleware implements NestMiddleware {
use(req: any, res: any, next: () => void) { console.log('middleware'); next(); }
}
@Injectable()
class GlobalGuard implements CanActivate {
canActivate() { console.log('global guard'); return true; }
}
@Injectable()
class ReportsGuard implements CanActivate {
canActivate() { console.log('controller guard'); return true; }
}
@Injectable()
class TimingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler) {
console.log('interceptor before');
return next.handle().pipe(
tap({ next: () => console.log('interceptor after'), error: () => console.log('interceptor sees error') }),
);
}
}
@UseGuards(ReportsGuard)
@UseInterceptors(TimingInterceptor)
@Controller('reports')
class ReportsController {
@Get(':id')
find(@Param('id', ParseIntPipe) id: number) {
console.log('handler, id is a', typeof id);
throw new Error('report store unavailable');
}
}
@Module({
controllers: [ReportsController],
providers: [{ provide: APP_GUARD, useClass: GlobalGuard }],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(LogMiddleware).forRoutes(ReportsController);
}
}go deeper
Recite the order without hesitation: middleware, guards, interceptors in, pipes, handler, interceptors out, and filters only when something throws uncaught.
Explain why each stage sits where it does: middleware is context-blind, guards read the ExecutionContext, interceptors wrap an Observable, pipes act on the handler's arguments.
Trace what has already run when a guard, a pipe, the handler or a middleware throws, and use that to explain a missing log line or an interceptor that never fired.
Use the order to place team conventions: authorization in guards that never trust unparsed input, cross-cutting timing in interceptors, and one global filter as the error contract.
## The order Nest documents A **NestJS** application wraps every HTTP request in a sequence the framework calls the **request lifecycle**. Each kind of component you can bind has a fixed slot in it: 1. **Middleware**: first globally bound middleware (registered with `app.use()`), then module-bound middleware (applied with `MiddlewareConsumer` in a module's `configure()` method). 2. **Guards**: classes implementing `CanActivate` that decide whether the request may proceed. 3. **Interceptors, inbound**: classes implementing `NestInterceptor`; the code before `next.handle()` runs here. 4. **Pipes**: classes implementing `PipeTransform` that transform or validate each handler argument. 5. **The route handler**: the controller method, plus any service it calls. 6. **Interceptors, outbound**: the RxJS operators each interceptor attached to the `Observable` returned by `next.handle()`, in reverse order. 7. **Exception filters**: classes decorated with `@Catch()`, consulted only when an exception goes uncaught. The docs put it in one line: guards are executed **after** all middleware, but **before** any interceptor or pipe. ## Why each stage sits where it does - **Middleware is context-blind.** It has the platform's `(req, res, next)` shape and does not know which handler will run after it calls `next()`; it runs before Nest has selected a route handler at all. - **Guards see the `ExecutionContext`.** They can read the handler and controller class and their metadata, so they answer "may this request reach this handler?" before any work is done on its behalf. - **Interceptors wrap the call.** An interceptor's `intercept(context, next)` runs code, calls `next.handle()` and gets back an `Observable` of the handler's result. That is how one class can time a request, map its result or translate its error. - **Pipes run last before the call** because they operate on the arguments the handler is about to receive: `@Body()`, `@Param()`, `@Query()` and friends. - **Filters sit outside the happy path.** They are the exceptions layer, not a stage every request passes. ## What happens when something throws As soon as an uncaught exception occurs, the rest of the lifecycle is skipped and the request goes to the exceptions layer. Where it is thrown decides what has already run: - **A guard returns `false`**: Nest throws a `ForbiddenException`. Interceptors, pipes and the handler never run, so a timing interceptor records nothing. - **A pipe throws** (for example `ParseIntPipe` on a non-numeric id): the interceptors' inbound code has already run, and an interceptor's `catchError` (or `tap` error callback) sees the exception. The handler is never called. - **The handler or a service throws**: interceptors see the error on the way out, then a filter answers. A plain `Error` reaches Nest's built-in filter, which replies `500` with `{"statusCode":500,"message":"Internal server error"}`. - **Middleware throws**: guards, interceptors, pipes and the handler never run; the error goes straight to the exceptions layer. Exceptions you catch yourself with `try/catch` never reach a filter. ## A worked trace The first code example binds a global logger-style middleware for one controller, a global guard through `APP_GUARD`, a controller guard, a timing interceptor and `ParseIntPipe` on the `id` parameter, and the handler throws. The second example is what the app prints for two requests. For `/reports/42` every stage runs and the interceptor sees the handler's error. For `/reports/abc` the pipe rejects the id after the interceptor has started, so the handler line never appears and the response is the pipe's `400`. ## Common slips | Belief | What Nest actually does | |---|---| | Validation pipes run before guards | Guards run first; pipes come after the interceptors' inbound code | | Filters run at the end of every request | Filters run only for an uncaught exception | | Interceptors run before guards | Guards run before every interceptor | | A denied request still reaches the interceptors | A guard's denial skips interceptors, pipes and the handler | ## How to confirm the order in your own app - Log one line from each component, as the example does: `use()` in the middleware, `canActivate()` in each guard, before and after `next.handle()` in each interceptor, and the handler. - For the error path, attach a `tap({ error })` or `catchError` operator in an interceptor and log inside the exception filter's `catch()` method. - Send one valid request and one that a pipe rejects; the missing handler line shows exactly where the pipeline stopped. Two practical consequences follow. An interceptor is the wrong place to measure the cost of authorization, because guards have finished before it starts. And a guard cannot rely on a pipe having parsed or validated anything, because pipes have not run yet: a guard reads the raw request.
- In a NestJS 12 app, can a guard rely on a ValidationPipe having validated the request body?No. Guards run before interceptors and pipes, so a guard sees the raw request: an unvalidated body and route parameters still as strings. If authorization depends on a parsed value, the guard has to parse it itself, or the check belongs in the handler or a service after the pipes have run.
- In a NestJS 12 app, does a timing interceptor measure the time spent in guards?No. Every guard has finished before the first interceptor's inbound code runs, and a request a guard denies never reaches the interceptor at all. To time the whole request, including middleware and guards, measure in middleware or at the platform level instead.
- In a NestJS 12 app, the handler throws and an interceptor uses RxJS catchError on next.handle(); does an exception filter still run?Only if the interceptor lets an error out. The handler runs inside the Observable that `next.handle()` returns, so its error reaches the interceptor's outbound code before any filter. If `catchError` returns a value, the request completes normally and no filter runs; if it rethrows, for example with `throwError(() => new BadGatewayException())`, the filter search starts with that new exception.
- Pipes run before guards, so the body is validated before authorization.
- Exception filters run as the last step of every request.
- Interceptors run before guards, so they can time authorization too.
- A guard returning false still lets the interceptors and handler run.
- Middleware can read which handler will run, just as a guard can.