Lesson 24 +10 XP

Route Parameters (req.params) & Query Strings (req.query)

Path Parameters vs Query Parameters

Express allows capturing URL variables via named route parameters (req.params) and query strings (req.query).

1. Dynamic Route Parameters (req.params)

Used to identify a specific resource entity by ID or unique slug.

// GET /api/v1/categories/tech/products/99
app.get("/api/v1/categories/:categoryName/products/:productId", (req, res) => {
  const { categoryName, productId } = req.params;
  res.json({ category: categoryName, id: Number(productId) });
});

2. Query String Parameters (req.query)

Used for filtering, sorting, pagination, and searching options across collections.

// GET /api/v1/products?search=phone&page=2&limit=20&sort=-price
app.get("/api/v1/products", (req, res) => {
  const { search = "", page = 1, limit = 10, sort = "createdAt" } = req.query;

  res.json({
    appliedFilters: {
      searchTerm: search,
      pageNumber: Number(page),
      pageSize: Number(limit),
      sortBy: sort
    }
  });
});

When to Use Which?

  • Use req.params for mandatory resource identification (/users/:id).
  • Use req.query for optional parameters like pagination, sorting, or filtering (?page=1&sort=asc).

TL;DR

  • Route tokens preceded by : populate req.params.
  • URL query parameters after ? populate req.query.