Node.js theorytheory 0/50 · 0%
Networking · easy

17. Query strings and URLs

Parsing request URLs safely with the URL API.

Rather than parsing URLs by hand, use the standard `URL` class (available globally in Node), which parses the protocol, host, pathname, and query string into structured pieces.

js
const url = new URL("https://api.example.com/tokens?chain=base&limit=20");
console.log(url.pathname);              // "/tokens"
console.log(url.searchParams.get("chain")); // "base"
console.log(url.searchParams.get("limit")); // "20"

for (const req of ["/tokens?chain=base"]) {
  const parsed = new URL(req, "http://localhost"); // base URL needed for relative paths
  console.log(parsed.searchParams.get("chain"));
}

For relative request URLs (as seen inside an http handler, e.g. `req.url`), pass a base URL as the second argument to `URL` so it can resolve into an absolute one.

Check your understanding

  1. 1. Which built-in class parses a URL into pathname, query params, etc.?

  2. 2. How do you read a query parameter named 'chain'?

  3. 3. Why pass a base URL as the second argument to `new URL(...)`?