In a NestJS 12 app, how do global, controller and route bindings order guards and interceptors, and why do interceptors unwind in reverse?
answer
- outer scope first on the way in
- listed order inside one decorator
- next.handle() returns an Observable
- first in, last out
basics
~10 sGuards and interceptors both run global, then controller, then route, and in listed order inside one decorator. Each interceptor wraps the next one's Observable, so their after-phase unwinds route, controller, then global.
solid answer
~40 sWithin a stage Nest runs globally bound components first (registered with `app.useGlobalGuards()` or an `APP_GUARD` provider, and the interceptor equivalents), then those bound by a decorator on the controller class, then those on the method. Inside one `@UseGuards(A, B)` the order is the listed order. Interceptors follow the same order inbound, but each one calls `next.handle()` and gets back an `Observable` that contains everything inside it, so the global interceptor wraps the controller one, which wraps the route one, which wraps the handler. Results and errors therefore come back route, controller, global: first in, last out. Middleware has its own order: `app.use()` middleware first, then module-bound middleware, with `@Global()` modules first, then the root module, then other modules by distance from the root.
code
typescript · 16 lines// main.ts: global bindings
app.useGlobalGuards(new MaintenanceGuard());
app.useGlobalInterceptors(new RequestIdInterceptor());
// invoices.controller.ts: controller and route bindings
@UseGuards(TenantGuard, QuotaGuard)
@UseInterceptors(AuditInterceptor)
@Controller('invoices')
export class InvoicesController {
@UseGuards(OwnerGuard)
@UseInterceptors(TimingInterceptor)
@Get(':id')
findOne(@Param('id') id: string) {
return { id };
}
}go deeper
Remember the phrase global, controller, route for guards, interceptors and pipes, and that guards listed in one decorator run left to right.
Explain the reverse unwinding from the code: next.handle() returns an Observable containing everything inside the interceptor, so the outermost interceptor sees results last.
Use the nesting to debug a global interceptor that logs the wrong error or envelope, and to say which guard may rely on data another guard attached.
Decide which concerns a team binds globally versus per controller, knowing global interceptors wrap everything and route interceptors can mask errors from them.
## Three binding scopes In **NestJS**, a guard, interceptor, pipe or filter is "global", "controller" or "route" depending on **where it is bound**, not on what it does: - **Global**: passed to `app.useGlobalGuards()` (or `useGlobalInterceptors()`, `useGlobalPipes()`, `useGlobalFilters()`), or provided by a module under the `APP_GUARD` token (or `APP_INTERCEPTOR`, `APP_PIPE`, `APP_FILTER`). - **Controller**: listed in a decorator such as `@UseGuards()` placed on the controller class. - **Route**: listed in the same decorator placed on one handler method. ## Inbound order: global, controller, route Nest builds each route's list of guards by concatenating the global list, the class metadata and the method metadata, in that order. The docs give the canonical example: with `@UseGuards(Guard1, Guard2)` on the controller and `@UseGuards(Guard3)` on the method, `Guard1` executes before `Guard2`, and both execute before `Guard3`. A global guard runs before all three. The same rule holds for the inbound side of interceptors and for pipes: - **Guards**: global, then controller, then route; listed order within each decorator. - **Interceptors (before `next.handle()`)**: global, then controller, then route. - **Pipes**: global, then controller, then route, then the pipes on individual parameters. The one component that does **not** start at the global level is the exception filter: Nest consults route filters first, then controller, then global. ## Why interceptors unwind in reverse An interceptor implements `intercept(context, next)`. Calling `next.handle()` returns an RxJS `Observable` that, when subscribed, runs **everything inside this interceptor**: the next interceptor, the pipes and the handler. The interceptor then attaches operators such as `map`, `tap` or `catchError` to that `Observable`. So the chain is nested like this: 1. The global interceptor's inbound code runs and calls `next.handle()`. 2. That runs the controller interceptor's inbound code, which calls `next.handle()`. 3. That runs the route interceptor's inbound code, which calls `next.handle()`, which runs the pipes and the handler. 4. The handler's value flows out through the route interceptor's operators first, then the controller's, then the global one's. The docs call this **first in, last out**: inbound global, controller, route; outbound route, controller, global. An error travels the same outward path, so the route interceptor's `catchError` sees it before the global one does, and if the route interceptor replaces the error, the outer interceptors see only the replacement. ## Middleware has its own ordering rule Middleware is not bound with decorators, so its rule is different: - Globally bound middleware, registered with `app.use()`, runs first. - Module-bound middleware, applied with `MiddlewareConsumer` in a module's `configure()`, runs next, in the order it is bound within that module. - Across modules, middleware from `@Global()` modules runs first, then the root module's, then the other modules' **ordered by their distance from the root module** in the import graph. ## A worked example The code example binds two controller guards in one decorator, a route guard, a global guard, and interceptors at all three levels. The printed trace shows the guards in global, controller (listed order), route order, the interceptors inbound in the same order, and their after-phase reversed. | Component | Inbound order | Outbound order | |---|---|---| | Middleware | `app.use()`, then module-bound | not applicable | | Guards | global, controller, route | not applicable | | Interceptors | global, controller, route | route, controller, global | | Pipes | global, controller, route, parameter | not applicable | ## Common slips - Assuming the most specific binding runs first. That is true only of exception filters; guards, interceptors and pipes start at the global level. - Expecting several guards in one `@UseGuards()` to run concurrently. They run one after another, and the first denial stops the rest. - Treating `app.useGlobalGuards()` and `APP_GUARD` as different scopes. Both are global; they differ in dependency injection and in when they join the global list. ## Why it matters in practice - A global interceptor that maps every response into an envelope runs **last** on the way out, so it wraps whatever a route interceptor has already produced. - A route interceptor that converts an error with `catchError` hides the original from the global interceptor that logs errors. - A controller guard cannot depend on a route guard having run, but a route guard can depend on the controller's guards having passed, for example on a user the controller guard attached to the request.
- In a NestJS 12 app, if a route interceptor turns an error into a different exception with catchError, what does the global interceptor see?Only the replacement. The global interceptor wraps the route interceptor's `Observable`, so it receives whatever that inner `Observable` emits or errors with. If the route interceptor maps a database error to a `BadGatewayException`, a global error-logging interceptor logs the `BadGatewayException`, not the original.
- In a NestJS 12 app, in what order does middleware from different modules run?Middleware registered with `app.use()` runs first. Module-bound middleware follows: `@Global()` modules first, then the root module, then the other modules ordered by their distance from the root module in the import graph. Within one module it runs in the order it is bound.
Interceptors nest like envelopes inside envelopes: the outermost one is opened first on the way in and sealed last on the way out, so the global interceptor sees the request first and the response last.
- Route guards run before controller guards because they are more specific.
- Interceptors run their after-phase in the same order as their before-phase.
- Guards inside one @UseGuards() call run in parallel.
- Global interceptors see the handler's raw result before any route interceptor.