0
0
Expressframework~3 mins

Admin vs user route protection in Express - When to Use Which

Choose your learning style9 modes available
The Big Idea

Discover how a simple middleware can save your app from security leaks and messy code!

The Scenario

Imagine building a website where some pages are only for admins and others for regular users. You try to check user roles on every page manually by writing repeated code everywhere.

The Problem

Manually checking roles on every route is tiring and easy to forget. If you miss a check, unauthorized users might see sensitive info. It also makes your code messy and hard to update.

The Solution

Using route protection middleware lets you centralize role checks. You write the check once, then apply it to routes needing admin or user access. This keeps your code clean and secure.

Before vs After
Before
app.get('/admin', (req, res) => {
  if (req.user.role !== 'admin') {
    return res.status(403).send('Forbidden');
  }
  res.send('Welcome Admin');
});
After
function checkRole(role) {
  return (req, res, next) => {
    if (req.user.role !== role) return res.status(403).send('Forbidden');
    next();
  };
}
app.get('/admin', checkRole('admin'), (req, res) => {
  res.send('Welcome Admin');
});
What It Enables

This approach makes it easy to protect many routes by role, improving security and keeping your code simple and reusable.

Real Life Example

On a company dashboard, only HR staff can access employee salary info, while regular employees see their own profiles. Route protection middleware enforces this smoothly.

Key Takeaways

Manual role checks are repetitive and risky.

Middleware centralizes and simplifies access control.

Secure your app while keeping code clean and maintainable.