0
0
NestJSframework~5 mins

Creating middleware in NestJS

Choose your learning style9 modes available
Introduction

Middleware lets you run code before your app handles a request. It helps you check or change requests easily.

Check if a user is logged in before allowing access to a page.
Log details about each request for debugging or monitoring.
Add headers to responses for security or tracking.
Block requests from certain IP addresses.
Parse data from requests before your main code uses it.
Syntax
NestJS
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
export class YourMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    // Your code here
    next();
  }
}

Middleware is a class with a use method that runs on each request.

Always call next() to continue to the next step in request handling.

Examples
This middleware logs the URL of every request.
NestJS
import { Injectable, NestMiddleware } 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 to: ${req.url}`);
    next();
  }
}
This middleware checks if the request has an authorization header and blocks it if missing.
NestJS
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
export class AuthMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    if (!req.headers.authorization) {
      return res.status(401).send('Unauthorized');
    }
    next();
  }
}
Sample Program

This example creates a middleware that logs the HTTP method and URL of every request. It then applies this middleware to all routes in the app.

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

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

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

Middleware runs in the order you apply it, so order matters.

Use forRoutes to apply middleware only to specific paths or controllers.

Middleware can modify requests and responses before they reach your route handlers.

Summary

Middleware runs code before your app handles requests.

Create middleware by making a class with a use method.

Apply middleware to routes using MiddlewareConsumer.