π₯ Middleware in NestJS
1οΈβ£ What is Middleware?
Middleware in NestJS is a function that runs before the request reaches the controller. It can be used for:
β
Logging requests
β
Authentication
β
Modifying request data
β
Blocking unauthorized requests
π₯ Task 1: Create a Logging Middleware
Step 1: Create a Middleware File
Inside src/, create a new file: logger.middleware.ts
Step 2: Write the Middleware Code
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(`[${new Date().toISOString()}] ${req.method} ${req.url}`); next(); } } β This middleware logs the method and URL of every request.
β next() β Passes control to the next handler (controller or another middleware).
π₯ Task 2: Apply Middleware in app.module.ts
Modify src/app.module.ts to apply the middleware:
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common'; import { UserModule } from './user/user.module'; import { LoggerMiddleware } from './logger.middleware'; @Module({ imports: [UserModule], }) export class AppModule implements NestModule { configure(consumer: MiddlewareConsumer) { consumer.apply(LoggerMiddleware).forRoutes('*'); // Apply to all routes } } β This applies the logging middleware to all routes in the app.
π₯ Task 3: Test the Middleware
1οΈβ£ Start the server
Run the following command:
npm run start 2οΈβ£ Send a request
Make a GET request to:
http://localhost:3000/user 3οΈβ£ Check the terminal
You should see logs like:
[2025-03-06T10:30:00.123Z] GET /user π Bonus: Logging Request Body for POST Requests
Modify the logger.middleware.ts file to log the request body only for POST requests:
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(`[${new Date().toISOString()}] ${req.method} ${req.url}`); // Log request body for POST requests if (req.method === 'POST') { console.log('Request Body:', JSON.stringify(req.body)); } next(); } } Now, when you send a POST request, the terminal will display:
[2025-03-06T10:31:00.456Z] POST /user Request Body: {"name":"John","email":"john@example.com"} β Your Task
π₯ Implement the logging middleware in your NestJS project.
π₯ Modify it to log the request body for POST requests.
π₯ Test it and drop your thoughts in the comments! π
π¬ What do you think?
Do you use middleware in your NestJS projects? Share your experience in the comments! π―
Top comments (0)