Official NestJS documentation on middleware, covering the NestMiddleware interface, MiddlewareConsumer, functional middleware, route matching, and global middleware registration.

Key takeaways

  • Nest middleware is equivalent to Express middleware: functions that run before the route handler, with access to req, res, and next(). They can execute code, modify request/response, end the request-response cycle, or pass control to the next middleware.
  • Class-based middleware implements NestMiddleware with a use(req, res, next) method and is decorated with @Injectable(). It fully supports dependency injection.
  • Middleware is not configured in @Module() — instead, the module class implements NestModule and defines a configure(consumer: MiddlewareConsumer) method.
  • The MiddlewareConsumer provides a fluent API: .apply(Middleware).forRoutes(paths/controllers) and .exclude(routes) for selective application.
  • forRoutes() accepts strings, RouteInfo objects, controller classes, or wildcards (abcd/*splat). exclude() also supports wildcard patterns.
  • Functional middleware: Simple middleware without dependencies can be written as plain functions (req, res, next) => void instead of classes.
  • Global middleware: app.use(middleware) from INestApplication applies to all routes, but does not support DI. For DI-enabled global middleware, use .forRoutes('*') inside a module’s configure() method.
  • Express adapter auto-registers json and urlencoded body parsers; customize via bodyParser: false in NestFactory.create().
  • configure() can be async for asynchronous setup.

Entities and concepts

Connections to existing knowledge

Middleware in NestJS occupies a different position from Pipes and Exception Filters. While pipes have access to execution context (argument metadata) and operate just before the handler, middleware runs earlier in the request lifecycle and lacks context awareness. This is why NestJS Pipes notes that middleware cannot replace pipes for validation — middleware doesn’t know which handler or parameters are involved. Middleware is better suited for cross-cutting concerns like logging, CORS, and body parsing that don’t need route-specific context.