0
0
NestJSframework~5 mins

Global middleware in NestJS

Choose your learning style9 modes available
Introduction

Global middleware runs for every request in your app. It helps you add common features like logging or security checks everywhere without repeating code.

You want to log every request to your server.
You need to check user authentication on all routes.
You want to add headers to all responses.
You want to measure how long each request takes.
You want to handle CORS or security policies globally.
Syntax
NestJS
import { Injectable, NestMiddleware, MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    console.log(`Request... Method: ${req.method}, URL: ${req.url}`);
    next();
  }
}

@Module({})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(LoggerMiddleware).forRoutes('*');
  }
}

The forRoutes('*') means the middleware runs on all routes.

Middleware must call next() to continue the request cycle.

Examples
This applies the middleware to every route in the app.
NestJS
consumer.apply(LoggerMiddleware).forRoutes('*');
This applies the middleware only to the /users route.
NestJS
consumer.apply(AuthMiddleware).forRoutes('users');
This applies multiple middleware globally in order.
NestJS
consumer.apply(LoggerMiddleware, AuthMiddleware).forRoutes('*');
Sample Program

This example shows how to create a simple logger middleware that prints the HTTP method and URL for every request. It is applied globally to all routes using forRoutes('*').

NestJS
import { Injectable, NestMiddleware, MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    console.log(`Request... Method: ${req.method}, URL: ${req.url}`);
    next();
  }
}

@Module({})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(LoggerMiddleware).forRoutes('*');
  }
}

// When you run the NestJS app and make any HTTP request, the console will show the request method and URL.
OutputSuccess
Important Notes

Global middleware runs before route handlers and can modify requests or responses.

Always call next() in middleware to avoid blocking requests.

You can apply multiple middleware globally by listing them in apply().

Summary

Global middleware runs on every request in the app.

Use consumer.apply(...).forRoutes('*') to apply middleware globally.

Middleware helps add common features like logging or security checks easily.