@Injectable()
export class LoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
console.log(req.method, req.originalUrl);
next();
}
}
@Module({})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(LoggerMiddleware).exclude("health").forRoutes(CatsController);
}
}
Write a class that implements NestMiddleware, then register it in the module's configure() method.
Writing it. The class has a use(req, res, next) method. It must call next() or end the response. Otherwise the request hangs. The class is @Injectable(), so it can inject providers from its module. When there are no dependencies, a plain function with the same signature also works.
Registering it. You don't list middleware in @Module(). Instead, the module implements NestModule. In its configure() method you use MiddlewareConsumer:
apply()takes one or more middleware.forRoutes()takes paths, route objects with HTTP methods, or controllers.exclude()skips some routes.
For middleware on every route, you can also call app.use() in main.ts. But that version can't use DI (dependency injection).
- Implement
NestMiddleware.use(req, res, next). - Middleware must call
next()or end the response. - Register it in the
configure(consumer)method of aNestModule. - Use
apply().forRoutes()to pick routes andexclude()to skip some. - Use
app.use()for global function middleware without DI.
Read more
- Middleware (https://docs.nestjs.com/middleware)docs.nestjs.com