devnotes.

router.param() function

router.param() registers a callback that runs whenever a request includes a specific route parameter, before the route handler itself runs. Even if the parameter appears in several routes, the callback fires once per request-response cycle.

Syntax

router.param(name, function)

The callback receives req, res, next, and the parameter's value.

Example

routes.js:

const express = require("express");
const router = express.Router();

router.param("customerId", (req, res, next, id) => {
    console.log("Looking up customer:", id);
    next();
});

router.get("/customer/:customerId", (req, res) => {
    console.log("Handler for customer route running");
    res.end();
});

module.exports = router;

app.js:

const express = require("express");
const app = express();
const customerRoutes = require("./routes");

app.use("/", customerRoutes);

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`App running at ${PORT}`));

Visiting /customer/205 first logs Looking up customer: 205, then runs the route handler.

Use cases

  • Pre-loading a resource (like a user or product) before the route runs.
  • Validating a parameter's format before proceeding.
  • Avoiding repeated lookup logic across multiple routes that share a parameter.
router.param() function | DevNotes