VOOZH about

URL: https://www.geeksforgeeks.org/node-js/how-to-handle-route-parameters-in-express/

⇱ Handle Route Parameters in Express - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Handle Route Parameters in Express

Last Updated : 19 Sep, 2025

Route parameters in Express.js are dynamic URL segments defined with a colon (:) and accessed via req.params, enabling efficient handling of variable data such as IDs in RESTful routes.

Syntax:

app.get('/users/:id', (req, res) => {
const userId = req.params.id;
res.send(`User ID is: ${userId}`);
});

In the above syntax:

  • :id: defines the route parameter.
  • req.params.id: retrieves the value from the URL.

Here are the different ways to handle route parameters in Express.js include basic, optional, and multiple parameters.

1. Basic Route Parameter Handling

Basic route parameters capture dynamic values directly from the URL. They are defined with a colon (:) in the route path and accessed via req.params inside the route handler.

Now let's understand this with the help of example:

Output: Accessing http://localhost:3000/users/123 will display

👁 UserProfile
Basic Route Parameter Handling

In this example:

  • /users/:userId: :userId is a route parameter that captures the value after /users/.
  • req.params.userId: Access the captured value and use it in the route handler for further logic.

2. Optional Route Parameters

Optional route parameters allow a URL segment to be omitted without breaking the route. They are defined by adding a question mark (?) after the parameter name. If the parameter is not provided, a default value can be used.

Now let's understand this with the help of example:

Output: Accessing http://localhost:3000/products/123 will display

👁 Route-Parameters-in-Express
Route Parameters

In this example:

  • /products/:productId?: :productId is optional, meaning the route will match with or without the productId.
  • req.params.productId || 'default': If no productId is provided, 'default' will be used instead.

Accessing http://localhost:3000/products/ will display

Product Page
Product ID: default

3. Multiple Route Parameters

Express allows you to define multiple route parameters in a single route. You can capture several dynamic values from the URL by adding multiple colon-prefixed parameters.

Now let's understand this with the help of example:

Output Accessing http://localhost:3000/posts/tech/456 will display

👁 Post-
Multiple Route Parameters

In this example:

  • /posts/:category/:postId: The route captures both category and postId from the URL.
  • req.params.category and req.params.postId: Access the captured values for use in the handler.
Comment

Explore