Have you notice something like this in your url. It sometimes look like this 👇
https://x.com/Kunalmadoliya
and sometimes like this 👇
https://www.x.com/in/kunal-madoliya-0378133b4/?skipRedirect=true
Technically there are no difference in both. What is the advantage of one is disadvantage for the other
In this blog topic to cover :
- What URL parameters are
- What query parameters are
- Differences between them
- When to use params vs query
URL / Path parameters
We use URL parameter to access a specific resource on the server. For example if you want to find a user by ID.
We can simply implement this simple code with a URL parameter
app.get("/:username", (req, res) => {
res.send(req.params.username)
})
Everything we enter after the slash will be handle by Express.js for example you want to do a database query based on the username or id depends on the usecase
Twitter uses URL parameter.
https://x.com/Kunalmadoliya
Query parameters
We use query parameters when the data is dynamic. For example if you want to filter, search , sort a mobile from a bunch of different mobile brands we use Query parameters.
for example :
// localhost/product?brand=iphone&price=23000
app.get("/product", (req, res) => {
res.send(req.query.brand + " " + req.query.price)
})
Query parameters works also the same way. All parameters that have been received are available in the req.query object
A new parameter is always marked by the question mark ?
We can pass multiple parameters in the URL but we do not need another question mark for it.
Differences between URL and Query parameters
| Point | URL Parameter | Query Parameter |
|---|---|---|
| What is it? | Value written inside the URL path | Value written after ? in the URL |
| Example | /users/101 | /users?id=101 |
| Used for | Access a specific resource | Send extra data like search or filter |
| URL Look | Clean and readable | Can become long and messy |
| Mostly used in | Dynamic routes | Search, filter, pagination |
When to use URL and Query parameters
URL parameter :- For clean , small , search engine friendly URLs that lead to a static resource
Query parameters :- For longer , more readable URLs , These are not relevant to search engines
Thanks for reading ! if enjoyed this blog , you can read more on this 👇
Top comments (0)