URL Parameters vs Query Strings in Express.js
Introduction
When building APIs with Express.js, handling client input via URLs is fundamental. Two of the most commonly used mechanisms are:
URL Parameters (Route Params)
Query Strings (Query Params)
What URL Parameters Are?
URL parameters are parts of the URL path used to identify a specific resource.
Example:
Fetching details of a user with given id
/users/42
In Express:
app.get('/users/:id', (req, res) => {
const userId = req.params.id;
res.send(`User ID is ${userId}`);
});
What Query Parameters Are?
Query parameters are key-value pairs appended to the URL after a ?.
Example:
/users?age=25&city=Mumbai
Now we are asking users whose age is 25 and city is Mumbai. It's kind of filtering.
In Express:
app.get('/users', (req, res) => {
const { age, city } = req.query;
res.send(`Age: \({age}, City: \){city}`);
});
Query Parameters are not only used for Filtering but also sorting and pagination
Differences Between URL Params and Query Strings
| Feature | URL Parameters | Query Parameters |
|---|---|---|
| Location | Part of URL path | After ? in URL |
| Purpose | Identify specific resource | Modify/filter data |
| Required | Usually required | Usually optional |
| Example | /users/10 |
/users?age=20 |
| Express Access | req.params |
req.query |
When to use params vs query?
Use URL Parameters When:
You are accessing a specific resource
The value is mandatory
It defines the identity of the resource
Example:
GET /users/123
GET /orders/987
Use Query Parameters When:
You are filtering or modifying results
The values are optional
You are dealing with lists or searches
Example:
GET /users?age=25
GET /products?category=electronics&sort=price

