← Back to Node.js, page 5

nodejs-0083 · Easy fresher

How do the URL and URLSearchParams classes work, and how do they differ from the legacy url.parse and querystring modules?

URL is the standard (WHATWG) parser available in Node and browsers. It splits an address into protocol, host, pathname, search and hash, and URLSearchParams reads and builds the query string with correct encoding. The legacy url.parse() and the querystring module are older, behave differently on edge cases and should not be used in new code.

Full answer

new URL(input, base) parses an absolute address, or a relative one with a base. It throws a TypeError on invalid input, and URL.canParse(input) checks without throwing (Node 19.9 and later).

Properties: protocol ('https:'), username and password, hostname, port (a string, empty for the default), host (hostname plus port), pathname ('/a/b'), search ('?x=1'), hash ('#top'), origin, href. Properties can be set, and the URL updates and re-encodes itself.

URLSearchParams works on the query:

  • url.searchParams.get('x') returns the first value or null. getAll('x') returns all. has, set (replace), append (add another), delete, sort.
  • Iteration gives [key, value] pairs. new URLSearchParams({ a: 1 }) or from an array of pairs builds one. toString() gives an encoded string.
  • Values are decoded and encoded for you: a space becomes + in the query string form, special characters become %XX.

Why not string concatenation: 'https://x.com/?q=' + term breaks when term has &, = or #, and it can allow parameter injection. Use searchParams.set or append.

Legacy APIs:

  • url.parse() has inconsistent parsing and was involved in security issues, because different parsers read the same string in different ways. It is deprecated.
  • querystring.parse and stringify handle repeated keys and encoding slightly differently from URLSearchParams. Prefer URLSearchParams.
  • url.fileURLToPath and pathToFileURL convert between file URLs and paths, which matters in ES modules.

The URL parser also normalizes: lower-cases the host, removes the default port, resolves ../ segments and converts IP forms such as 0x7f.1 to 127.0.0.1.

javascript
const url = new URL('https://user:pass@Schoolabe.com:443/courses/node/../react?level=fresher&tag=a&tag=b#reviews');

console.log('protocol:', url.protocol, '| hostname:', url.hostname, '| port:', JSON.stringify(url.port));
console.log('pathname (resolved):', url.pathname, '| hash:', url.hash, '| origin:', url.origin);
console.log('get level:', url.searchParams.get('level'), '| getAll tag:', url.searchParams.getAll('tag'));

// Building a query safely: special characters are encoded for you.
const search = new URL('https://schoolabe.com/search');
search.searchParams.set('q', 'node & express #1');
search.searchParams.append('page', 2);
console.log('built:', search.href);

// set replaces, append adds, delete removes.
search.searchParams.set('page', 3);
search.searchParams.delete('q');
console.log('after set and delete:', search.search);

// Relative addresses need a base.
console.log('resolved:', new URL('../fees?plan=pro', 'https://schoolabe.com/courses/node/').href);

// Invalid input
console.log('canParse("not a url"):', URL.canParse('not a url'), '| canParse("http://x.org"):', URL.canParse('http://x.org'));

// The parser normalizes odd host spellings.
console.log('0x7f.1 becomes:', new URL('http://0x7f.1/').hostname);

// Iteration and conversion
const params = new URLSearchParams({ a: '1', b: 'two words' });
console.log('entries:', [...params], '| string:', params.toString());
console.log('to object (last value wins):', Object.fromEntries(new URLSearchParams('x=1&x=2&y=3')));

The parser removes the default port 443, resolves the .. segment and lower-cases the host. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): protocol: https: | hostname: schoolabe.com | port: "" pathname (resolved): /courses/react | hash: #reviews | origin: https://schoolabe.com get level: fresher | getAll tag: [ 'a', 'b' ] built: https://schoolabe.com/search?q=node+%26+express+%231&page=2 after set and delete: ?page=3 resolved: https://schoolabe.com/courses/fees?plan=pro canParse("not a url"): false | canParse("http://x.org"): true 0x7f.1 becomes: 127.0.0.1 entries: [ [ 'a', '1' ], [ 'b', 'two words' ] ] | string: a=1&b=two+words to object (last value wins): { x: '2', y: '3' }

Key points

  • new URL(input, base) parses and normalizes.
  • searchParams handles encoding. Do not concatenate query strings.
  • URL.canParse checks without exceptions.
  • url.parse and querystring are legacy.

Common mistakes

  • Building query strings by joining text.
  • Forgetting that searchParams.get returns a string or null.
  • Calling new URL on user input without try/catch.
  • Using Object.fromEntries on repeated keys and losing values.

Follow-ups

  • Why is url.parse considered unsafe?
  • How does URLSearchParams encode a space?
  • How do you convert a file URL to a path?

Tips

  • Use the set versus append difference as a quick check.
  • Mention URL.canParse.
  • Say 'never concatenate query strings'.