0
0
Expressframework~8 mins

Request context middleware in Express - Performance & Optimization

Choose your learning style9 modes available
Performance: Request context middleware
MEDIUM IMPACT
This affects server response time and throughput by adding processing steps per request.
Adding request-specific data accessible in all downstream handlers
Express
app.use((req, res, next) => {
  // Initialize empty context
  req.context = {};
  next();
});

app.get('/route', async (req, res) => {
  if (!req.context.data) {
    req.context.data = await fetchDataAsync();
  }
  res.send(req.context.data);
});
Defers expensive async operations to route handlers and avoids blocking middleware.
📈 Performance GainNon-blocking middleware improves throughput and reduces average response time by 30-100ms.
Adding request-specific data accessible in all downstream handlers
Express
app.use((req, res, next) => {
  // Heavy synchronous computation
  const data = expensiveSyncFunction();
  req.context = { data };
  next();
});
Blocking synchronous work delays every request, increasing server response time.
📉 Performance CostBlocks event loop for duration of expensiveSyncFunction, increasing response latency by 50-200ms depending on complexity.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Heavy synchronous middlewareN/AN/AN/A[X] Bad
Lightweight async middlewareN/AN/AN/A[OK] Good
Rendering Pipeline
Request context middleware runs during the server's request handling pipeline before route handlers. It affects how fast the server can start processing and responding.
Middleware Execution
Request Handling
Response Generation
⚠️ BottleneckSynchronous or heavy computations in middleware block the event loop, delaying all subsequent processing.
Optimization Tips
1Avoid heavy synchronous work in request context middleware to keep server responsive.
2Use asynchronous operations and lazy loading for data in middleware.
3Profile middleware execution time to identify bottlenecks.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk of heavy synchronous code in request context middleware?
AIt blocks the event loop, delaying all requests.
BIt increases client-side rendering time.
CIt causes layout shifts in the browser.
DIt reduces CSS selector efficiency.
DevTools: Performance
How to check: Record a server profile or use Node.js profiling tools to measure middleware execution time per request.
What to look for: Look for long blocking times in middleware functions that delay request handling.