0
0
Expressframework~8 mins

Middleware factory pattern in Express - Performance & Optimization

Choose your learning style9 modes available
Performance: Middleware factory pattern
MEDIUM IMPACT
This pattern affects server response time and middleware execution efficiency in Express apps.
Creating middleware that needs configuration per route
Express
function loggerFactory(level) {
  return function logger(req, res, next) {
    console.log(`[${level}] ${req.method} ${req.url}`);
    next();
  };
}
app.use(loggerFactory('info'));
Configuration is done once when middleware is created, reducing per-request work.
📈 Performance Gainreduces CPU work per request, improving throughput
Creating middleware that needs configuration per route
Express
function logger(req, res, next) {
  const level = req.query.level || 'info';
  console.log(`[${level}] ${req.method} ${req.url}`);
  next();
}
app.use(logger);
Middleware recalculates config on every request causing unnecessary overhead.
📉 Performance Costadds CPU overhead on every request, increasing response time slightly
Performance Comparison
PatternMiddleware CreationPer-request CostCPU OverheadVerdict
Direct middleware with config insideSingle instanceHigh (recomputes config)High[X] Bad
Middleware factory with config parameterMultiple instances (once per config)Low (uses preset config)Low[OK] Good
Rendering Pipeline
Middleware factory pattern affects the server-side request handling pipeline by optimizing middleware creation and execution.
Middleware Initialization
Request Handling
⚠️ BottleneckPer-request middleware execution with redundant computations
Optimization Tips
1Create middleware with configuration once using a factory function.
2Avoid recalculating settings inside middleware on every request.
3Reuse middleware instances to reduce CPU overhead and improve throughput.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using a middleware factory pattern in Express?
AIt reduces per-request computation by configuring middleware once.
BIt increases the number of middleware functions executed per request.
CIt delays middleware execution until after response is sent.
DIt caches HTTP responses automatically.
DevTools: Node.js Profiler or Chrome DevTools Performance panel
How to check: Record CPU profile during requests, compare middleware execution time with and without factory pattern.
What to look for: Lower CPU time per request and fewer redundant computations indicate better performance.