0
0
Expressframework~3 mins

Why Router level middleware in Express? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could protect whole sections of your app with just one simple step?

The Scenario

Imagine building a web app where you want to check user login status only for certain parts of your site, like the admin pages, but not for the public pages.

You try to add the same login check code inside every route handler manually.

The Problem

Manually adding the same check in every route is tiring and easy to forget.

If you miss one, unauthorized users might sneak in.

Also, updating the check means changing many places, which is slow and error-prone.

The Solution

Router-level middleware lets you attach a function that runs automatically for all routes in a specific router.

This means you write the login check once, and it applies only where you want.

It keeps your code clean, safe, and easy to update.

Before vs After
Before
app.get('/admin/dashboard', checkLogin, (req, res) => { ... });
app.get('/admin/settings', checkLogin, (req, res) => { ... });
After
const adminRouter = express.Router();
adminRouter.use(checkLogin);
adminRouter.get('/dashboard', (req, res) => { ... });
adminRouter.get('/settings', (req, res) => { ... });
app.use('/admin', adminRouter);
What It Enables

You can organize your app so middleware runs only where needed, making your code safer and easier to manage.

Real Life Example

In an online store, you want to verify admin users before they access product management pages, but let shoppers browse products freely.

Router-level middleware lets you protect admin routes without affecting public pages.

Key Takeaways

Manually repeating middleware code is error-prone and hard to maintain.

Router-level middleware runs middleware functions for all routes in a router automatically.

This keeps your app organized, secure, and easier to update.