Performance: Conditional middleware execution
This affects server response time and resource usage by controlling when middleware runs during request handling.
app.use('/api', (req, res, next) => { // heavy processing only for /api routes next(); });
app.use((req, res, next) => {
// heavy processing
next();
});| Pattern | Middleware Calls | CPU Usage | Response Latency | Verdict |
|---|---|---|---|---|
| Middleware runs on all requests | All requests | High | Increased | [X] Bad |
| Middleware runs only on specific routes | Subset of requests | Lower | Reduced | [OK] Good |
| Middleware partially runs then skips | All requests but partial work | Medium | Moderate | [!] OK |
app.use((req, res, next) => {
if (req.query.token === '123') {
console.log('Token valid');
next();
} else {
res.status(401).send('Unauthorized');
}
});
app.get('/', (req, res) => res.send('Welcome!'));?token=123?app.use((req, res, next) => {
if (req.headers['x-auth']) {
next();
}
res.status(403).send('Forbidden');
});Pass the test and this pattern moves unknown