In a NestJS 12 app, how do you bind a class middleware to some routes with MiddlewareConsumer, and when is functional middleware enough?
answer
- not in the module decorator
- a module that implements one interface
- apply, then exclude, then forRoutes
- no dependencies, no class
basics
~10 sMake the module implement NestModule and, in configure(consumer), call consumer.apply(TenantMiddleware).forRoutes(OrdersController), optionally with exclude() first. A plain function is enough when the middleware needs no injected dependencies.
solid answer
~40 sA class middleware is an `@Injectable()` class implementing `NestMiddleware`, whose `use(req, res, next)` must call `next()` or end the response. It is not listed in `@Module()`: the module implements `NestModule` and binds it in `configure(consumer: MiddlewareConsumer)` with `consumer.apply(TenantMiddleware).forRoutes(OrdersController)`. `forRoutes()` takes path strings such as `'orders/*splat'`, controller classes or `{ path, method: RequestMethod.GET }` objects, and `exclude()` called before it carves routes out. A class middleware can inject providers of its module. **Functional middleware**, a plain `(req, res, next)` function, is enough when it needs no dependencies, and it is the right form for `app.use()` in `main.ts`, which runs outside the DI container.
code
typescript · 27 linesimport { Injectable, MiddlewareConsumer, Module, NestMiddleware, NestModule, RequestMethod } from '@nestjs/common';
import type { NextFunction, Request, Response } from 'express';
import { OrdersController } from './orders.controller.js';
import { TenantsService } from './tenants.service.js';
@Injectable()
export class TenantMiddleware implements NestMiddleware {
constructor(private readonly tenants: TenantsService) {}
use(req: Request, res: Response, next: NextFunction) {
res.locals.tenant = this.tenants.fromHost(req.hostname);
next();
}
}
@Module({
controllers: [OrdersController],
providers: [TenantsService],
})
export class OrdersModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(TenantMiddleware)
.exclude({ path: 'orders/health', method: RequestMethod.GET })
.forRoutes(OrdersController);
}
}go deeper
Recall the pieces: NestMiddleware with use(req, res, next), a module implementing NestModule, and consumer.apply(...).forRoutes(...) inside configure().
Explain how forRoutes accepts paths, controllers and RouteInfo objects, why exclude comes first, and why app.use middleware gets no injection.
Show you choose middleware only for work that needs no handler metadata, and keep global middleware light and dependency-free unless bound through a module.
Decide which cross-cutting concerns a team puts in middleware versus guards or interceptors, and where global middleware is registered so it stays discoverable.
## What Nest middleware is In NestJS, **middleware** is code that runs before the route handler for the routes it is bound to. With the default Express adapter, Nest middleware is equivalent to Express middleware: it receives the request, the response and a `next` function, and it must either call `next()` or end the response, or the request is left hanging. Nest adds two things on top: **class middleware** that can use dependency injection, and a **binding API**, `MiddlewareConsumer`, that attaches middleware to routes from inside a module. ## Two forms of middleware **Class middleware** is a class decorated `@Injectable()` that implements the `NestMiddleware` interface from `@nestjs/common`: ```typescript @Injectable() export class TenantMiddleware implements NestMiddleware { constructor(private readonly tenants: TenantsService) {} use(req: Request, res: Response, next: NextFunction) { // resolve the tenant, then continue next(); } } ``` Its constructor can inject any provider available in the module that binds it, exactly like a controller or a service. **Functional middleware** is a plain function with the `(req, res, next)` signature and no class around it. The docs recommend it whenever the middleware has no dependencies. | | Class middleware | Functional middleware | |---|---|---| | Shape | `@Injectable()` class with `use()` | a plain function | | Dependency injection | yes, from its module | no | | Bound with | `MiddlewareConsumer` | `MiddlewareConsumer` or `app.use()` | | Typical use | needs a service or config | logging, a header, a third-party middleware | ## Binding with MiddlewareConsumer Middleware is **not** declared in the `@Module()` decorator. Instead the module class implements `NestModule`, whose single method `configure(consumer: MiddlewareConsumer)` Nest calls during startup. The consumer has a fluent API: 1. `apply(...middleware)` names one or more middleware, classes or functions; several run in the order listed. 2. `exclude(...routes)` optionally removes routes, by path string or `RouteInfo` object, and supports wildcards. 3. `forRoutes(...routes)` says where it applies: path strings, controller classes, or `{ path, method }` objects using the `RequestMethod` enum. ```typescript export class OrdersModule implements NestModule { configure(consumer: MiddlewareConsumer) { consumer .apply(TenantMiddleware) .exclude({ path: 'orders/health', method: RequestMethod.GET }) .forRoutes(OrdersController); } } ``` A few details: - `exclude()` comes **before** `forRoutes()`; `forRoutes()` returns the consumer, which has only `apply()`. - Path strings follow the router's wildcard syntax: `'orders/*splat'` matches `orders/1` and `orders/1/items` but not `orders/` itself, while `'orders/{*splat}'` also matches the bare prefix. - A `{ path, method: RequestMethod.GET }` entry restricts the middleware to one HTTP method. - `configure()` may be `async` if it needs to await something first. - With the Express adapter, Nest registers the JSON and URL-encoded body parsers itself; to configure parsers through the consumer you pass `bodyParser: false` to `NestFactory.create()`. ## What the middleware receives On the Express adapter, `req`, `res` and `next` are the Express objects themselves, so anything an Express middleware can do works here: read headers, set `res.locals`, end the response early with `res.status(...).json(...)`. That is also why existing Express middleware, such as a CORS or security-headers package, can be passed straight to `apply()`. On the Fastify adapter the signatures differ, and the docs point to the Fastify chapter for the details. Errors are part of the contract too. A class or functional middleware bound through the consumer can throw an `HttpException`, return a rejected promise from an `async use()`, or call `next(err)`; all three reach Nest's exceptions layer. ## Global middleware To run middleware for every route there are two choices: - `app.use(logger)` in `main.ts`, on the application instance. This middleware is handled by the underlying platform rather than Nest's middleware module and **cannot access the DI container**, so use functional middleware there. - A class middleware bound with `.forRoutes('*')` inside a module, which keeps injection. ## Choosing the form - Needs a service, a repository or configuration: class middleware bound through the consumer. - Needs nothing: a function, bound through the consumer for some routes or with `app.use()` for all. - Needs route metadata, such as a decorator on the handler: that is a guard's or an interceptor's job, not middleware's, because middleware runs before a handler is chosen. ## Common mistakes - Adding the middleware class to `providers` and expecting it to run; providers are never applied to routes on their own. - Forgetting `implements NestModule`, or placing `exclude()` after `forRoutes()`. - Forgetting to call `next()`, which stalls every matching request.
- In NestJS 12, how do you run two middleware on the same routes in a fixed order?Pass both to one `apply()` call, `consumer.apply(cors(), TenantMiddleware).forRoutes(OrdersController)`; they run sequentially in the order listed. Classes and functions can be mixed in the same list.
- In a NestJS 12 app, how do you make a class middleware that needs a service apply to every route?Bind it inside a module with `consumer.apply(TenantMiddleware).forRoutes('*')`. Registering it with `app.use()` would not work for a class that needs injection, because middleware registered on the application instance cannot reach the DI container.
- Lists the middleware class in @Module providers and expects it to run.
- Calls exclude() after forRoutes() on the middleware consumer.
- Registers an injectable class middleware through app.use() in main.ts.
- Writes a middleware use() method that never calls next().