What is Express.js Router-level middleware?
Answer
Router-level middleware is middleware bound to an express.Router() instance rather than the app instance. It only runs for requests that match the router's mounted path. This allows you to scope middleware to specific route groups. For example, apply authentication only to API routes: const apiRouter = express.Router(); apiRouter.use(authenticate); apiRouter.get('/users', getUsers); app.use('/api', apiRouter);. All /api/* requests go through authenticate, but public routes mounted directly on app are unaffected. You can stack multiple routers, each with their own middleware chain, enabling fine-grained control over which middleware applies to which routes without cluttering the main app.js.
Previous
How do you test an Express.js API?
Next
How do you implement WebSocket support alongside Express.js?
More Express.js Questions
View all →- Intermediate How do you implement JWT authentication in Express.js?
- Intermediate What is Express middleware chaining and how does it work?
- Intermediate What is the helmet package and why should you use it?
- Intermediate How do you implement rate limiting in Express.js?
- Intermediate What is input validation and how do you do it in Express?