Performance: Why middleware processes requests before handlers
This affects the time it takes for the server to start processing a request and the overall responsiveness of the application.
app.use(async (req, res, next) => { // lightweight async preprocessing await Promise.resolve(); next(); }); app.get('/data', (req, res) => { res.send('Data'); });
app.use((req, res, next) => {
// heavy synchronous processing
for (let i = 0; i < 1e7; i++) {}
next();
});
app.get('/data', (req, res) => {
res.send('Data');
});| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy synchronous middleware | N/A (server-side) | N/A | N/A | [X] Bad |
| Lightweight async middleware | N/A (server-side) | N/A | N/A | [OK] Good |
next() passes control to the next middleware or handler.next() function -> Option Bexport function logger(req, res, next) {
console.log('Middleware start');
next();
console.log('Middleware end');
}export function authMiddleware(req, res, next) {
if (!req.headers.authorization) {
res.status(401).send('Unauthorized');
return;
}
next();
}req here makes it available later.req.timestamp before calling next() so handlers see the value.req.timestamp = Date.now() in middleware, then call next() -> Option APass the test and this pattern moves unknown