Handling Route Parameters in Express.js

🚀 Introduction

Route parameters are dynamic values embedded directly within a URL path. They allow an Express.js application to capture specific information from the URL, such as user IDs, product IDs, or category names. Route parameters are defined using a colon (:) and are accessed through the req.params object.

Information

Route parameters are commonly used to identify a specific resource, such as a user, product, blog post, or order.

📋 Prerequisites

  • Node.js installed.
  • Express.js installed.
  • A basic Express.js server created.
  • Basic understanding of Express routing.

❓ What Are Route Parameters?

Route parameters are placeholders within a route path that capture values from the requested URL. Each parameter is prefixed with a colon (:), and Express automatically stores the extracted values inside the req.params object.

RouteRequest URLParameter Value
/users/:id/users/101id = 101
/products/:productId/products/25productId = 25
/posts/:slug/posts/express-routingslug = express-routing

🌐 Route Parameter Structure

URL
Static Path
Route Parameter
Example Request
/users
:id
/users/101

📝 Creating a Route with Parameters

Single Route Parameter

const express = require('express');

const app = express();

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

  res.send(`User ID: ${userId}`);
});

app.listen(3000);

If a client visits http://localhost:3000/users/101, Express extracts the value 101 and stores it in req.params.id.

📤 Example Response

Response

User ID: 101

📌 Multiple Route Parameters

A route can contain more than one parameter. Each parameter is identified by its unique name.

Multiple Route Parameters

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

Example request:
/users/15/orders/250

📤 JSON Response

Response

{
  "userId": "15",
  "orderId": "250"
}

đŸ”ĸ Converting Route Parameters

Route parameter values are received as strings. Convert them when numeric operations are required.

Convert Parameter to Number

app.get('/products/:id', (req, res) => {
  const productId = Number(req.params.id);

  res.send(`Product ID: ${productId}`);
});

Tip

Use Number() or parseInt() when you need numeric values for calculations or database queries.

📌 Route Parameters with Multiple Segments

Category and Product

app.get('/category/:category/product/:productId', (req, res) => {
  res.json({
    category: req.params.category,
    productId: req.params.productId
  });
});

Example request:
/category/electronics/product/101

📊 Common Use Cases

Use CaseExample Route
User Profile/users/:id
Product Details/products/:id
Blog Post/posts/:slug
Order Information/orders/:orderId
Category Products/categories/:name

🔄 Route Matching Process

📌 Route Parameters vs Query Parameters

FeatureRoute ParametersQuery Parameters
LocationPart of the URL pathAfter the ? symbol
Access Methodreq.paramsreq.query
PurposeIdentify a specific resourceFilter, search, sort, or paginate data
Example/users/101/users?page=2

âš ī¸ Validating Route Parameters

Simple Validation

app.get('/users/:id', (req, res) => {
  const id = Number(req.params.id);

  if (isNaN(id)) {
    return res.status(400).send('Invalid User ID');
  }

  res.send(`User ID: ${id}`);
});

Warning

Always validate route parameters before using them in database queries or business logic to prevent errors and improve application security.

💡 Best Practices

  • Use route parameters to identify specific resources.
  • Choose descriptive parameter names such as :userId or :productId.
  • Validate parameter values before processing them.
  • Convert numeric parameters to numbers when required.
  • Use query parameters for optional filtering and route parameters for resource identification.
  • Keep route URLs clean, readable, and RESTful.

Best Practice

Follow RESTful URL conventions by using route parameters for uniquely identifying resources. For example, use /users/:id instead of /getUser?id=1.

📚 Learn More

Explore the official Express.js documentation for routing:
â€ĸ Express.js Routing Guide
â€ĸ Express.js Request - req.params

📝 Summary

Summary

Route parameters enable Express.js applications to capture dynamic values directly from URL paths using the req.params object. They are ideal for identifying specific resources such as users, products, or orders. By validating parameter values and following RESTful design principles, you can create clean, secure, and maintainable web applications.