Query strings carry key-value filters, search terms, and pagination options after the ? in a URL (such as ?search=node+js&page=2). While Node.js still ships the legacy node:querystring module, modern codebases use the standard URLSearchParams API because it handles encoding cleanly and works identically in browsers.
URLSearchParamsURLSearchParams accepts either a raw query string ('?q=books&limit=10'), an object literal, or an array of [key, value] tuples. It automatically percent-encodes spaces, &, =, and Unicode characters so user input never corrupts the URL.
// 1. Build a query string safely from an object
const params = new URLSearchParams({
q: 'Node.js & Streams',
page: '2',
sort: 'latest',
});
params.append('tag', 'backend');
params.append('tag', 'async');
console.log('Encoded query:', params.toString());
// 2. Parse an incoming query string
const parsed = new URLSearchParams('?q=Node.js+%26+Streams&tag=backend&tag=async');
console.log('Search query:', parsed.get('q'));
console.log('Tags array:', parsed.getAll('tag'));
Notice how .get('tag') returns only the first matching value, whereas .getAll('tag') returns every repeated value as an array—handy for multi-select checkboxes and filter chips.
node:querystringNode's official documentation places node:querystring in maintenance/legacy status in favor of URLSearchParams. Note one key difference: new URLSearchParams() strips a leading ? automatically, whereas querystring.parse('?a=1') leaves the ? attached to the key name '?a'.
`?q=${userInput}`: An unescaped & or # inside userInput breaks the query string or drops remaining parameters. Always use URLSearchParams.URLSearchParams with Object.fromEntries(params) when keys repeat: Object.fromEntries() silently drops earlier values when a key appears multiple times (like tag=a&tag=b). Read repeated keys with params.getAll('tag').'0' and 'false' are truthy strings in JS; parse numbers with Number() and validate ranges before querying your database.{ limit: undefined } to new URLSearchParams()?URLSearchParams converts undefined into the literal string 'undefined'! Filter out undefined and null keys before building query strings.
+ vs %20 in query strings?URLSearchParams follows the application/x-www-form-urlencoded spec, automatically decoding both + and %20 back into spaces when calling .get().
URLSearchParams handle prototype-pollution keys like __proto__ safely?Yes. Because URLSearchParams stores entries internally rather than assigning properties onto a plain {} object, __proto__ keys do not pollute Object.prototype.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.