Session-Based AuthenticationLesson 3.5
session middleware for route protection in Express
requireAuth middleware pattern, req.session.userId check, role-based middleware, redirect vs 401 response, middleware chaining, reusable guard functions
Session Middleware for Route Protection
Auth middleware sits between the router and route handlers, short-circuiting unauthenticated requests before they touch business logic.
// Authentication check
function requireAuth(req, res, next) {
if (!req.session.userId) {
return res.status(401).json({ error: 'Authentication required' });
}
next();
}
// Role-based authorization
function requireRole(role) {
return (req, res, next) => {
if (!req.session.userId) {
return res.status(401).json({ error: 'Authentication required' });
}
if (req.session.role !== role) {
return res.status(403).json({ error: 'Insufficient permissions' });
}
next();
};
}
// Usage
app.get('/dashboard', requireAuth, (req, res) => {
res.json({ userId: req.session.userId });
});
app.delete('/admin/user/:id', requireRole('admin'), (req, res) => {
// Only admins reach here
});Return the correct HTTP status: 401 when the user is not authenticated, 403 when they are authenticated but lack permission. APIs return JSON error responses; traditional web apps redirect to a login page. Keep that distinction consistent across your routes.
The factory pattern (requireRole(role)) lets you create parameterized middleware without code duplication. Extend it for permission scopes, subscription tiers, or any other access model.
