Performance: Middleware composition for auth layers
MEDIUM IMPACT
This affects the server response time and throughput by how efficiently authentication checks are composed and executed before reaching route handlers.
function authMiddleware(req, res, next) {
if (!req.user) return res.status(401).send('Unauthorized');
if (!req.user.isAdmin) return res.status(403).send('Forbidden');
next();
}
app.use(authMiddleware);app.use((req, res, next) => {
if (!req.user) return res.status(401).send('Unauthorized');
next();
});
app.use((req, res, next) => {
if (!req.user.isAdmin) return res.status(403).send('Forbidden');
next();
});| Pattern | Middleware Calls | CPU Overhead | Response Latency | Verdict |
|---|---|---|---|---|
| Multiple small auth middleware | 2+ calls per request | High due to repeated checks | Higher latency | [X] Bad |
| Single combined auth middleware | 1 call per request | Lower CPU usage | Lower latency | [OK] Good |