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, andnext(). They can execute code, modify request/response, end the request-response cycle, or pass control to the next middleware. - Class-based middleware implements
NestMiddlewarewith ause(req, res, next)method and is decorated with@Injectable(). It fully supports dependency injection. - Middleware is not configured in
@Module()— instead, the module class implementsNestModuleand defines aconfigure(consumer: MiddlewareConsumer)method. - The
MiddlewareConsumerprovides a fluent API:.apply(Middleware).forRoutes(paths/controllers)and.exclude(routes)for selective application. forRoutes()accepts strings,RouteInfoobjects, 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) => voidinstead of classes. - Global middleware:
app.use(middleware)fromINestApplicationapplies to all routes, but does not support DI. For DI-enabled global middleware, use.forRoutes('*')inside a module’sconfigure()method. - Express adapter auto-registers
jsonandurlencodedbody parsers; customize viabodyParser: falseinNestFactory.create(). configure()can beasyncfor 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.