0
0
NestjsHow-ToBeginner ยท 4 min read

How to Create Middleware in NestJS: Simple Guide

In NestJS, create middleware by implementing the NestMiddleware interface with a use() method. Then, apply it in a module using configure() method of MiddlewareConsumer to run code before route handlers.
๐Ÿ“

Syntax

Middleware in NestJS is a class that implements the NestMiddleware interface. It must have a use(req, res, next) method where you write your logic. You apply middleware in a module by overriding the configure() method and using MiddlewareConsumer to specify routes.

  • use(req, res, next): Runs on each request, calls next() to continue.
  • MiddlewareConsumer: Configures which routes use the middleware.
typescript
import { Injectable, NestMiddleware, MiddlewareConsumer, Module, RequestMethod } from '@nestjs/common';
import { NextFunction, Request, Response } from 'express';

@Injectable()
class LoggerMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    console.log(`Request... ${req.method} ${req.url}`);
    next();
  }
}

@Module({})
class AppModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(LoggerMiddleware)
      .forRoutes({ path: '*', method: RequestMethod.ALL });
  }
}
๐Ÿ’ป

Example

This example shows a simple logger middleware that prints the HTTP method and URL of each request. It is applied globally to all routes in the AppModule. When you run the app and make requests, the console logs the request details before the route handler runs.

typescript
import { Injectable, NestMiddleware, MiddlewareConsumer, Module, RequestMethod, Controller, Get } from '@nestjs/common';
import { NextFunction, Request, Response } from 'express';

@Injectable()
class LoggerMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    console.log(`Request... ${req.method} ${req.url}`);
    next();
  }
}

@Controller()
class AppController {
  @Get()
  getHello() {
    return 'Hello World!';
  }
}

@Module({
  controllers: [AppController],
})
class AppModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(LoggerMiddleware)
      .forRoutes({ path: '*', method: RequestMethod.ALL });
  }
}
Output
Request... GET /
โš ๏ธ

Common Pitfalls

Common mistakes when creating middleware in NestJS include:

  • Not calling next() inside use(), which blocks the request.
  • Forgetting to apply middleware in the module's configure() method.
  • Applying middleware to wrong routes or missing route patterns.
  • Using middleware that is not decorated with @Injectable(), causing dependency injection errors.
typescript
/* Wrong: Missing next() call blocks requests */
@Injectable()
class BadMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    console.log('This will block requests');
    // next() is missing here
  }
}

/* Right: Always call next() to continue */
@Injectable()
class GoodMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    console.log('This will allow requests');
    next();
  }
}
๐Ÿ“Š

Quick Reference

Summary tips for NestJS middleware:

  • Middleware must implement NestMiddleware and have a use() method.
  • Always call next() to pass control to the next handler.
  • Apply middleware in the module's configure() method using MiddlewareConsumer.
  • Use @Injectable() decorator for middleware classes.
  • Specify routes carefully with forRoutes() to control middleware scope.
โœ…

Key Takeaways

Create middleware by implementing the NestMiddleware interface with a use() method.
Always call next() inside use() to continue request processing.
Apply middleware in the module's configure() method using MiddlewareConsumer.
Use @Injectable() decorator on middleware classes for dependency injection.
Specify routes with forRoutes() to control where middleware runs.