Query string
- Node.js course
- Intermediate
- Lesson 17/116
- 5 min
Learn to parse URL query strings.
Query string
A query string is the key=value pairs that come after the ? in a URL. Example: in /greet?name=Alex the name=Alex part is a query string.
To parse a query string in Node.js you use new URL(req.url, base). This gives a URL object; url.searchParams.get("name") retrieves a key's value. Example: const url = new URL(req.url, "http://localhost"); const name = url.searchParams.get("name");. The base is required because req.url is a relative path; without a full URL URL cannot parse it. This is the standard way for search, filtering and form parameters.
Using searchParams
The URL object's searchParams property is a URLSearchParams object. With .get("key") you get a single value; with .has("key") you check if a key exists.
Example: const url = new URL("/greet?name=Alex&age=30", "http://localhost"); url.searchParams.get("name"); gives Alex; url.searchParams.get("age") gives 30. If the key is missing, get returns null. For keys with multiple values, getAll is used. This structure is the built-in way to parse URL parameters safely; it is safer than doing split by hand.
Practice Read a value from the query string
Import the http module. Create a server with createServer. Inside the handler create a url with new URL(req.url, "http://localhost"), get name with url.searchParams.get("name") and respond with res.end("Hello " + name). The ready-made code below sends a request to /?name=Alex.
Starter code
// Import the http module and create a server
// write here
server.listen(3000, () => {
http.get("http://localhost:3000/?name=Alex", (res) => {
let body = "";
res.on("data", (c) => body += c);
res.on("end", () => { console.log("Reply: " + body); server.close(); });
});
});Sample solution
const http = require("http");
const server = http.createServer((req, res) => {
const url = new URL(req.url, "http://localhost");
const name = url.searchParams.get("name");
res.end("Hello " + name);
});
server.listen(3000, () => {
http.get("http://localhost:3000/?name=Alex", (res) => {
let body = "";
res.on("data", (c) => body += c);
res.on("end", () => { console.log("Reply: " + body); server.close(); });
});
});Expected output
Yanıt: Merhaba Ayşe
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Where is the query string found in a URL?
/selam?ad=Ayşe- After the ? sign Correct answer
- After the port number
- After the # sign
- In the header
Explanation: The query string comes after the ? mark.
2 Complete the searchParams.get call
const ad = url.searchParams.____("ad");
const ad = url.searchParams.get("ad");
Explanation: get gives the value of a key.
3 Match each piece to its role
| Term | Meaning |
|---|---|
new URL |
Creates a URL object |
searchParams.get |
Gives a key's value |
"?" |
Query string start |
base |
Foundation for relative path |