0
0
NestJSframework~8 mins

Applying middleware to routes in NestJS - Performance & Optimization

Choose your learning style9 modes available
Performance: Applying middleware to routes
MEDIUM IMPACT
Middleware affects the request processing speed and can impact the time before the route handler executes, influencing interaction responsiveness.
Applying middleware to all routes indiscriminately
NestJS
app.use('/api/users', userMiddleware); // applies middleware only to /api/users routes
Middleware runs only on targeted routes, reducing unnecessary processing and improving responsiveness.
📈 Performance Gainreduces middleware executions, lowering INP latency
Applying middleware to all routes indiscriminately
NestJS
app.use(globalMiddleware); // applies middleware to every route
Middleware runs on every request, even when not needed, causing unnecessary processing and slower response times.
📉 Performance Costadds processing overhead on every request, increasing INP latency
Performance Comparison
PatternMiddleware RunsProcessing OverheadResponse DelayVerdict
Global middleware on all routesEvery requestHighIncreased INP latency[X] Bad
Middleware applied to specific routesOnly targeted requestsLowMinimal delay[OK] Good
Rendering Pipeline
Middleware runs during the server request lifecycle before the route handler, affecting how fast the server can respond to user input.
Request Processing
Route Matching
Handler Execution
⚠️ BottleneckMiddleware processing time before route handler
Core Web Vital Affected
INP
Middleware affects the request processing speed and can impact the time before the route handler executes, influencing interaction responsiveness.
Optimization Tips
1Apply middleware only to routes that require it to reduce processing overhead.
2Keep middleware logic lightweight to minimize request handling delay.
3Avoid global middleware unless absolutely necessary to improve input responsiveness.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk of applying middleware globally to all routes in NestJS?
AMiddleware runs on every request, causing unnecessary processing.
BMiddleware reduces bundle size.
CMiddleware improves LCP by preloading data.
DMiddleware eliminates layout shifts.
DevTools: Network
How to check: Open DevTools Network panel, filter requests by route, and compare response times with and without middleware.
What to look for: Look for increased response time on routes with middleware indicating processing overhead.