🚀 Express.js Intermediate

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.