NestJS is a powerful framework, but it doesn’t mean that everything is so smooth sailing. Often, you will need to run code before the request reaches the route handler. It can be used for logging, authentication, validation, modifying requests or dealing with exceptions..
In NestJS, the middleware function is run during every request-response interaction. and they can change the request and response objects or even do logic checks before the request goes to a specific route.
Middleware is especially powerful with cross section issues such as authentication, logging or setting security headers.
Step 1: Set up a NestJS Project
First of all, make sure that you set up a NestJS project. To most people, this step should be pretty straightforward, you can easily create a new NestJS project with Nest CLI.
npm i -g @nestjs/cli
nest new nest-middleware-demo
cd nest-middleware-demo
Step 2: Create the Middleware Class
In NestJS, middleware is a class that implements the NestMiddleware interface. creating the middleware also requires implementing use which takes in req and res, as well as next callback.
Create logger.middleware.ts file inside the src directory
// src/logger.middleware.ts
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) {
const now = Date.now();
console.log(`Request... ${req.method} ${req.originalUrl}`);
next();
}
}
Above code does the following:
The LoggerMiddleware class implements NestMiddleware and overrides the use method.
As with all middlewares, the use function retrieves req, res and next which is invoked to yield control to the following middleware or path handler.
The middleware logs the HTTP method, URL, and response time for each request made by the user.
Step 3: Middleware Installation to the Application
There is more than one way to apply middleware in NestJS: inside modules, on certain routes, or even globally.
Apply Middleware Globally
If you want to ensure that the middleware runs on all routes, you need to update main.ts file as follows:
// src/main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { LoggerMiddleware } from './logger.middleware';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// Apply middleware globally
app.use(LoggerMiddleware);
await app.listen(3000);
}
bootstrap();
In this case, all incoming requests to the application have the LoggerMiddleware middleware added to them.
Apply middleware for Selected Routes:
The same logic applies if you want to add middleware only for certain routes. Here is how you can change app.module.ts to configure middleware for selected routes only:
// src/app.module.ts
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { LoggerMiddleware } from './logger.middleware';
import { AppController } from './app.controller';
@Module({
imports: [],
controllers: [AppController],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
// Apply middleware only to specific routes
consumer.apply(LoggerMiddleware).forRoutes('your-route-name');
// Apply middleware to multiple routes
consumer.apply(LoggerMiddleware).forRoutes('route1', 'route2');
}
}
In this case, the LoggerMiddleware is applied only to the your-route-name route. Since you may want other routes or even other controllers to implement the same middleware, you are free to combine the selected routes.
Step 4: Check Your Middleware
Now that you have the middleware, it’s time to plug it into your NestJS application and test it locally. Just execute
npm run start
Now, each time you make a request to the application (e.g., via Postman or a web browser), the console should show logs that capture the HTTP request method, URL, and the time taken to respond to each request.
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our NodeJS Expertise.