How to Create and Utilize Middleware

Learn about creating and leveraging middleware in NestJS.

overview

In NestJS, a middleware is a function that acts between the request and response to do a particular thing. Middleware is used for a variety of purposes, such as parsing requests, adding response headers, and preventing unauthorized access. In this article, I will explain how to create middleware with NestJS and how to utilize it with concrete code examples.

nest.js v10.1.7
nodejs v19.7.0

In addition, all the code created this time is posted on GitHub.

How to create middleware

First, create a new middleware using NestJS’s CLI. Execute the following command to create a middleware named logger.

nest g mi users/middleware/logger

After running this command, a file called logger.middleware.ts will be created in the users/middleware directory. This file is where the newly created middleware implementation goes.

import { Injectable, NestMiddleware } from '@nestjs/common';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  use(req: any, res: any, next: () => void) {
    console.log("Request received at " + new Date());
    next();
  }
}

In the above code, whenever the middleware receives a request, it will print the message “Request received” to the console along with the current date and time.

How to apply middleware

Next, apply the created middleware to your NestJS application. This is done in the users.module.ts file, which is the application’s module.

import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
import { LoggerMiddleware } from './middleware/logger/logger.middleware';

@Module({
  imports: [],
  controllers: [UsersController],
  providers: [UsersService],
})
export class UsersModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(LoggerMiddleware).forRoutes('*');
  }
}

In the code above, LoggerMiddleware is applied to all routes (*). This will run the LoggerMiddleware for every request your application receives.

test

Let’s check that the middleware is working properly by running the following command: Each command prints the current date and time to the console along with the message “Request received”.

# get user list
curl http://localhost:3000/users
# add user
curl -X POST -H "Content-Type: application/json" -d '{"name":"Mike"}' http://localhost:3000/users
# update user
curl -X PUT -H "Content-Type: application/json" -d '{"name": "Bob"}' http://localhost:3000/users/1
# remove user
curl -X DELETE http://localhost:3000/users/4

summary

In this article, we create middleware with NestJS

, explained how to apply it to your application. Middleware is a key concept that works between requests and responses to do specific processing. Creating and using middleware is an essential skill for application development using NestJS.