How to add a global middleware for all routes in Nestjs?

February 17, 2023 - 3 min read

To add a global middleware for all routes in NestJS, you can use the use() method of the app (INestApplication) instance of your NestJS application and pass the middleware as an argument to the method. If you have multiple middlewares, you can pass them as arguments to the use() method, separated by commas (,).

TL;DR

Filepath: src/main.ts

import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";

// import the middleware
import { ApplicationLogger } from "./middlewares/application-logger.middleware";

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  // Add `ApplicationLogger` middleware as a global middleware for all routes.
  // It can be done using the `use()` method from the
  // `INestApplication` instance and passing the `ApplicationLogger` as an argument to it.
  app.use(ApplicationLogger);
  await app.listen(3000);
}
bootstrap();

For example, let's say we have a middleware called ApplicationLogger that logs out the url and the host of the incoming request to the terminal.

The middleware looks like this,

Filepath: src/middlewares/application-logger.middleware.ts

/* Middleware that logs the base URL and the host URL of incoming requests. */

// Express types for the req, res, and next variables
import { Request, Response, NextFunction } from "express";

// middleware to log the base url and the host url of the incoming requests
export function ApplicationLogger(
  req: Request,
  res: Response,
  next: NextFunction
) {
  // log the base url and the host url from the `req` object
  console.log({
    Host: req.host,
    URL: req.url,
  });

  next();
}

A better approach to using this middleware is to use it as a global middleware.

To do that first, we have to go to the main.ts file or the application bootstrapping file. It can be found inside the src directory of the Nestjs application.

In my case, the main.ts file looks like this,

Filepath: src/main.ts

import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

Inside the main.ts file and after creating an instance of the INestApplication using the NestFactory.create() method, we have to use the use() method on the instance of the INestApplication and pass the ApplicationLogger middleware as an argument to the use() method.

It can be done like this,

Filepath: src/main.ts

import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";

// import the middleware
import { ApplicationLogger } from "./middlewares/application-logger.middleware";

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  // Add `ApplicationLogger` middleware as a global middleware for all routes.
  // It can be done using the `use()` method from the
  // `INestApplication` instance and passing the `ApplicationLogger` as an argument to it.
  app.use(ApplicationLogger);
  await app.listen(3000);
}
bootstrap();

Now if we go to any of the routes whether it may be valid or invalid the url and the host of the incoming request will be printed onto the terminal.

We have successfully added a global middleware for all routes in Nestjs. Yay! 🥳.

See the above code live in codesandbox.

That's all 😃.