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)