• Mail us
  • Book a Meeting
  • Call us
  • Chat with us

NodeJS

Build Reusable Middleware in NestJS


Introduction

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..

What is Middleware in NestJS?

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.

Creating Middleware in NestJS

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/clinest new nest-middleware-democd 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.tsimport { 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.tsimport { 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.tsimport { 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.

Use Cases for Middleware in NestJS

  • Authentication and Authorization: Middleware is often used in routes to check authentication bearer tokens and allow a user to access these routes. Authentication can include checking for verified JWT tokens, session cookies, or any other mechanism that can be verified for a user’s identity.
  • Logging: You can create custom logging middleware, which captures requests for particular data like headers, query parameters, or the time taken to respond to various requests.
  • Validation: Middleware can check incoming requests before they reach a route handler for content types, headers, or input formats.
  • CORS and Security Headers: Middleware can set or modify HTTP request header such as CORS Header, security headers and even custom headers to control access and security.
  • Rate Limiting: Middleware can be designed to limit the number of requests a user can perform in a specified period of time in an attempt to thwart attempts of DDoS or service abuse.
  • Ready to transform your business with our technology solutions? Contact Us today to Leverage Our NodeJS Expertise.

Share

facebook
LinkedIn
Twitter
Mail
NodeJS

Related Center Of Excellence