devnotes.

Working with Query Strings

Look at almost any URL with a search or filter applied — ?category=books&sort=price&page=2 — and that part after the ? is a query string: a simple key-value format for passing small pieces of data to a server through the URL itself, most often paired with a GET request.

Reading query parameters with the modern URL API

const { URL } = require('url');

const myUrl = new URL('https://shop.example.com/products?category=books&page=2');

console.log(myUrl.searchParams.get('category')); // 'books'
console.log(myUrl.searchParams.get('page'));      // '2' — always a string, never a number
console.log(myUrl.searchParams.has('sort'));      // false — not present in this URL

Every value read from a query string comes back as a string, even something that looks numeric like '2' — worth remembering when you go to use it in a calculation, since '2' + 1 gives '21', not 3.

Reading query parameters inside an actual server

const http = require('http');

http.createServer((req, res) => {
  const requestUrl = new URL(req.url, `http://${req.headers.host}`);
  const category = requestUrl.searchParams.get('category');
  const page = Number(requestUrl.searchParams.get('page')) || 1;

  res.end(`Showing ${category || 'all'} products, page ${page}`);
}).listen(3000);

req.url only contains the path and query string, not the full URL — passing a base URL (built from req.headers.host) as the second argument to new URL() is what lets this work correctly.

Building a query string from an object — the reverse direction

const params = new URLSearchParams({
  category: 'electronics',
  sort: 'price',
  page: '1'
});

console.log(params.toString()); // 'category=electronics&sort=price&page=1'
console.log(`https://shop.example.com/products?${params.toString()}`);

This is the common pattern for constructing a URL dynamically — say, when your code needs to call an external API with parameters computed at runtime, rather than hand-assembling a string with manual & and = characters (which is easy to get subtly wrong, especially with special characters that need URL-encoding).

The older querystring module, briefly

An older core module, querystring, does a similar job with a slightly different, less modern API:

const querystring = require('querystring');

const parsed = querystring.parse('category=books&page=2');
console.log(parsed); // { category: 'books', page: '2' }

const built = querystring.stringify({ category: 'books', page: 2 });
console.log(built); // 'category=books&page=2'

It still works and you'll see it in older codebases, but URL/URLSearchParams is the modern, generally recommended choice for new code — it's a web-standard API (the same one browsers use), not a Node.js-specific one.

Working with Query Strings | DevNotes