How to add more than one middleware for APIs in Nestjs?

February 4, 2023 - 2 min read

To add more than one middleware for APIs in Nestjs, you have to add the middleware function or class as an argument to the apply() method of the MiddlewareConsumer interface separated by , (comma) symbol inside the configure() method of the module class.

NOTE: To know more about creating middleware in Nestjs, see the blog on How to create functional middleware for APIs in Nestjs?.

For example, let's say we have 2 middlewares called ApplicationLogger and one called RequestTransformer. To add these 2 middlewares, we can use the apply() method and pass both the middlewares as arguments separated by the , (comma) symbol.

It can be done like this,

import { MiddlewareConsumer, Module, NestModule } from "@nestjs/common";
import { GreetController } from "./greet/greet.controller";
import { GreetService } from "./greet/greet.service";
import { ApplicationLogger } from "./middlewares/application-logger.middleware";
import { RequestTransformer } from "./middlewares/request-transformer.middleware";

@Module({
  imports: [],
  controllers: [GreetController],
  providers: [GreetService],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    // using the `apply()` method pass the `ApplicationLogger` and
    // the `RequestTransformer` middlewares as arguments separated by comma symbol.
    // The chained `forRoutes()` method is used to define
    // the APIs for which the middlewares need to work upon.
    consumer
      .apply(ApplicationLogger, RequestTransformer)
      .forRoutes(GreetController);
  }
}

We have successfully added more than one middleware for APIs in Nestjs. Yay 🥳!

See the above code live in codesandbox.

That's all 😃.