What is the difference between route parameters and query strings in Express?
Route parameters are part of the path, like /users/42, and identify a specific resource, read from req.params. Query strings follow a question mark, like ?page=2, and filter or tweak a request, read from req.query.
Explain it simply
Think of an IRCTC ticket. The PNR number identifies exactly one booking: that is a route parameter. Filters such as "AC only" or "sort by price" change how a list is shown without identifying a single thing: those are query parameters.
Example
const express = require("express");
const app = express();
// GET /students/42
app.get("/students/:id", (req, res) => {
res.json({ id: req.params.id }); // "42" (a string)
});
// GET /students?branch=cse&page=2
app.get("/students", (req, res) => {
const { branch = "all", page = "1" } = req.query;
res.json({ branch, page: Number(page) });
});
// GET /courses/web/lessons/3
app.get("/courses/:course/lessons/:n", (req, res) => {
res.json(req.params); // {"course":"web","n":"3"}
});Rules of thumb:
- Use params for identity: which student, which order.
- Use query strings for optional filtering, sorting and pagination.
- Both arrive as strings, so convert with
Number()and validate. - Query values can also be arrays or objects (
?tag=a&tag=b), so never assume a string.
What to say in the interview
"Params are path segments identifying a resource, in req.params; query strings are optional key-value filters after the question mark, in req.query. Both are strings and untrusted, so I validate and convert them."
Common mistakes
- Using
req.params.idas a number without conversion, so"2" + 1becomes"21". - Putting secrets in query strings, which end up in logs.