Introduction
Query parameters are key-value pairs appended to the end of a URL after a ? character. They are commonly used to filter data, search records, sort results, paginate responses, or pass optional information to the server. In Node.js, the built-in http module provides the request URL, which can be parsed using the standard URL class to easily access query parameters.
Information
What are Query Parameters?
Query parameters appear after the path in a URL. Each parameter consists of a name and a value separated by an equals sign (=). Multiple parameters are separated using an ampersand (&).
| Example URL | Query Parameters |
|---|---|
| /products?category=books | category=books |
| /search?q=nodejs&page=2 | q=nodejs, page=2 |
| /users?id=10&active=true | id=10, active=true |
URL Structure
Parsing the URL
The URL class parses the incoming request URL into useful components such as the pathname and query parameters.
Parsing the request URL
const http = require("http");
const server = http.createServer((req, res) => {
const url = new URL(req.url, "http://localhost:3000");
console.log(url.pathname);
console.log(url.search);
res.end("URL parsed");
});
server.listen(3000);Accessing Query Parameters
The searchParams property provides methods to retrieve query parameter values.
Reading query parameters
const http = require("http");
const server = http.createServer((req, res) => {
const url = new URL(req.url, "http://localhost:3000");
const name = url.searchParams.get("name");
const age = url.searchParams.get("age");
res.writeHead(200, {
"Content-Type": "application/json"
});
res.end(JSON.stringify({
name,
age
}));
});
server.listen(3000);Example Request
Request URL
GET /?name=Alice&age=25 HTTP/1.1
Host: localhost:3000Example Response
JSON response
{
"name": "Alice",
"age": "25"
}Handling Multiple Query Parameters
APIs often receive several query parameters simultaneously for filtering, sorting, and pagination.
Reading multiple parameters
const url = new URL(req.url, "http://localhost:3000");
const category = url.searchParams.get("category");
const sort = url.searchParams.get("sort");
const page = url.searchParams.get("page");
console.log(category);
console.log(sort);
console.log(page);Example URL
Multiple query parameters
GET /products?category=electronics&sort=price&page=2 HTTP/1.1
Host: localhost:3000Using Query Parameters for Search
Query parameters are frequently used to implement search functionality.
Search endpoint
const http = require("http");
const server = http.createServer((req, res) => {
const url = new URL(req.url, "http://localhost:3000");
if (url.pathname === "/search") {
const keyword = url.searchParams.get("q");
res.writeHead(200, {
"Content-Type": "application/json"
});
res.end(JSON.stringify({
search: keyword
}));
return;
}
res.writeHead(404);
res.end();
});
server.listen(3000);Checking for Missing Parameters
If a parameter does not exist, the get() method returns null. Your application should validate required parameters before processing the request.
Validate required query parameters
const id = url.searchParams.get("id");
if (!id) {
res.writeHead(400, {
"Content-Type": "application/json"
});
return res.end(JSON.stringify({
error: "Missing id parameter"
}));
}Important
Retrieving All Values for the Same Parameter
A URL may contain the same query parameter multiple times. Use the getAll() method to retrieve every value.
Using getAll()
const tags = url.searchParams.getAll("tag");
console.log(tags);
// URL:
// /posts?tag=node&tag=javascript&tag=httpExpected Output
Result
[
"node",
"javascript",
"http"
]Useful searchParams Methods
| Method | Description |
|---|---|
| get(name) | Returns the first matching value. |
| getAll(name) | Returns all matching values. |
| has(name) | Checks whether a parameter exists. |
| entries() | Returns all parameter name-value pairs. |
| keys() | Returns all parameter names. |
| values() | Returns all parameter values. |
Typical Request Flow
Practical Use Cases
- đ Search functionality.
- đ Pagination using page and limit.
- đ Filtering records by category or status.
- âī¸ Sorting results using fields such as sort.
- đ¯ Optional request customization.
Best Practices
- Use the URL class instead of manually parsing URLs.
- Validate required parameters before processing requests.
- Return meaningful HTTP status codes for invalid input.
- Convert numeric values using Number() or parseInt() when needed.
- Provide sensible default values for optional parameters.
Best Practice
Common Mistakes
| Mistake | Recommended Solution |
|---|---|
| Manually splitting the URL string | Use the built-in URL class. |
| Ignoring missing parameters | Validate required inputs. |
| Treating numbers as strings | Convert values before using them. |
| Not handling invalid input | Return a 400 Bad Request response. |
Official Documentation
Node.js URL API Documentation and Node.js HTTP Module Documentation