Stop 03 · Express.js BasicsTopics · 3/8

Route Parameters

Part of the MERN Stack Roadmap

In short

/users/42 and /users/43 are the same route with different values. Route parameters let one handler serve every user, order or product by its id.

Route parameters like /api/products/:id capture parts of the URL into req.params, so one route can serve any product. Query strings like ?page=2 arrive in req.query.

The mascot walks down a corridor of doors holding a key with a coloured tag.

Think of it like this

Hostel room keys

Every room in the corridor looks the same. What changes is the number on your key tag, and that tells you which door is yours. In /rooms/:roomId, the route is the corridor and :roomId is the tag that picks the door.

Watch it happen

Matching /orders/:orderId/items/:itemId

orders
0
A102
1
items
2
7
3

1/5Request path /orders/A102/items/7 is split into four segments.

The big ideas

What you need to know

:name captures a segment

Whatever sits in that part of the URL lands in req.params.name.

Always strings

req.params.id is "7", not 7. Convert with Number() and check it isn't NaN.

Nest for relationships

/users/:userId/orders reads naturally: the orders belonging to that user.

app.param for reuse

app.param("orderId", loader) runs once per request to load the order for every route that uses :orderId.

See it in code

Walk through the code

js
1app.get("/users/:userId/orders/:orderId", async (req, res) => {2  const userId = Number(req.params.userId);3  if (!Number.isInteger(userId) || userId <= 0) {4    return res.status(400).json({ error: "userId must be a positive integer" });5  }6 7  const order = await db.orders.findOne({8    id: req.params.orderId,9    userId,10  });11  if (!order) return res.status(404).json({ error: "Order not found" });12  res.json(order);13});

1/4Two parameters in one path: the user and the order.

Checking that the order belongs to that user is not just tidy; it stops one user reading another user's orders by changing the URL.

Save yourself the pain

Common mistakes

Oops

Using req.params.id in a database query without checking the user owns that record.

Do this instead

Always filter by the logged-in user too. Otherwise anyone can guess ids and read others' data.

Oops

Comparing req.params.id === 7 and wondering why it's never true.

Do this instead

Params are strings. Compare with "7" or convert with Number() first.

Your mission

Nested resources

~20 min

Quick check

Route /products/:id, request /products/15. What is req.params.id?

Go deeper

  1. 1Build GET /api/products/:id that returns one item or a 404.
  2. 2Read optional filters such as ?category=books from req.query.
  3. 3Remember that params and query values always arrive as strings, so convert numbers yourself.

Also part of these roadmaps

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge