0
0
Node.jsframework~8 mins

Building custom middleware in Node.js - Performance & Optimization

Choose your learning style9 modes available
Performance: Building custom middleware
MEDIUM IMPACT
This affects server response time and how quickly the server processes requests before sending responses.
Processing HTTP requests with custom middleware in Node.js
Node.js
app.use(async (req, res, next) => {
  await someAsyncOperation();
  next();
});
Using asynchronous operations prevents blocking the event loop, allowing other requests to be handled concurrently.
📈 Performance GainNon-blocking middleware improves throughput and reduces response delays.
Processing HTTP requests with custom middleware in Node.js
Node.js
app.use((req, res, next) => {
  // heavy synchronous computation
  for (let i = 0; i < 1e8; i++) {}
  next();
});
Blocking the event loop with heavy synchronous code delays all requests, increasing response time.
📉 Performance CostBlocks event loop for hundreds of milliseconds, increasing server response time and INP.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Blocking synchronous middleware0 (server-side)0 (server-side)0 (server-side)[X] Bad
Asynchronous non-blocking middleware0 (server-side)0 (server-side)0 (server-side)[OK] Good
Rendering Pipeline
Middleware runs on the server before sending responses, affecting how fast the server can start sending data to the browser.
Request Handling
Response Preparation
⚠️ BottleneckBlocking synchronous code in middleware delays response start time.
Core Web Vital Affected
INP
This affects server response time and how quickly the server processes requests before sending responses.
Optimization Tips
1Avoid heavy synchronous code in middleware to prevent blocking the event loop.
2Use asynchronous operations and call next() only after completion.
3Keep middleware logic simple and fast to improve server response time.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk of using heavy synchronous code in custom middleware?
AIt increases the size of the JavaScript bundle sent to the client.
BIt blocks the event loop, delaying all incoming requests.
CIt causes layout shifts in the browser.
DIt improves server throughput by batching requests.
DevTools: Network and Performance panels
How to check: Use Network panel to measure server response time; use Performance panel to check request blocking time.
What to look for: Look for long server response times or blocking periods indicating slow middleware processing.