0
0
Expressframework~3 mins

Why Middleware composition for auth layers in Express? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could secure your app with simple building blocks instead of repeating code everywhere?

The Scenario

Imagine you have to check if a user is logged in, then verify their role, and finally confirm their permissions for every single request by writing all these checks inside each route handler.

The Problem

Doing all these checks manually in every route is repetitive, easy to forget, and makes your code messy and hard to maintain. If you want to change one check, you must update many places, risking bugs.

The Solution

Middleware composition lets you build small, reusable functions for each auth step and combine them easily. This way, your routes stay clean, and auth logic is centralized and consistent.

Before vs After
Before
app.get('/dashboard', (req, res) => {
  if (!req.user) return res.status(401).send('Login required');
  if (req.user.role !== 'admin') return res.status(403).send('Forbidden');
  // ...rest of handler
});
After
const compose = (middlewares) => (req, res, next) => {
  let index = 0;
  const run = () => {
    if (index < middlewares.length) {
      middlewares[index++](req, res, run);
    } else {
      next();
    }
  };
  run();
};

const auth = compose([checkLoggedIn, checkAdminRole]);
app.get('/dashboard', auth, (req, res) => {
  // ...rest of handler
});
What It Enables

You can build clear, maintainable, and secure auth layers by combining simple middleware functions that run in order automatically.

Real Life Example

Think of a club entrance where a bouncer first checks your ID, then your membership card, and finally your VIP pass before letting you in. Middleware composition is like having each bouncer handle one check smoothly in a line.

Key Takeaways

Manual auth checks clutter code and cause errors.

Middleware composition breaks auth into reusable steps.

It keeps routes clean and security consistent.