What is Middleware in NestJS?
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:
- A function, like in Express;
- A class implementing the
NestMiddlewareinterface.
An example of a simple functional middleware:
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)
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.
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:
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
NestMiddlewareor a plain function; - Mounted in a module via
MiddlewareConsumer; - Runs before Guards, Interceptors, and Pipes;
- Used for low-level HTTP logic (not business logic).
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.