Middleware thực thi trước Guards, có access vào raw req/res/next giống Express. Dùng cho logging, CORS, session, body parsing, request tracking.
Functional middleware là function đơn giản (req, res, next) => { next() } — dùng khi không cần DI. Class middleware implement NestMiddleware với method use(req, res, next) và @Injectable() — dùng khi cần inject services.
Apply middleware trong module implements NestModule với configure(consumer: MiddlewareConsumer). consumer.apply(Middleware).forRoutes('*') apply cho tất cả. .forRoutes({ path: 'users', method: RequestMethod.GET }) hoặc .forRoutes(UsersController) cho specific routes/controllers. .exclude() loại trừ routes cụ thể. Có thể chain nhiều middleware: .apply(M1, M2, M3). Global middleware (Express-style) dùng app.use(helmet(), cors(), express.json()) trong main.ts trước khi listen.