How to apply middleware to multiple APIs or controllers in Nestjs?

February 5, 2023 - 2 min read

To apply middleware to multiple APIs or controllers in Nestjs, you have to pass the string API routes or the Controller classes to the forRoutes() method of the MiddlewareConfigProxy interface of the Nestjs separated by the , (comma) symbol. The forRoutes() method is chained after the apply() method of the MiddlewareConsumer interface inside the Module class.

For example, let's say we have two controllers, GreetController and CustomersController, and two middlewares, RequestTransformer and ApplicationLogger.

NOTE: For more information on creating middleware, refer to this blog How to create functional middleware for APIs in Nestjs?.

NOTE: For more information on creating APIs, refer to this blog How to make a simple GET request or an API endpoint in Nestjs?.

To apply both the RequestTransformer and the ApplicationLogger middleware to the GreetController and the CustomersController API controllers, we can pass both the controller classes to the forRoutes() method separated by the , (comma) symbol after the apply() method of the MiddlewareConsumer interface.

It can be done like this,

import { MiddlewareConsumer, Module, NestModule } from "@nestjs/common";
import { GreetController } from "./greet/greet.controller";
import { CustomersController } from "./customers/customers.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, CustomersController],
  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.
    // - More APIs or API `Controller` classes can be
    //   added by separating with the `,` (comma) symbol in the `forRoutes()` method.
    consumer
      .apply(ApplicationLogger, RequestTransformer)
      .forRoutes(GreetController, CustomersController);
  }
}

With the above code, we have successfully added middlewares to both the GreetController and CustomersController API controllers in Nestjs. Great job! 🥳

See the above code live in codesandbox.

That's all 😃.