02 / 03

What is middleware in NestJS and how does it differ from Express middleware?

NestJS middleware is functionally equivalent to Express middleware — it has access to req, res, and next(). The key difference is that NestJS middleware can be a class implementing NestMiddleware decorated with @Injectable(), giving it full access to the DI container. Functional middleware is still supported for simple stateless cases.

Class-based middleware with DI
NestJS middleware vs Express middleware:
  1. 1

    Express middleware — plain functions, no DI, registered with app.use().

  2. 2

    NestJS class middleware — @Injectable() class, full DI support, applied via configure().

  3. 3

    NestJS functional middleware — plain function, no DI, lighter weight for simple cases.

  4. 4

    Both must call next() to pass control to the next handler or the request will hang.

  5. 5

    NestJS middleware runs before routing — it has no knowledge of which controller handles the request.