router.use()

Mounts middleware scoped to a router and its routes.

Since Express 4 Spec ↗

Syntax

router.use([path,] ...middleware)

Parameters

NameTypeRequiredDescription
path string | RegExp No Optional mount path relative to the router.
middleware ...function Yes Middleware or sub-routers.

Returns

Router — The router, for chaining.

Examples

const router = express.Router();

router.use((req, res, next) => {
  if (!req.headers.authorization) return res.sendStatus(401);
  next();
});

router.get('/secret', (req, res) => res.send('ok'));
app.use('/api', router);
Output
$ curl localhost:3000/api/secret
(401 Unauthorized)
const router = express.Router();
router.use('/admin', adminRouter);
app.use(router);

Notes

Middleware added with `router.use` runs only for requests handled by that router, making it ideal for per-feature auth or logging. Declaration order still matters within the router.

See also