0
0
Expressframework~8 mins

Middleware execution flow (req, res, next) in Express - Performance & Optimization

Choose your learning style9 modes available
Performance: Middleware execution flow (req, res, next)
MEDIUM IMPACT
This affects server response time and how quickly the client receives the final page or data.
Handling multiple middleware functions in an Express app
Express
app.use(async (req, res, next) => {
  await someAsyncTask();
  next();
});
app.use((req, res) => {
  res.send('Done');
});
Using asynchronous code prevents blocking, allowing other requests to be handled concurrently.
📈 Performance GainNon-blocking middleware improves server throughput and reduces response delay
Handling multiple middleware functions in an Express app
Express
app.use((req, res, next) => {
  // heavy synchronous task
  for(let i = 0; i < 1e8; i++) {}
  next();
});
app.use((req, res) => {
  res.send('Done');
});
Blocking synchronous code in middleware delays the entire request processing and response.
📉 Performance CostBlocks event loop, increasing server response time by hundreds of milliseconds
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Blocking synchronous middleware0 (server-side)0 (server-side)0 (client-side)[X] Bad
Asynchronous non-blocking middleware0 (server-side)0 (server-side)0 (client-side)[OK] Good
Rendering Pipeline
Middleware functions process the request and response objects sequentially on the server before sending the final response to the browser.
Request Handling
Response Preparation
Network Transfer
⚠️ BottleneckBlocking or slow middleware delays the entire response, increasing LCP on the client.
Core Web Vital Affected
LCP
This affects server response time and how quickly the client receives the final page or data.
Optimization Tips
1Avoid heavy synchronous tasks inside middleware to prevent blocking.
2Always call next() once middleware work is done to continue the flow.
3Use asynchronous operations in middleware to keep the server responsive.
Performance Quiz - 3 Questions
Test your performance knowledge
What happens if middleware contains heavy synchronous code?
AIt speeds up response time by running faster.
BIt blocks the event loop and delays all requests.
CIt only affects the current request without blocking others.
DIt improves browser rendering performance.
DevTools: Network
How to check: Open DevTools, go to Network tab, reload the page, and check the Time column for server response delay.
What to look for: Look for long waiting (TTFB) times indicating slow server middleware processing.