CodingNic

Express.js Fundamentals

Route Parameters

Express.js Fundamentals 8 min read

Route Parameters

Objectives

By the end of this lesson, you should be able to:

  • Capture a dynamic segment of a URL using a route parameter
  • Read a route parameter’s value from req.params
  • Use multiple route parameters in a single route

💡 Why this matters: A real API needs routes like /users/42 or /posts/17/comments/3, where the number is dynamic, not a fixed path. Route parameters are how Express captures that dynamic piece without writing a separate route for every possible ID.

⚠️ A note on verification: every snippet and every response shown below was actually run and tested with real HTTP requests.

A Single Route Parameter

javascript
const express = require('express');
const app = express();

app.get('/users/:id', (req, res) => {
  res.json({ userId: req.params.id });
});

app.listen(4004);
bash
curl http://localhost:4004/users/42
text
{"userId":"42"}

A colon (:) before a segment name in a route path marks it as a route parameter, :id matches any value in that position, and Express makes it available as req.params.id. Route parameters are always strings, req.params.id here is "42", not the number 42, converting it (with Number()) is the caller’s responsibility if a number is needed.

Multiple Route Parameters

javascript
app.get('/users/:userId/posts/:postId', (req, res) => {
  res.json({ userId: req.params.userId, postId: req.params.postId });
});
bash
curl http://localhost:4004/users/7/posts/99
text
{"userId":"7","postId":"99"}

A single route can capture as many parameters as needed, req.params holds all of them, one property per named segment, keyed by the name after the colon.

Try It

  1. Write a route /products/:productId returning { productId: req.params.productId } as JSON, and test it with several different IDs.
  2. Write a route /categories/:categoryId/items/:itemId capturing both parameters, and confirm both appear correctly in the response.
  3. Convert a captured :id parameter to a number with Number(req.params.id), and confirm typeof the converted value is "number" while the original req.params.id is "string".
  4. Explain, in your own words, why route parameters are always strings, even when the URL segment looks like a number.

Recap

  • :name in a route path captures a dynamic URL segment, available as req.params.name.
  • A route can have multiple parameters, all available on req.params at once.
  • Route parameter values are always strings, converting them is the handler’s responsibility.

Next lesson: query parameters, reading values from a URL’s ?key=value portion.