Performance: Creating middleware
Middleware affects request processing speed and can impact server response time and client perceived latency.
import { Injectable, NestMiddleware } from '@nestjs/common'; import { Request, Response, NextFunction } from 'express'; @Injectable() export class LoggingMiddleware implements NestMiddleware { use(req: Request, res: Response, next: NextFunction) { setImmediate(() => { console.log(`Request to ${req.url}`); }); next(); } }
import { Injectable, NestMiddleware } from '@nestjs/common'; import { Request, Response, NextFunction } from 'express'; @Injectable() export class LoggingMiddleware implements NestMiddleware { use(req: Request, res: Response, next: NextFunction) { // Synchronous heavy computation for (let i = 0; i < 1e7; i++) {} console.log(`Request to ${req.url}`); next(); } }
| Pattern | Event Loop Blocking | Request Latency | Concurrency Impact | Verdict |
|---|---|---|---|---|
| Synchronous heavy work in middleware | High (blocks event loop) | High latency per request | Low concurrency | [X] Bad |
| Asynchronous non-blocking middleware | None (event loop free) | Low latency | High concurrency | [OK] Good |
use that takes req, res, next.use method correctly. class MyMiddleware { handle(req, res, next) { next(); } } uses handle, which is invalid. Options C and D define functions, not classes.class LoggerMiddleware {
use(req, res, next) {
console.log('Request URL:', req.url);
next();
}
}req.url and then calls next() to continue.use is defined and next() is called.class LoggerMiddleware {
use(req, res, next) {
console.log('Request received');
}
}
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(LoggerMiddleware).forRoutes('users');
}
}use method does not call next(), causing the request to hang without reaching the route handler.path and method in forRoutes.{ path: '/login', method: RequestMethod.POST }. Use consumer.apply(MyMiddleware).forRoutes('/login') and check method inside middleware applies middleware to all methods on '/login', requiring manual filtering. Apply middleware globally and filter POST requests inside middleware applies globally, which is less efficient. NestJS does not support method-specific middleware is false.Pass the test and this pattern moves unknown