Updated on 16 Apr, 20266 mins read 59 views

Middleware is the first layer that handles incoming requests in NestJS. It runs before guards, pipes, and controllers, making it ideal for tasks that should happen early in the request lifecycle.

What is Middleware?

A middleware is a function (or class) that:

  • Has access to the request (req)
  • Has access to the response (res)
  • Can modify or stop the request
  • Must call next() to pass control forward

Simple Idea:

Middleware = “Do something before the request reaches the controller”

Middleware Flow in NestJS

Request → Middleware → Guards → Pipes → Controller → Response

If middleware does not call next(), the request stops there.

Types of Middleware

1 Functional Middleware

Quick and simple

export function logger(req, res, next) {
  console.log('Request received');
  next();
}

2 Class-based Middleware (Recommended)

import { Injectable, NestMiddleware } from '@nestjs/common';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  use(req: any, res: any, next: () => void) {
    console.log(`Request: ${req.method} ${req.url}`);
    next();
  }
}

Creating Middleware

Step 1: Generate middleware

nest generate middleware logger

Step 2: Implement logic

use(req, res, next) {
  console.log('Logging...');
  next();
}

Applying Middleware

Middleware is applied inside a module using configure()

import { Module, MiddlewareConsumer } from '@nestjs/common';

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

Applies middleware only to /users routes

Buy Me A Coffee

Leave a comment

Your email address will not be published. Required fields are marked *