In a NestJS 12 app, a tenant middleware throws UnauthorizedException, but the controller's @UseFilters filter never formats it. Why, and what fixes it?
answer
- middleware runs before a handler is chosen
- which filters exist at that moment
- global only: two registrations
- async use and next(err)
basics
~20 sConsumer-bound middleware runs before Nest has selected a route handler, so only global exception filters apply to its errors; controller-scoped and method-scoped filters are never consulted. Register the formatting filter globally, through APP_FILTER or app.useGlobalFilters().
solid answer
~40 sMiddleware bound through `MiddlewareConsumer` runs before a route handler is selected, so Nest cannot know which controller's `@UseFilters()` would apply. It wraps each middleware with an exceptions handler that has no controller or route context, so of your filters only the **global** ones apply. An `UnauthorizedException` thrown there is formatted by a filter registered with `app.useGlobalFilters()` or the `APP_FILTER` token, or else by the built-in filter, which is why the client sees Nest's default `{"message":"missing tenant","error":"Unauthorized","statusCode":401}` instead of the controller's shape. `@UseFilters()` on the middleware class is not supported either. The fix is to make that filter global. For async work, declare `use()` as `async` or return a promise, or call `next(err)`, so the error reaches the exceptions layer at all.
code
typescript · 20 linesimport { Injectable, Module, NestMiddleware, UnauthorizedException } from '@nestjs/common';
import { APP_FILTER } from '@nestjs/core';
import type { NextFunction, Request, Response } from 'express';
import { HouseFormatFilter } from './house-format.filter.js';
@Injectable()
export class TenantMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
if (!req.headers['x-tenant']) {
// Only global filters see this; @UseFilters on OrdersController does not.
throw new UnauthorizedException('missing tenant');
}
next();
}
}
@Module({
providers: [{ provide: APP_FILTER, useClass: HouseFormatFilter }],
})
export class AppModule {}go deeper
Recall that errors thrown in middleware are handled only by global exception filters, registered with app.useGlobalFilters() or APP_FILTER.
Explain why: middleware runs before a handler is selected, so no controller or method filters exist yet, and @UseFilters on a middleware class is unsupported.
Diagnose from the default body, fix with a global APP_FILTER, and know when a guard is the better home for a check that needs scoped handling.
Set the convention that response formatting lives in one global filter, so no team discovers the middleware gap through a client complaint.
## The symptom A team has a controller-scoped filter that reshapes every error from `OrdersController` into its house format, `{ code, detail, path }`. A `TenantMiddleware`, bound with `consumer.apply(TenantMiddleware).forRoutes(OrdersController)`, throws `UnauthorizedException` when the tenant header is missing. Errors from the handlers come back in the house format; the tenant error comes back as Nest's default body: ```json {"message":"missing tenant","error":"Unauthorized","statusCode":401} ``` The filter is bound to the right controller, the exception is an `HttpException`, and the status is right. Only the shape is wrong. ## Why the scoped filter is skipped Nest's exception filters exist at three scopes: **method** and **controller** (bound with `@UseFilters()`), and **global** (bound with `app.useGlobalFilters()` or an `APP_FILTER` provider). Method and controller scope are attached to a route handler, and a route handler's filters can only be consulted once Nest knows which handler the request is going to. Middleware runs **before a route handler is selected**. When Nest binds a consumer middleware, it wraps the `use()` method in a proxy whose exceptions handler knows the global filters but no controller or route handler, because none has been chosen yet. So: - a filter registered globally sees the middleware's exception; - the built-in filter answers if no global filter claims it; - the controller-scoped and method-scoped filters are never invoked. The docs state it in exactly these terms, and add that binding filters to a middleware class with `@UseFilters()` is not supported. | Filter registration | Sees a handler's error | Sees a consumer middleware's error | |---|---|---| | `@UseFilters()` on the handler | yes | no | | `@UseFilters()` on the controller | yes | no | | `app.useGlobalFilters(new F())` | yes | yes | | `{ provide: APP_FILTER, useClass: F }` | yes | yes | ## How to fix it Pick one of these, in roughly this order: 1. **Make the formatting filter global.** Register it with `APP_FILTER` so it can inject what it needs, or with `app.useGlobalFilters()` if it has no dependencies. Every error, from middleware or handler, then gets the house format. This is usually right anyway: a response format is rarely a property of one controller. 2. **Move the check out of middleware.** A tenant check that throws an authorization error can live in a guard instead. Guards run after the handler is selected, so a scoped filter sees their exceptions, and a guard can read handler metadata. The guard contract itself belongs with the guards material. 3. **Keep the scoped filter, but stop throwing in middleware.** Let the middleware only enrich the request, and let the handler or a guard throw. This is a narrower fix and easy to undo by accident. ## Making sure the error reaches the exceptions layer The global-only rule applies only to errors Nest actually sees. Three habits keep them visible: - **Throw synchronously** from `use()`; the proxy catches it. - **Declare `use()` as `async` or return a promise** when it awaits something; the proxy awaits it, so a rejection is forwarded to the exceptions layer. - **Call `next(err)`** when wrapping callback-style Express middleware that reports failures through its callback. An error thrown inside a callback that fires after `use()` has returned, from a timer for instance, is outside all of these and is not handled by Nest at all. Middleware registered with `app.use()` in `main.ts` is run by the underlying platform rather than Nest's middleware module; the docs recommend throwing from consumer-bound middleware so the exceptions layer processes the error. ## How to diagnose it quickly - Check where the throwing code runs: a `NestMiddleware` class or function bound in `configure()` means only global filters apply. - Add a temporary global filter decorated `@Catch()` that logs and delegates to `BaseExceptionFilter`; if it fires for the request, the error is coming from middleware or from somewhere scoped filters do not cover. - Compare the response body with the default one: an `error` field holding the status phrase means the built-in filter answered, not yours. ## Takeaways - Scoped filters belong to route handlers; middleware has no handler yet. - Anything that must shape every error, including middleware errors, should be a global filter. - An authorization decision that needs scoped error handling or handler metadata is better placed in a guard.
- In NestJS 12, does the same rule apply to an async middleware whose awaited lookup rejects?Yes. If `use()` is declared `async` or returns a promise, Nest's middleware proxy awaits it and forwards the rejection to the exceptions layer, where again only global filters, or the built-in filter, apply. If the middleware starts async work without returning its promise, the rejection escapes the proxy and Nest never sees it.
- Why might moving the tenant check into a guard change which NestJS 12 filter formats its error?A guard runs after Nest has selected the route handler, inside the handler's own exception handling, so method-scoped and controller-scoped filters can claim its exceptions. A guard can also read handler metadata through `Reflector`, which middleware cannot, since no handler exists when middleware runs.
A visitor turned away at the building's front turnstile never reaches the sales department, so the sales department's complaints desk never hears of it; only the building-wide complaints office can. Consumer middleware is the turnstile, scoped filters are the department desk, and global filters are the building-wide office.
- Thinks @UseFilters on the controller covers its route middleware too.
- Proposes putting @UseFilters() directly on the middleware class.
- Believes only app.useGlobalFilters(), not APP_FILTER, reaches middleware errors.
- Assumes Nest catches errors thrown from a timer callback inside middleware.
- Blames the exception class and switches to a plain Error instead.