0
0
NestJSframework~8 mins

Functional middleware in NestJS - Performance & Optimization

Choose your learning style9 modes available
Performance: Functional middleware
MEDIUM IMPACT
Functional middleware affects request processing speed and server response time by controlling how requests flow through the middleware stack.
Handling HTTP requests with middleware in NestJS
NestJS
export function fastMiddleware(req, res, next) {
  // Non-blocking async operation example
  setImmediate(next);
}
Uses non-blocking async call to avoid event loop blocking, allowing other requests to be processed concurrently.
📈 Performance GainNo event loop blocking, reduces INP and improves server responsiveness
Handling HTTP requests with middleware in NestJS
NestJS
export function slowMiddleware(req, res, next) {
  // Simulate heavy synchronous task
  const start = Date.now();
  while (Date.now() - start < 100) {}
  next();
}
This middleware blocks the event loop with a synchronous delay, causing slow request processing and poor responsiveness.
📉 Performance CostBlocks event loop for 100ms per request, increasing INP and delaying response
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Blocking synchronous middlewareN/A (server-side)N/AN/A[X] Bad
Non-blocking async middlewareN/A (server-side)N/AN/A[OK] Good
Rendering Pipeline
Functional middleware runs on the server before the response is sent. It affects the server's ability to quickly process and forward requests, impacting how fast the client receives content.
Request Handling
Middleware Execution
Response Sending
⚠️ BottleneckBlocking synchronous code inside middleware delays the entire request pipeline.
Core Web Vital Affected
INP
Functional middleware affects request processing speed and server response time by controlling how requests flow through the middleware stack.
Optimization Tips
1Avoid synchronous blocking code in middleware to keep the event loop free.
2Use asynchronous APIs and minimal logic inside middleware for faster request handling.
3Profile middleware execution time to identify and fix slow operations.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk of using synchronous code inside functional middleware in NestJS?
AIt blocks the event loop, delaying all incoming requests.
BIt increases the size of the client bundle.
CIt causes layout shifts in the browser.
DIt reduces CSS selector specificity.
DevTools: Network panel in browser DevTools and server profiling tools
How to check: Use the Network panel to measure server response times and use Node.js profiling or logging to check middleware execution duration.
What to look for: Look for long server response times or middleware functions that block the event loop causing delayed responses.