Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 42 ยท The Request Pipeline

Middleware

Learn NestJS middleware: class and functional middleware, consumer.apply with forRoutes and exclude, execution order, and when guards or interceptors fit better.

Middleware is code that runs before a route handler. It receives the raw request and response plus a next function, and it can inspect or change them, end the request early, or hand control to the next piece with next(). Nest middleware is the same idea as Express middleware, so anything you know from Express carries over.

In Nest, middleware is the very first stage of the request pipeline. That position is both its strength and its limit: it is perfect for generic, route-agnostic work (request ids, logging, parsing, CORS, compression) and a poor place for logic that needs to know which controller or handler will run. For that, Nest gives you guards, pipes and interceptors, which this chapter covers next.

Real Nest code needs Node and npm, so the snippets below are read-only. The runnable parts are small stand-ins that reproduce how a middleware chain, route matching and ordering behave.

Middleware in one picture

Request in Raw req and res objects.
Chain Each one calls next().
Handler Reached only if all pass.

Forget next() and the request hangs.

1 / 2

Where middleware sits

flowchart LR
  A["Request"] --> B["Middleware"]
  B --> C["Guards"]
  C --> D["Interceptors (before)"]
  D --> E["Pipes"]
  E --> F["Route handler"]
  F --> G["Interceptors (after)"]
  G --> H["Exception filters on error"]
  H --> I["Response"]

Middleware runs first. Guards, interceptors, pipes and filters come later and know which handler is running.

Because middleware runs before guards, it cannot know whether the user is allowed in, and it has no access to the handler's metadata. Keep that in mind when you choose where to put code.

Functional middleware

The simplest middleware is a function with the Express signature:

TypeScript
import { Request, Response, NextFunction } from 'express';

export function requestId(req: Request, res: Response, next: NextFunction) {
  const id = req.header('x-request-id') ?? crypto.randomUUID();
  res.setHeader('x-request-id', id);
  next();
}

Use a function when the middleware needs no dependencies. It can also be registered globally in main.ts:

TypeScript
const app = await NestFactory.create(AppModule);
app.use(requestId);

app.use() accepts only functional middleware. It is created outside the dependency injection container, so it cannot receive injected services.

Class middleware

When the middleware needs a service (a logger, a config object, a token verifier), write a class with @Injectable() that implements NestMiddleware. Nest instantiates it through the injector, so its constructor can take providers like any other class:

TypeScript
import { Injectable, NestMiddleware } from '@nestjs/common';

@Injectable()
export class AccessLogMiddleware implements NestMiddleware {
  constructor(private readonly logger: AppLogger) {}

  use(req: Request, res: Response, next: NextFunction) {
    const started = Date.now();
    res.on('finish', () => {
      this.logger.log(`${req.method} ${req.originalUrl} ${res.statusCode} ${Date.now() - started}ms`);
    });
    next();
  }
}

The finish event is the right place to log the status code: at the time use runs the response does not exist yet.

Registering with consumer.apply

Middleware is not listed in the @Module() decorator. Instead the module implements NestModule and a configure method:

TypeScript
import { MiddlewareConsumer, Module, NestModule, RequestMethod } from '@nestjs/common';

@Module({ controllers: [CatsController] })
export class CatsModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(AccessLogMiddleware)
      .exclude({ path: 'cats/health', method: RequestMethod.GET })
      .forRoutes(CatsController);
  }
}

forRoutes accepts several kinds of target:

Argument Matches
'cats' A path string (the global prefix, if you set one, is applied)
{ path: 'cats', method: RequestMethod.GET } One path and one HTTP method
CatsController Every route of that controller
'*' or a wildcard pattern Everything or a pattern. Wildcard syntax has changed between Nest versions, so check the docs of the version you use

exclude takes the same kind of route objects and removes them from the match. apply accepts several middleware at once, and they run in the order you list them:

TypeScript
consumer.apply(requestId, AccessLogMiddleware, cookieParser()).forRoutes('*');

Third-party Express middleware such as helmet() or cookie-parser is used the same way. Separate apply calls in the same configure method are also applied in the order you write them.

Order and short-circuiting

A middleware chain behaves like a relay race: each runner decides whether to pass the baton. Three outcomes are possible:

  1. Call next(): the request continues.
  2. Send a response (for example res.status(429).json(...)) and do not call next(): the chain stops and nothing later runs, including the handler.
  3. Do neither: the request hangs until the client gives up. This is the classic middleware bug.

Order matters when one middleware prepares something another uses. A request id must be created before the logger that prints it. Global app.use() middleware runs before module middleware.

Middleware, guards, interceptors: which one?

Need Best place
Add a header, set a request id, parse cookies, log every request Middleware
Decide whether the caller may reach this handler Guard
Convert or validate incoming arguments Pipe
Wrap the handler: timing, response shaping, caching Interceptor
Turn errors into responses Exception filter

The rule of thumb: if the code needs to know which handler is about to run, or what metadata it carries, middleware is the wrong tool. Guards and interceptors get an ExecutionContext that exposes exactly that.

One more difference: with the Fastify adapter, middleware receives Fastify's raw Node request and response objects, not Express ones, so Express-only middleware may not work unchanged. See Deployment and Performance.

Stand-in: a middleware chain with route matching

This is not Nest's implementation. It is a small dispatcher with an apply().exclude().forRoutes() style API, so you can see matching and order. The "request" is a plain object and the "response" collects what was written.

JS A tiny middleware consumer

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that /health skips both middleware (no header, no log line) because of exclude, while /dogs still passes through them before the router finds nothing.

Stand-in: short-circuiting and order

The second stand-in shows what happens when a middleware stops the chain, and why order matters. A rate limit and a body check both answer without calling next(). Everything is synchronous, so the output is deterministic.

JS Short-circuits and ordering

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The rate-limited request never reaches needsJson or the handler. In the reversed order the same request is rejected for its content type first (415 instead of 429), so the order you list middleware in changes the responses clients see.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which kind of middleware can receive injected providers in its constructor?

    Class middleware is created by Nest's injector, so it can take dependencies. Functions given to app.use() live outside the container.
  2. 2. A middleware neither sends a response nor calls next(). What happens to the request?

    Nothing moves the request forward and nothing answers it, so it stays open. Always call next() or end the response.
  3. 3. Where do you register class middleware for a module?

    @Module() has no middleware property. You implement NestModule and call consumer.apply(...).forRoutes(...).
  4. 4. You need to allow a request only for users with the admin role, based on metadata on the handler. What is the best fit?

    Guards receive an ExecutionContext that exposes the handler and its metadata, which middleware cannot see.

Summary

  • Middleware runs first in the pipeline, with raw request and response objects and a next function.
  • Use functional middleware for simple, dependency-free work (also usable with app.use()); use an @Injectable() class when you need injection.
  • Register module middleware in configure(consumer) with apply, exclude and forRoutes; listed middleware runs in order.
  • Always call next() or end the response; otherwise the request hangs.
  • If the code must know the handler or its metadata, use a guard, pipe or interceptor instead.

Continue with Pipes and Validation to see how incoming data is converted and checked.