Performance: Protecting routes with auth middleware
This affects the server response time and user experience by adding authentication checks before route handlers run.
Jump into concepts and practice - no test required
function authMiddleware(req, res, next) {
if (!req.user) {
return res.redirect('/login');
}
next();
}
app.get('/dashboard', authMiddleware, (req, res) => {
res.send('Dashboard');
});app.get('/dashboard', (req, res) => { if (!req.user) { res.redirect('/login'); return; } // route logic res.send('Dashboard'); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Auth check inside each route | N/A (server-side) | N/A | N/A | [X] Bad |
| Auth middleware before routes | N/A (server-side) | N/A | N/A | [OK] Good |
function authMiddleware(req, res, next) {
if (req.headers.authorization === 'valid-token') {
next();
} else {
res.status(401).send('Unauthorized');
}
}
app.get('/dashboard', authMiddleware, (req, res) => {
res.send('Welcome to dashboard');
});function authMiddleware(req, res, next) {
if (!req.user) {
res.status(403).send('Forbidden');
}
next();
}function authMiddleware(req, res, next) {
if (!req.headers.authorization) {
return res.status(401).send('Unauthorized');
}
req.userId = req.headers.authorization;
next();
}
// How to apply this middleware and log userId for routes '/profile' and '/settings'?