CodePark/ questions / Middleware & request lifecycle
START PRACTICINGPRACTICE
Backend question · NestJS › Middleware & request lifecycle

How do you write and register middleware in Nest for specific routes?

@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 a NestModule.
  • Use apply().forRoutes() to pick routes and exclude() to skip some.
  • Use app.use() for global function middleware without DI.