In NestJS, you can use Express middleware at the module, controller, or individual route level. NestJS is fundamentally built on top of Express (by default, but Fastify can also be used), so you can directly leverage Express middleware. Here are some approaches for implementing Express route-specific middleware:
Global Middleware
To apply middleware across the entire application, register it globally in the main.ts file:
typescriptimport { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import * as helmet from 'helmet'; // A security middleware async function bootstrap() { const app = await NestFactory.create(AppModule); app.use(helmet()); // Apply helmet middleware globally await app.listen(3000); } bootstrap();
Module-Level Middleware
At the Module level, implement the NestModule interface and configure middleware in the configure method:
typescriptimport { Module, NestModule, MiddlewareConsumer } from '@nestjs/common'; import { loggerMiddleware } from './logger.middleware'; @Module({ // ... other configuration such as controllers and providers }) export class AppModule implements NestModule { configure(consumer: MiddlewareConsumer) { consumer .apply(loggerMiddleware) .forRoutes('cats'); // Apply middleware exclusively to the 'cats' route } }
Controller-Level Middleware
For middleware limited to specific routes within a controller, configure it in the controller's constructor:
typescriptimport { Controller, Get, UseMiddleware } from '@nestjs/common'; @Controller('cats') export class CatsController { @Get() @UseMiddleware(loggerMiddleware) // Apply middleware using decorator findAll() { // ... route handling logic } }
Note that the @UseMiddleware decorator is not an official NestJS API; this is for illustrative purposes only. In NestJS, you can use @UseGuards, @UseInterceptors, @UsePipes, and @UseFilters for related functionality. For middleware, it's typically registered at the Module level via the configure method. However, if you need to directly integrate Express middleware within route handlers, use this approach:
typescriptimport { Controller, Get, Req, Res, Next } from '@nestjs/common'; import { Request, Response, NextFunction } from 'express'; @Controller('cats') export class CatsController { @Get() findCat(@Req() req: Request, @Res() res: Response, @Next() next: NextFunction) { loggerMiddleware(req, res, next); // ... after invoking next(), route handling logic continues } }
By applying these methods, you can implement Express route-specific middleware at appropriate hierarchical levels in your NestJS application. Always consider middleware scope and execution order to ensure application security and efficiency.