Router Level Middleware in Express: What It Is and How It Works
router level middleware is middleware that is attached to an instance of express.Router(). It runs only for routes defined within that router, helping organize middleware logic by grouping related routes together.How It Works
Imagine your Express app as a big office building with many rooms. Each room is like a group of routes that share a common purpose. Router level middleware acts like a security guard assigned only to a specific room, checking requests before they enter that room.
When you create a router using express.Router(), you can add middleware to it. This middleware will only run for requests that match routes inside that router, not for the whole app. This helps keep your code clean and focused, as middleware logic is applied only where needed.
Example
This example shows a router with middleware that logs the request method and URL only for routes inside the router.
import express from 'express'; const app = express(); const router = express.Router(); // Router level middleware router.use((req, res, next) => { console.log(`Router Middleware: ${req.method} ${req.originalUrl}`); next(); }); // Route inside router router.get('/hello', (req, res) => { res.send('Hello from router!'); }); // Use router on /api path app.use('/api', router); // Route outside router app.get('/', (req, res) => { res.send('Hello from main app!'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
When to Use
Use router level middleware when you want to apply middleware only to a specific group of routes. This is helpful for:
- Applying authentication or logging only to API routes.
- Grouping routes by feature or resource for better code organization.
- Reducing unnecessary middleware execution on unrelated routes.
For example, if you have user-related routes, you can create a user router with middleware that checks if a user is logged in before accessing those routes.
Key Points
- Router level middleware runs only for routes inside its router.
- It helps keep middleware logic organized and scoped.
- Defined using
router.use()or on specific router routes. - It does not affect routes outside the router.