0
0
NestJSframework~5 mins

Middleware ordering in NestJS

Choose your learning style9 modes available
Introduction

Middleware ordering controls the sequence in which middleware functions run. This helps manage how requests are processed step-by-step.

When you want to log requests before checking user authentication.
When you need to parse request data before validating it.
When you want to add headers after some middleware modifies the request.
When you want to handle errors after all other middleware runs.
Syntax
NestJS
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(MiddlewareOne, MiddlewareTwo)
      .forRoutes('path');
  }
}
Middleware runs in the order they are listed in the apply() method.
Order matters because each middleware can modify the request or response for the next one.
Examples
LoggerMiddleware runs first, then AuthMiddleware for requests to 'users' route.
NestJS
consumer.apply(LoggerMiddleware, AuthMiddleware).forRoutes('users');
AuthMiddleware runs first, then LoggerMiddleware. Changing order changes behavior.
NestJS
consumer.apply(AuthMiddleware, LoggerMiddleware).forRoutes('users');
Only one middleware runs for 'posts' route.
NestJS
consumer.apply(ParseMiddleware).forRoutes('posts');
Sample Program

This example shows two middleware: LoggerMiddleware runs first and logs a message, then AuthMiddleware runs and logs another message. The order in apply() controls this sequence.

NestJS
import { Injectable, NestMiddleware, MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
class LoggerMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    console.log('Logger: Request received');
    next();
  }
}

@Injectable()
class AuthMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    console.log('Auth: Checking authentication');
    next();
  }
}

@Module({})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(LoggerMiddleware, AuthMiddleware)
      .forRoutes('test');
  }
}
OutputSuccess
Important Notes

Always list middleware in the order you want them to run.

If middleware does not call next(), the chain stops and later middleware won't run.

Middleware ordering affects request processing and response behavior.

Summary

Middleware order controls the sequence of request handling.

Use apply() method to list middleware in the desired order.

Order affects how requests are logged, authenticated, or modified.