Skip to main content

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:

  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() }
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

MethodDescription
.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

ScenarioExample
Authentication / token decodingChecking a JWT from a header
Request loggingRecording the method, URL, timing
CachingChecking/writing a response in Redis
LocalizationSetting the language from headers
Rate limiting / IP filteringProtecting the API from spam
Tracing / metricsSending data to Prometheus, Sentry, Datadog

7. Middleware vs Guards vs Interceptors

These three mechanisms are similar, but run at different levels:

MechanismLevelWhen it runsUse
MiddlewareHTTP (before Nest)Before the controller (Express/HTTP level)Logging, tokens, parsing, CORS
GuardsNest levelBefore the route handler runsChecking permissions, roles, authorization
InterceptorsNest levelBefore and after calling the handlerTransforming 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).

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.