What is Middleware in NestJS: Simple Explanation and Example
Middleware in NestJS is a function that runs before the route handler to process requests or responses. It can modify requests, perform checks, or log information before passing control to the next step.How It Works
Think of middleware as a checkpoint on a road before you reach your destination. When a request comes to your NestJS app, middleware acts like a gatekeeper that can inspect or change the request before it reaches the final handler that sends a response.
Middleware functions receive the request and response objects, and a next function to pass control forward. They can do things like check if a user is logged in, log request details, or add extra data to the request. After their work, they call next() to let the request continue its journey.
Example
This example shows a simple logging middleware that prints the request method and URL before passing control to the next handler.
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... Method: ${req.method}, URL: ${req.url}`); next(); } } // In your module import { Module, MiddlewareConsumer, RequestMethod } from '@nestjs/common'; import { LoggerMiddleware } from './logger.middleware'; @Module({}) export class AppModule { configure(consumer: MiddlewareConsumer) { consumer .apply(LoggerMiddleware) .forRoutes({ path: '*', method: RequestMethod.ALL }); } }
When to Use
Use middleware when you want to run code before your route handlers process requests. Common uses include:
- Logging request details for debugging or monitoring
- Checking if a user is authenticated before accessing certain routes
- Adding or modifying request headers or data
- Handling CORS (Cross-Origin Resource Sharing) settings
Middleware is great for tasks that apply to many routes and need to run early in the request lifecycle.
Key Points
- Middleware runs before route handlers in NestJS.
- It can modify requests, responses, or perform checks.
- Always call
next()to continue the request flow. - Middleware is useful for logging, authentication, and request modification.
- It applies to routes globally or selectively.