Suggest an editImprove this articleRefine the answer for “What is Middleware in NestJS?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)Middleware is a function or class that runs before a request reaches the controller: it has access to `req`, `res`, and `next()`; in NestJS it's implemented as a function (like in Express) or a class implementing `NestMiddleware`, mounted in a module via `configure()`/`MiddlewareConsumer` rather than automatically. **Key point:** middleware works at the HTTP level before Nest even reaches the controller (logging, tokens, CORS), while Guards and Interceptors already run inside Nest's context (with metadata, DI, decorators) - before and after the handler call, respectively.Shown above the full answer for quick recall.Answer (EN)Image## 1. What Middleware is in NestJS > **Middleware** is a function (or a class) > that **runs before a request reaches the controller**. It has access to: - `req` (the incoming request), - `res` (the response), - and the `next()` function, to pass execution further along the chain. So middleware is an **HTTP-level "filter"** that all (or some) requests pass through. ## 2. Middleware's signature In NestJS, middleware can be: 1. A **function**, like in Express; 2. A **class** implementing the `NestMiddleware` interface. An example of a simple functional middleware: ```javascript import { Request, Response, NextFunction } from 'express'; export function logger(req: Request, res: Response, next: NextFunction) { console.log(`${req.method} ${req.url}`); next(); // must call next() } ``` ## 3. A middleware class (the recommended approach) ```javascript import { Injectable, NestMiddleware } from '@nestjs/common'; import { Request, Response, NextFunction } from 'express'; @Injectable() export class LoggerMiddleware implements NestMiddleware { use(req: Request, res: Response, next: NextFunction) { console.log(`Request... ${req.method} ${req.url}`); next(); } } ``` Class injection (`@Injectable`) lets it use dependencies, such as services (`AuthService`, `ConfigService`, `Logger`, etc.). ## 4. Mounting middleware Middleware **isn't registered automatically**, it needs to be declared in a module via the `configure()` method. ```javascript import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common'; import { LoggerMiddleware } from './logger.middleware'; import { UsersController } from './users.controller'; @Module({ controllers: [UsersController], }) export class UsersModule implements NestModule { configure(consumer: MiddlewareConsumer) { consumer .apply(LoggerMiddleware) // specify the middleware .forRoutes(UsersController); // apply it to a specific controller or path } } ``` ## 5. MiddlewareConsumer's methods | Method | Description | |---|---| | `.apply(...middlewares)` | Specify one or more middleware | | `.forRoutes(...routes)` | Apply to routes or controllers | | `.exclude(...paths)` | Exclude routes from applying it | Example: ```javascript consumer .apply(AuthMiddleware, LoggerMiddleware) .exclude('auth/login', 'auth/register') .forRoutes('users', 'orders'); ``` ## 6. Where middleware is used in NestJS | Scenario | Example | |---|---| | Authentication / token decoding | Checking a JWT from a header | | Request logging | Recording the method, URL, timing | | Caching | Checking/writing a response in Redis | | Localization | Setting the language from headers | | Rate limiting / IP filtering | Protecting the API from spam | | Tracing / metrics | Sending data to Prometheus, Sentry, Datadog | ## 7. Middleware vs Guards vs Interceptors These three mechanisms are similar, but run at **different levels**: | Mechanism | Level | When it runs | Use | |---|---|---|---| | Middleware | HTTP (before Nest) | Before the controller (Express/HTTP level) | Logging, tokens, parsing, CORS | | Guards | Nest level | Before the route handler runs | Checking permissions, roles, authorization | | Interceptors | Nest level | Before and after calling the handler | Transforming the response, timing, caching | That is: - **Middleware** runs before Nest even reaches the controller; - **Guards/Interceptors** already run inside Nest's context (with metadata, DI, decorators, etc.). ## Summary > **Middleware in NestJS** is functions or classes > that run **before the controller processes the request**, > letting you: > > - log, modify, check, or reject requests, > - add data to `req`, > - or perform other tasks "before" the Nest pipeline. The key facts: - Implemented via `NestMiddleware` or a plain function; - Mounted in a module via `MiddlewareConsumer`; - Runs **before** Guards, Interceptors, and Pipes; - Used for **low-level HTTP logic** (not business logic).For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.