Create a URL with search params
Build a URL with query parameters using URL and searchParams, and see how spaces and ampersands are encoded, plus how to resolve a relative path. Node.js 18.
Gluing a query string together with template literals breaks the first time a value contains &. URL and its searchParams do the encoding, and Node.js 24 gives the output below.
const url = new URL('https://api.example.test/search');
url.searchParams.set('q', 'node & typescript');
url.searchParams.append('tag', 'a');
url.searchParams.append('tag', 'b');
url.searchParams.set('page', 2);
console.log(url.href);
console.log(url.search);
console.log(new URL('/v2/items?x=1', 'https://api.example.test/v1/').href);
console.log(new URLSearchParams({ q: 'a b', empty: '' }).toString());https://api.example.test/search?q=node+%26+typescript&tag=a&tag=b&page=2
?q=node+%26+typescript&tag=a&tag=b&page=2
https://api.example.test/v2/items?x=1
q=a+b&empty=searchParams.set() replaces a parameter and append() adds another with the same name, so tag appears twice. The value node & typescript came out as node+%26+typescript: the ampersand is percent-encoded and the space becomes a plus, the form encoding that URLSearchParams follows. A number is converted to a string. A second argument to new URL() is a base, and '/v2/items?x=1' against https://api.example.test/v1/ resolves to the host's root path, dropping v1. The rules are in the WHATWG URL Standard.
Passing an object to new URLSearchParams() is the shortest way to build a query, but it cannot repeat a name, so use an array of pairs for that. The plus for a space is correct in a query string and wrong in a path, where %20 is used, so do not paste url.search into a path segment.