0
0
NestJSframework~8 mins

Global middleware in NestJS - Performance & Optimization

Choose your learning style9 modes available
Performance: Global middleware
MEDIUM IMPACT
Global middleware affects the request processing time and overall server response speed by running on every incoming request.
Applying middleware logic to all incoming HTTP requests
NestJS
app.use((req, res, next) => {
  if (req.path.startsWith('/api')) {
    lightweightCheck();
  }
  next();
});
Runs lightweight checks only on relevant routes, reducing unnecessary processing.
📈 Performance GainReduces blocking time per request, improving INP and overall throughput.
Applying middleware logic to all incoming HTTP requests
NestJS
app.use((req, res, next) => {
  heavyComputation();
  next();
});
Runs expensive computation on every request, increasing response time and blocking event loop.
📉 Performance CostBlocks event loop for each request, increasing INP and slowing server response.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Heavy synchronous global middlewareN/A (server-side)N/AN/A[X] Bad
Lightweight conditional global middlewareN/A (server-side)N/AN/A[OK] Good
Rendering Pipeline
Global middleware runs early in the server request pipeline before route handlers, affecting how fast the server can start sending a response.
Request Parsing
Middleware Execution
Route Handling
⚠️ BottleneckMiddleware Execution when middleware is heavy or synchronous
Core Web Vital Affected
INP
Global middleware affects the request processing time and overall server response speed by running on every incoming request.
Optimization Tips
1Keep global middleware logic minimal and asynchronous.
2Apply global middleware only to necessary routes when possible.
3Avoid heavy computations inside global middleware to prevent blocking.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk of using heavy global middleware in NestJS?
AIt causes layout shifts in the browser.
BIt increases the size of the client bundle.
CIt blocks the event loop on every request, increasing response time.
DIt reduces the number of HTTP requests.
DevTools: Performance (Node.js profiling tools or NestJS debug logs)
How to check: Use Node.js profiler or NestJS logging to measure middleware execution time per request.
What to look for: Look for long blocking times or high CPU usage during middleware execution indicating slow middleware.