Performance: Middleware composition for auth layers
This affects the server response time and throughput by how efficiently authentication checks are composed and executed before reaching route handlers.
Jump into concepts and practice - no test required
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 |
checkToken and checkRole to an Express route using an array?req.user = { role: 'user' } hits the route?function checkToken(req, res, next) {
if (!req.user) return res.status(401).send('No token');
next();
}
function checkAdmin(req, res, next) {
if (req.user.role !== 'admin') return res.status(403).send('Forbidden');
next();
}
app.get('/secure', [checkToken, checkAdmin], (req, res) => res.send('Welcome admin'));function auth(req, res, next) {
if (!req.headers.authorization) {
res.status(401).send('Unauthorized');
}
next();
}
app.get('/data', auth, (req, res) => res.send('Data'));