How to use route parameters — Basic
Path segments like :userId and :pasteId are available on req.params. Define them in the router path; read them in the controller or service.
Learn: Route parameters are part of the path template. In /users/:userId/pastes/:pasteId, req.params.userId and req.params.pasteId are strings set by Express when the route matches. Use them to identify which resource to load or update. With nested routers, mergeParams: true lets a child router see :userId from the parent mount.
Supplementary examples
Nested mount + child param
// app.use("/users/:userId/pastes", pastesRouter);
// GET /users/3/pastes/9 -> req.params.userId === "3", req.params.pasteId === "9"
async function read(req, res, next) {
const { userId, pasteId } = req.params;
// ...
}Course example
// Router — path defines the parameter name
router.get("/:pasteId", controller.read);
// Controller — req.params matches :pasteId
async function read(req, res, next) {
const { pasteId } = req.params;
const paste = await service.read(pasteId);
res.json({ data: paste });
}
Additional references & examples
- Express Router API
Router methods, route parameters, and mounting paths.
- Express req.params
Route parameters populated from the path pattern.