DevPath · Learn to code ESPTEN

Routes, REST and API design

Express Router: routes and parameters

The Express Router

When an API grows, declaring every route on app becomes unmanageable. The Router lets you group the routes of a resource into its own module and mount them under a prefix:

import { Router } from "express";
const router = Router();

router.get("/", listProducts);          // GET  /products
router.get("/:id", getProduct);          // GET  /products/5
router.post("/", createProduct);         // POST /products

app.use("/products", router);            // mounts the group under /products

Each router is a "mini-application": it has its own routes and middleware, and is mounted wherever you want. This way the code stays organized by resource.

Route parameters: req.params

The dynamic segments of the route are marked with : and arrive in req.params (always as text strings):

router.get("/:id", (req, res) => {
  const id = req.params.id;   // /products/5  ->  "5"
  res.json({ id });
});

Query string: req.query

What comes after the ? in the URL is the query string. Express parses it and leaves it in req.query as an object:

// GET /products?page=2&limit=10
router.get("/", (req, res) => {
  const page = req.query.page;     // "2"
  const limit = req.query.limit;   // "10"
  res.json({ page, limit });
});

Both req.params and req.query arrive as strings. If you need a number, convert it with Number(...).

Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
REST design: resources and statuses →