devnotes.

router.use() Function

router.use() mounts middleware onto a Router instance — for all its routes, or only for requests matching a specific path.

Syntax

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

Example

const express = require("express");
const app = express();
const router = express.Router();
const PORT = 5000;

router.use((req, res, next) => {
    console.log("Router-level middleware hit");
    next();
});

router.get("/items", (req, res) => {
    res.send("List of items");
});

app.use("/inventory", router);

app.listen(PORT, () => console.log(`Listening on ${PORT}`));

Every request to /inventory/* passes through the logging middleware before reaching its route.

Use cases

  • Applying authentication or logging to a specific group of routes.
  • Validating request data before it reaches a route handler.
  • Organizing middleware logically inside modular router files.
router.use() Function | DevNotes