0
0
Expressframework~3 mins

Why Protecting routes with auth middleware in Express? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if one small missing check lets strangers see your private data?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
app.get('/dashboard', (req, res) => {
  if (!req.user) {
    return res.redirect('/login');
  }
  res.send('Welcome to your dashboard');
});
After
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');
});
What It Enables

This lets you easily protect many routes with one simple function, making your app safer and your code cleaner.

Real Life Example

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.

Key Takeaways

Manual checks cause repeated code and risk mistakes.

Auth middleware centralizes login checks for safety and clarity.

Protecting routes becomes simple and reliable.