Kind: Interface
Source: packages/common/interfaces/middleware/middleware-consumer.interface.ts
Part of: Common
Interface defining method for applying user defined middleware to routes.
MiddlewareConsumer defines the API used to register application middleware during module configuration. Its apply() method accepts one or more middleware classes or functions and returns a configuration proxy that can target specific routes, controllers, HTTP methods, or exclusions.
Diagram
mermaidgraph LR A[Module.configure] --> B[MiddlewareConsumer] B --> C[apply Middleware] C --> D[MiddlewareConfigProxy] D --> E[forRoutes / exclude] E --> F[Matched HTTP Routes] F --> G[Middleware Execution] G --> H[Route Handler]
Usage
tsimport { MiddlewareConsumer, Module, NestModule, RequestMethod } from '@nestjs/common';
import { LoggerMiddleware } from './logger.middleware';
import { CatsController } from './cats.controller';
@Module({
controllers: [CatsController],
})
export class CatsModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(LoggerMiddleware)
.exclude({ path: 'cats/health', method: RequestMethod.GET })
.forRoutes(CatsController);
}
}
AI Coding Instructions
- Use
MiddlewareConsumerinside a module'sconfigure()method, typically by implementingNestModule. - Pass middleware classes or compatible middleware functions to
consumer.apply(). - Chain
forRoutes()afterapply()to ensure middleware is attached to intended controllers or route patterns. - Use
exclude()beforeforRoutes()when a middleware should not run for selected endpoints. - Keep middleware registration module-specific when possible; use global middleware only when it truly applies across the application.
Used by
4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example.
Imported by (4)
CoreModule—integration/inspector/src/core/core.module.ts:8AppModule—integration/nest-application/global-prefix/src/app.module.ts:7AppModule—integration/versioning/src/app.module.ts:13MiddlewareBuilder—packages/core/middleware/builder.ts:17
Was this page helpful?