Application-level vs router-level middleware
scoping of middleware.
app.use() binds to the app and runs everywhere; router.use() binds to a Router and runs only for that router's routes.
claiming they are interchangeable or that scope does not matter.
WHAT THIS TESTS This probes your understanding of where middleware executes and how Express composes routers into the request pipeline.
A GOOD ANSWER COVERS Application-level middleware is attached directly to the app instance via app.use() (optionally with a path) and runs for every matching request across the entire application. Router-level middleware is attached to an express.Router() instance via router.use() and only executes for requests that match routes defined on that router, once the router is mounted with app.use('/path', router). Both share the same (req, res, next) contract; the difference is purely scope. Router-level middleware lets you apply behavior to a logical group of routes without affecting the rest of the app.
COMMON WRONG ANSWERS Claiming the two are interchangeable. Believing router-level middleware runs globally. Forgetting that the mount path prefixes all router routes. Applying authentication at app level when only the admin section needs it, either over-protecting public routes or, conversely, under-scoping security.
LIKELY FOLLOW-UPS How does mount path interact with router paths? What is the execution order when both app-level and router-level middleware match? How do you share data set in app-level middleware with router routes (via req)?
ONE CONCRETE EXAMPLE A use case for router-level middleware is gating an admin area. const adminRouter = express.Router(); adminRouter.use(requireAdmin); adminRouter.get('/dashboard', handler); app.use('/admin', adminRouter); Here requireAdmin only runs for /admin routes, so public routes stay open while everything under /admin is protected. Doing this with app.use(requireAdmin) would force authentication on every endpoint, including the login page itself, creating a redirect loop.
Read the original → expressjs.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.