URL Parameters vs Query Strings in Express.js
What are URL Parameters (Route Params)?
URL parameters are dynamic values inside the URL path used to identify a specific resource.
Think: “Which exact thing?” (identifier)
Example:
/users/42
Here:
42= user ID (specific user)
In Express:
app.get('/users/:id', (req, res) => {
console.log(req.params.id); // 42
});
:id is a placeholder
Value comes from the URL path
What are Query Parameters?
Query parameters are key-value pairs added after ? in a URL used to modify or filter data.
Think: “How do I want the data?” (filters/modifiers)
Example:
/users?age=20&sort=asc
Here:
age=20→ filtersort=asc→ modifier
In Express:
app.get('/users', (req, res) => {
console.log(req.query.age); // 20
console.log(req.query.sort); // asc
});
Differences (Clear & Practical)
| Feature | URL Params | Query Params |
|---|---|---|
| Purpose | Identify resource | Filter / modify data |
| Position | Inside URL path | After ? |
| Example | /users/42 |
/users?age=20 |
| Required? | Usually required | Usually optional |
| Meaning | “Which user?” | “Which type of users?” |
Real Examples
1. User Profile (Identifier → URL Param)
GET /users/42
You are asking:
“Give me user with ID 42”
req.params.id
2. Search / Filters (Modifiers → Query Params)
GET /products?category=shoes&price=1000
You are asking:
“Give me products filtered by category and price”
req.query.category
req.query.price
3. Combined Usage (Real-World API)
GET /users/42/posts?sort=latest&limit=5
Meaning:
42→ which user (param)sort,limit→ how to fetch posts (query)
Accessing in Express
app.get('/users/:id', (req, res) => {
const userId = req.params.id; // identifier
const filter = req.query.sort; // modifier
res.send({ userId, filter });
});
When to Use Params vs Query
Use URL Params when:
You are targeting one specific resource
Required for the request to make sense
Examples:
/users/42
/orders/1001
/posts/abc123
Use Query Params when:
You are filtering, sorting, paginating
Optional inputs
Examples:
/users?age=20
/products?sort=price
/posts?page=2
Conclusion
Parameters and queries are important for fetching the required data accurately, parameters help finding exact thing, while using queries helps find the things related to
