Performance: Building custom middleware
This affects server response time and how quickly the server processes requests before sending responses.
app.use(async (req, res, next) => { await someAsyncOperation(); next(); });
app.use((req, res, next) => {
// heavy synchronous computation
for (let i = 0; i < 1e8; i++) {}
next();
});| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Blocking synchronous middleware | 0 (server-side) | 0 (server-side) | 0 (server-side) | [X] Bad |
| Asynchronous non-blocking middleware | 0 (server-side) | 0 (server-side) | 0 (server-side) | [OK] Good |
app.use((req, res, next) => {
req.customValue = 42;
next();
});
app.get('/', (req, res) => {
res.send(`Value is ${req.customValue}`);
});app.use((req, res, next) => {
if (!req.headers['x-auth']) {
res.status(401).send('Unauthorized');
}
next();
});Pass the test and this pattern moves unknown