Middleware

Middleware functions run before the route handler and can inspect or modify the request.

Syntaxuse(req, res, next: NextFunction)

Middleware runs first in the lifecycle, before guards and the route handler. It has access to the request and response objects and a next() function.

Uses

  • Logging incoming requests.
  • Attaching data to the request.
  • Cross-cutting concerns shared by many routes.

A class middleware implements NestMiddleware and is applied in a module's configure() method. Middleware does not know which route will ultimately handle the request.

Example

Example Β· typescript
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(`${req.method} ${req.url}`);
    next();
  }
}

// Apply in a module:
// configure(consumer: MiddlewareConsumer) {
//   consumer.apply(LoggerMiddleware).forRoutes('*');
// }

When to use it

  • A developer writes a RequestLogger middleware that prints the HTTP method and URL for every incoming request to aid debugging.
  • A team applies a CORS middleware only to a specific route prefix using module-level consumer.apply().forRoutes().
  • An engineer uses middleware to attach a correlation ID from the X-Request-ID header to the request object before it reaches any guard or handler.

More examples

Class-based middleware

Implements NestMiddleware to log each request before calling next() to pass control to the next handler.

Example Β· 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) {
    console.log(`[${req.method}] ${req.url}`);
    next();
  }
}

Applying middleware in module

Registers the middleware globally for all routes using the MiddlewareConsumer in the module configure hook.

Example Β· ts
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { LoggerMiddleware } from './logger.middleware';

@Module({})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(LoggerMiddleware)
      .forRoutes('*');   // apply to all routes
  }
}

Middleware for specific routes

Applies AuthMiddleware to all UsersController routes while excluding the login endpoint using exclude().

Example Β· ts
configure(consumer: MiddlewareConsumer) {
  consumer
    .apply(AuthMiddleware)
    .exclude({ path: 'auth/login', method: RequestMethod.POST })
    .forRoutes(UsersController);
}

Discussion

  • Be the first to comment on this lesson.