0
0
NestJSframework~8 mins

Middleware ordering in NestJS - Performance & Optimization

Choose your learning style9 modes available
Performance: Middleware ordering
MEDIUM IMPACT
Middleware order affects how fast requests are processed and how many times the browser waits before getting a response.
Handling HTTP requests with multiple middleware functions
NestJS
app.use(lightMiddleware);
app.use(heavyMiddleware);
Light middleware runs first, quickly handling simple tasks and reducing delay before heavy processing.
📈 Performance GainReduces average request processing time, improving input responsiveness (INP).
Handling HTTP requests with multiple middleware functions
NestJS
app.use(heavyMiddleware);
app.use(lightMiddleware);
Heavy middleware runs before lightweight ones, causing unnecessary delay for all requests.
📉 Performance CostBlocks request processing longer, increasing input delay (INP) for users.
Performance Comparison
PatternMiddleware OrderRequest DelayUser ImpactVerdict
Heavy middleware firstHeavy → LightHigh delaySlower response, worse INP[X] Bad
Light middleware firstLight → HeavyLower delayFaster response, better INP[OK] Good
Rendering Pipeline
Middleware runs on the server before sending a response. The order affects how quickly the server can start sending data back to the browser.
Request Handling
Response Preparation
⚠️ BottleneckRequest Handling stage due to synchronous or heavy middleware blocking the pipeline.
Core Web Vital Affected
INP
Middleware order affects how fast requests are processed and how many times the browser waits before getting a response.
Optimization Tips
1Place lightweight middleware before heavy middleware to reduce request delay.
2Avoid blocking operations early in middleware to improve input responsiveness (INP).
3Use asynchronous middleware wisely to prevent blocking the request pipeline.
Performance Quiz - 3 Questions
Test your performance knowledge
Why should lightweight middleware run before heavy middleware in NestJS?
ATo delay response so the server can prepare more data
BTo reduce request processing time and improve input responsiveness
CTo increase bundle size for better caching
DTo avoid using asynchronous code
DevTools: Network and Performance panels
How to check: Record a performance profile while making requests; check waterfall timings and server response times.
What to look for: Look for long server processing times before response starts, indicating middleware blocking.