0
0
NestJSframework~8 mins

Why middleware processes requests before handlers in NestJS - Performance Evidence

Choose your learning style9 modes available
Performance: Why middleware processes requests before handlers
MEDIUM IMPACT
This affects the time it takes for the server to start processing a request and the overall responsiveness of the application.
Preprocessing requests before reaching route handlers
NestJS
app.use(async (req, res, next) => {
  // lightweight async preprocessing
  await Promise.resolve();
  next();
});
app.get('/data', (req, res) => {
  res.send('Data');
});
Async and minimal middleware avoids blocking, allowing faster handler execution.
📈 Performance GainReduces blocking time to near 0ms, improving INP and responsiveness.
Preprocessing requests before reaching route handlers
NestJS
app.use((req, res, next) => {
  // heavy synchronous processing
  for (let i = 0; i < 1e7; i++) {}
  next();
});
app.get('/data', (req, res) => {
  res.send('Data');
});
Heavy synchronous work in middleware blocks the event loop, delaying all request handling.
📉 Performance CostBlocks request processing for 100+ ms, increasing INP and slowing response.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Heavy synchronous middlewareN/A (server-side)N/AN/A[X] Bad
Lightweight async middlewareN/A (server-side)N/AN/A[OK] Good
Rendering Pipeline
Middleware runs early in the request lifecycle, before route handlers, allowing preprocessing like authentication or logging. This stage affects how quickly the server can start generating a response.
Request Parsing
Middleware Execution
Route Handler Execution
⚠️ BottleneckMiddleware Execution if it contains heavy synchronous code
Core Web Vital Affected
INP
This affects the time it takes for the server to start processing a request and the overall responsiveness of the application.
Optimization Tips
1Middleware runs before handlers to preprocess requests.
2Avoid heavy synchronous work in middleware to prevent blocking.
3Use async operations in middleware to keep the event loop free.
Performance Quiz - 3 Questions
Test your performance knowledge
Why does middleware run before route handlers in NestJS?
ATo delay the response intentionally
BTo preprocess requests and possibly modify them before handlers run
CTo run after the response is sent
DTo handle errors only
DevTools: Performance
How to check: Record a server-side profile or use Node.js profiling tools to measure middleware execution time before handlers.
What to look for: Look for long blocking tasks in middleware that delay route handler start times.