DEV Community

Cover image for 🔥 NestJS Middleware: Logging Requests with Ease! || By Munisekhar Udavalapati
Munisekhar Udavalapati
Munisekhar Udavalapati

Posted on

🔥 NestJS Middleware: Logging Requests with Ease! || By Munisekhar Udavalapati

🔥 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();
  }
}
Enter fullscreen mode Exit fullscreen mode

✔ 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
  }
}
Enter fullscreen mode Exit fullscreen mode

✔ 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
Enter fullscreen mode Exit fullscreen mode

2️⃣ Send a request

Make a GET request to:

http://localhost:3000/user
Enter fullscreen mode Exit fullscreen mode

3️⃣ Check the terminal

You should see logs like:

[2025-03-06T10:30:00.123Z] GET /user
Enter fullscreen mode Exit fullscreen mode

🚀 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();
  }
}
Enter fullscreen mode Exit fullscreen mode

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"}
Enter fullscreen mode Exit fullscreen mode

✅ 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)