What if one small missing check lets strangers see your private data?
Why Protecting routes with auth middleware in Express? - Purpose & Use Cases
Imagine you have a website where some pages should only be seen by logged-in users. You try to check if someone is logged in on every page manually by writing the same code again and again inside each route.
Doing this manually means repeating code everywhere, which is tiring and easy to forget. If you miss one place, unauthorized users might see private info. It also makes your code messy and hard to fix later.
Auth middleware lets you write the login check once and then apply it to any route you want to protect. This keeps your code clean, safe, and easy to manage.
app.get('/dashboard', (req, res) => { if (!req.user) { return res.redirect('/login'); } res.send('Welcome to your dashboard'); });
function authMiddleware(req, res, next) {
if (!req.user) return res.redirect('/login');
next();
}
app.get('/dashboard', authMiddleware, (req, res) => {
res.send('Welcome to your dashboard');
});This lets you easily protect many routes with one simple function, making your app safer and your code cleaner.
Think of a gym where only members can enter certain rooms. Instead of checking membership at every door separately, a guard (middleware) checks once and lets members pass smoothly.
Manual checks cause repeated code and risk mistakes.
Auth middleware centralizes login checks for safety and clarity.
Protecting routes becomes simple and reliable.