0
0
NestJSframework~8 mins

Creating middleware in NestJS - Performance Optimization Steps

Choose your learning style9 modes available
Performance: Creating middleware
MEDIUM IMPACT
Middleware affects request processing speed and can impact server response time and client perceived latency.
Adding logging to requests
NestJS
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();
  }
}
Defers logging asynchronously, allowing the request to continue without blocking the event loop.
📈 Performance GainNon-blocking middleware reduces INP and improves server responsiveness.
Adding logging to requests
NestJS
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();
  }
}
Heavy synchronous work blocks the event loop, delaying all requests and responses.
📉 Performance CostBlocks event loop for 50-100ms per request, increasing INP and overall latency.
Performance Comparison
PatternEvent Loop BlockingRequest LatencyConcurrency ImpactVerdict
Synchronous heavy work in middlewareHigh (blocks event loop)High latency per requestLow concurrency[X] Bad
Asynchronous non-blocking middlewareNone (event loop free)Low latencyHigh concurrency[OK] Good
Rendering Pipeline
Middleware runs during the server request processing pipeline before the final response is sent. It affects how fast the server can respond and how quickly the client receives data.
Request Handling
Event Loop
Response Generation
⚠️ BottleneckBlocking synchronous code in middleware stalls the event loop, delaying all requests.
Core Web Vital Affected
INP
Middleware affects request processing speed and can impact server response time and client perceived latency.
Optimization Tips
1Avoid synchronous heavy work in middleware to prevent blocking the event loop.
2Use asynchronous operations in middleware to keep the server responsive.
3Keep middleware logic minimal and non-blocking to improve request handling speed.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk of synchronous heavy computation inside NestJS middleware?
AIt increases CSS paint time in the browser.
BIt blocks the event loop, delaying all requests.
CIt causes layout shifts on the client side.
DIt reduces the bundle size.
DevTools: Performance
How to check: Record a server profile or use Node.js profiling tools to check event loop delays during request handling.
What to look for: Look for long blocking tasks or event loop stalls indicating synchronous blocking in middleware.