Parsing URLs

suggest change

Node.js implements the WHATWG URL Standard, the same URL parser that browsers use. It's exposed as two global classes:

Both are globals, so there's nothing to import. The node:url module adds helpers for converting between URLs and file paths and a few formatting functions.

The older url.parse() and the querystring module still exist but are legacy. Don't use them in new code (see the last section).

All examples were run with Node.js 24 as ES modules (.mjs files).

Parts of a URL

new URL(input) parses an absolute URL and gives you an object with a property for each part:

const url = new URL(
  'https://user:pa%20ss@www.example.com:8080/docs/guide/index.html?lang=en&page=2#install'
);

for (const k of ['href', 'origin', 'protocol', 'username', 'password',
                 'host', 'hostname', 'port', 'pathname', 'search', 'hash']) {
  console.log(k.padEnd(9), JSON.stringify(url[k]));
}
href      "https://user:pa%20ss@www.example.com:8080/docs/guide/index.html?lang=en&page=2#install"
origin    "https://www.example.com:8080"
protocol  "https:"
username  "user"
password  "pa%20ss"
host      "www.example.com:8080"
hostname  "www.example.com"
port      "8080"
pathname  "/docs/guide/index.html"
search    "?lang=en&page=2"
hash      "#install"

Things to notice:

Normalization

The parser normalizes what it parses. The scheme and host are lowercased, . and .. segments are resolved and a default port is dropped:

console.log(new URL('HTTPS://EXAMPLE.com/a/./b/../c').href);
console.log(new URL('https://example.com:443/').href);
console.log(JSON.stringify(new URL('https://example.com:443/').port));
console.log(new URL('https://example.com').href);
https://example.com/a/c
https://example.com/
""
https://example.com/

Note the last line: an empty path becomes / for http, https, ws, wss, ftp and file URLs. Comparing URLs as raw strings is therefore unreliable. Parse both and compare href instead.

Non-ASCII characters are encoded too. Host names are converted to Punycode, paths and queries are percent-encoded as UTF-8:

console.log(new URL('https://münchen.de/straße?q=café ü').href);
console.log(new URL('https://example.com/a b/ä').pathname);
https://xn--mnchen-3ya.de/stra%C3%9Fe?q=caf%C3%A9%20%C3%BC
/a%20b/%C3%A4

Handling invalid URLs

new URL() throws a TypeError with code ERR_INVALID_URL when the input isn't a valid absolute URL:

try {
  new URL('/relative/path');
} catch (err) {
  console.log(err.name, err.code, err.message);
}
TypeError ERR_INVALID_URL Invalid URL

Wrapping every parse in try/catch is clumsy, so there are two static helpers:

console.log(URL.canParse('not a url'));
console.log(URL.canParse('mailto:a@b.com'));
console.log(URL.canParse('/x', 'https://a.com'));

console.log(URL.parse('nope'));
console.log(URL.parse('/x', 'https://a.com')?.href);
false
true
true
null
https://a.com/x

Prefer URL.parse() when you need the result anyway: it parses once instead of twice.

Keep in mind that "valid" is a low bar. mailto:a@b.com, javascript:alert(1) and foo:bar are all valid URLs. If you accept URLs from users, also check protocol:

function parseHttpUrl(input) {
  const url = URL.parse(input);
  if (!url || (url.protocol !== 'http:' && url.protocol !== 'https:')) {
    return null;
  }
  return url;
}

console.log(parseHttpUrl('https://example.com/')?.href);
console.log(parseHttpUrl('javascript:alert(1)'));
console.log(parseHttpUrl('example.com'));
https://example.com/
null
null

Resolving relative URLs

The second argument to new URL(input, base) is a base URL. The input is resolved against it the same way a browser resolves a link in a page:

const base = 'https://example.com/docs/guide/intro.html';

for (const rel of ['setup.html', '../api/', '/about', '?q=1', '#top',
                   '//cdn.example.com/lib.js', 'https://other.org/']) {
  console.log(rel.padEnd(26), new URL(rel, base).href);
}
setup.html                 https://example.com/docs/guide/setup.html
../api/                    https://example.com/docs/api/
/about                     https://example.com/about
?q=1                       https://example.com/docs/guide/intro.html?q=1
#top                       https://example.com/docs/guide/intro.html#top
//cdn.example.com/lib.js   https://cdn.example.com/lib.js
https://other.org/         https://other.org/

An absolute input ignores the base completely, and //host/... (a protocol-relative URL) replaces the host. Keep that in mind when the input comes from users.

A common surprise is the trailing slash. A relative path replaces the last segment of the base path, so without a trailing slash the last segment is lost:

console.log(new URL('users', 'https://api.example.com/v1').href);
console.log(new URL('users', 'https://api.example.com/v1/').href);
console.log(new URL('/users', 'https://api.example.com/v1/').href);
https://api.example.com/users
https://api.example.com/v1/users
https://api.example.com/users

When building API clients, store the base URL with a trailing slash and use relative paths without a leading slash.

Reading query parameters with URLSearchParams

url.searchParams is a live URLSearchParams object for the query string. You can also create one directly from a string (a leading ? is allowed):

const p = new URLSearchParams('?tag=node&tag=js&q=hello+world&empty=&flag');

console.log(p.get('tag'));
console.log(p.getAll('tag'));
console.log(p.get('q'));
console.log(JSON.stringify(p.get('empty')), JSON.stringify(p.get('flag')));
console.log(p.get('missing'));
console.log(p.has('flag'), p.has('tag', 'js'), p.size);
node
[ 'node', 'js' ]
hello world
"" ""
null
true true 5

All values are strings. Convert and validate them yourself:

const params = new URL('https://shop.example.com/list?page=3&limit=abc').searchParams;

const page = Number.parseInt(params.get('page') ?? '1', 10);
const limit = Number.parseInt(params.get('limit') ?? '20', 10);

console.log(page, limit, Number.isNaN(limit) ? 20 : limit);
3 NaN 20

URLSearchParams is iterable, yielding [name, value] pairs:

const p = new URLSearchParams('tag=node&tag=js&q=hello');

for (const [name, value] of p) {
  console.log(name, '=', value);
}

console.log(Object.fromEntries(p));
tag = node
tag = js
q = hello
{ tag: 'js', q: 'hello' }

Object.fromEntries() is handy, but for repeated keys only the last value survives. Use getAll() for keys that can repeat.

Building query strings

Create URLSearchParams from an object, an array of pairs or a string, then modify it with append(), set(), delete() and sort():

const q = new URLSearchParams({ q: 'a&b=c', page: 2, lang: 'pl' });

q.append('tag', 'x');   // adds, keeps existing values
q.append('tag', 'y');
q.set('page', 3);       // replaces all values for the key
q.delete('lang');
q.sort();               // stable sort by key, useful for cache keys

console.log(q.toString());
console.log(new URLSearchParams([['a', '1'], ['a', '2']]).toString());
page=3&q=a%26b%3Dc&tag=x&tag=y
a=1&a=2

Non-string values like 2 are converted with String(). Special characters are encoded for you, so you never need to call encodeURIComponent() on values.

The most common use is adding parameters to a URL. Changes to url.searchParams update url.search and url.href immediately:

const url = new URL('https://api.example.com/search');
url.searchParams.set('q', 'café & crème');
url.searchParams.set('limit', 10);

console.log(url.href);

const res = await fetch(url); // fetch() accepts a URL object
https://api.example.com/search?q=caf%C3%A9+%26+cr%C3%A8me&limit=10

Encoding: + versus %20

URLSearchParams uses the application/x-www-form-urlencoded format, which encodes a space as +. encodeURIComponent() encodes it as %20 and also differs on a few other characters:

console.log(new URLSearchParams({ s: 'a b+c/~*' }).toString());
console.log('s=' + encodeURIComponent('a b+c/~*'));

const url = new URL('https://example.com/?q=a+b');
console.log(url.searchParams.get('q'));
console.log(decodeURIComponent('a+b'));
s=a+b%2Bc%2F%7E*
s=a%20b%2Bc%2F~*
a b
a+b

Both encodings are understood by servers. The trap is decoding: decodeURIComponent() does not turn + into a space. Always read query values with URLSearchParams, not by splitting the string and calling decodeURIComponent().

Modifying a URL

All properties except origin and searchParams are setters. Assigned values are validated and encoded:

const url = new URL('http://localhost:3000/old?x=1');

url.protocol = 'https';      // the colon is optional
url.hostname = 'example.org';
url.port = '';               // remove the port
url.pathname = '/new path';  // encoded to /new%20path
url.search = '';             // remove the query
url.hash = 'top';            // # is added

console.log(url.href);

url.port = '443';            // default port for https is dropped
console.log(url.href);

url.port = 'abc';            // invalid values are silently ignored
console.log(url.href);
https://example.org/new%20path#top
https://example.org/new%20path#top
https://example.org/new%20path#top

Invalid assignments don't throw, they are ignored. Check the result if it matters.

A URL object converts to its href string wherever a string is expected, including JSON.stringify():

const link = new URL('https://a.com/x');
console.log(`${link}`, JSON.stringify({ link }));
https://a.com/x {"link":"https://a.com/x"}

Parsing req.url in an HTTP server

In the node:http server, req.url is only the path and query, for example /hello?name=Ana. new URL() needs an absolute URL, so pass a base:

import http from 'node:http';

const server = http.createServer((req, res) => {
  const url = new URL(req.url, 'http://localhost');
  const name = url.searchParams.get('name') ?? 'world';
  const tags = url.searchParams.getAll('tag');

  res.setHeader('content-type', 'application/json');
  res.end(JSON.stringify({ path: url.pathname, name, tags }));
});

server.listen(3000);
$ curl 'http://localhost:3000/hello?name=Ana%20Maria&tag=a&tag=b'
{"path":"/hello","name":"Ana Maria","tags":["a","b"]}

Any base works if you only need pathname and searchParams. Many examples use `http://${req.headers.host}` as the base, but the Host header comes from the client, so don't trust the resulting hostname or origin for anything security related.

See http server for more about the server itself. Frameworks like Express already parse this for you into req.path and req.query.

Matching paths with URLPattern

URLPattern matches URLs against patterns with named groups and wildcards, similar to routes in web frameworks. It's a global in Node.js 24 (still experimental):

const pattern = new URLPattern({ pathname: '/users/:id/posts/:postId' });

console.log(pattern.test('https://example.com/users/42/posts/7'));
console.log(pattern.exec('https://example.com/users/42/posts/7?x=1').pathname.groups);
console.log(pattern.exec('https://example.com/users/42'));

const images = new URLPattern('https://*.example.com/files/*.:ext(jpg|png)');
const m = images.exec('https://cdn.example.com/files/2024/cat.png');
console.log(m.hostname.groups, m.pathname.groups);
true
{ id: '42', postId: '7' }
null
{ '0': 'cdn' } { '0': '2024/cat', ext: 'png' }

Parts not given in the pattern object match anything, so the first pattern accepts any protocol, host and query.

Validating redirect targets

A classic use of URL parsing is preventing open redirects: a login page that accepts ?next=/account must not redirect to another site. String checks like startsWith('/') fail on inputs like //evil.com. Resolve against your own origin and compare origins instead:

function safeRedirect(target, base) {
  const url = URL.parse(target, base);
  if (!url || url.origin !== new URL(base).origin) return '/';
  return url.pathname + url.search + url.hash;
}

const base = 'https://shop.example.com/login';
for (const t of ['/account?tab=orders', 'https://evil.com/', '//evil.com/x',
                 '/\\evil.com', 'javascript:alert(1)',
                 'https://shop.example.com.evil.com/']) {
  console.log(t.padEnd(36), '->', safeRedirect(t, base));
}
/account?tab=orders                  -> /account?tab=orders
https://evil.com/                    -> /
//evil.com/x                         -> /
/\evil.com                           -> /
javascript:alert(1)                  -> /
https://shop.example.com.evil.com/   -> /

The parser treats \ like / in special URLs, so /\evil.com is protocol-relative too. Browsers do the same, which is exactly why naive string checks fail.

File URLs and paths

ES modules identify files by file: URLs, and many APIs (fs, import(), new Worker()) accept them. Don't convert between file URLs and paths by hand: drive letters, percent-encoding and characters like # make it error-prone. Use fileURLToPath() and pathToFileURL() from node:url:

import { fileURLToPath, pathToFileURL } from 'node:url';

console.log(fileURLToPath('file:///home/me/My%20Docs/a.txt', { windows: false }));
console.log(fileURLToPath('file:///C:/Users/me/My%20Docs/a.txt', { windows: true }));

console.log(pathToFileURL('/home/me/notes #1.md', { windows: false }).href);
console.log(pathToFileURL('C:\\Users\\me\\notes #1.md', { windows: true }).href);
/home/me/My Docs/a.txt
C:\Users\me\My Docs\a.txt
file:///home/me/notes%20%231.md
file:///C:/Users/me/notes%20%231.md

The windows option forces Windows or POSIX rules; without it the current platform is used. Note how # is encoded as %23. With new URL('file://' + path) it would start the fragment and silently truncate the path.

To locate a file next to the current module, resolve a relative URL against import.meta.url:

import { readFile } from 'node:fs/promises';

const configUrl = new URL('./config.json', import.meta.url);
const config = JSON.parse(await readFile(configUrl, 'utf8'));

import.meta.dirname and import.meta.filename (Node.js 20.11+) give you the same information as plain paths, replacing __dirname and __filename from CommonJS.

Other helpers in node:url

url.format(URL, options) serializes a URL with parts left out or with Unicode host names:

import { format } from 'node:url';

const u = new URL('https://user:pw@example.com:8443/a?b=1#frag');
console.log(format(u, { auth: false, search: false, fragment: false }));
console.log(format(new URL('https://münchen.de/'), { unicode: true }));
https://example.com:8443/a
https://münchen.de/

domainToASCII() and domainToUnicode() convert host names to and from Punycode. An invalid domain returns an empty string:

import { domainToASCII, domainToUnicode } from 'node:url';

console.log(domainToASCII('münchen.de'));
console.log(domainToUnicode('xn--mnchen-3ya.de'));
console.log(JSON.stringify(domainToASCII('xn--iñvalid.com')));
xn--mnchen-3ya.de
münchen.de
""

urlToHttpOptions() converts a URL into the options object expected by http.request() and https.request():

import { urlToHttpOptions } from 'node:url';

console.log(urlToHttpOptions(new URL('https://user:pw@example.com:8443/a?b=1')));
[Object: null prototype] {
  protocol: 'https:',
  hostname: 'example.com',
  hash: '',
  search: '?b=1',
  pathname: '/a',
  path: '/a?b=1',
  href: 'https://user:pw@example.com:8443/a?b=1',
  port: 8443,
  auth: 'user:pw'
}

Legacy url.parse() and querystring

Older code and tutorials use url.parse() and the querystring module:

import url from 'node:url';
import querystring from 'node:querystring';

const legacy = url.parse('https://example.com:8080/p/a/t/h?query=string#hash', true);
console.log(legacy.pathname, legacy.port, legacy.query);

console.log(querystring.parse('a=1&a=2&b=x%20y'));
/p/a/t/h 8080 [Object: null prototype] { query: 'string' }
[Object: null prototype] { a: [ '1', '2' ], b: 'x y' }
(node:28300) [DEP0169] DeprecationWarning: `url.parse()` behavior is not standardized and prone to errors that have security implications. Use the WHATWG URL API instead. CVEs are not issued for `url.parse()` vulnerabilities.

url.parse() is deprecated (DEP0169) and prints a warning in Node.js 24. It doesn't follow the URL standard, so it can disagree with browsers and with new URL() about which host a URL points to, which has led to security bugs. It also accepts relative URLs like /path?x=1 without a base, which is why it was popular for parsing req.url.

Migration is straightforward:

Legacy Modern
url.parse(str) new URL(str) or URL.parse(str)
url.parse(req.url, true).query new URL(req.url, 'http://localhost').searchParams
url.resolve(from, to) new URL(to, from).href
url.format(obj) build a URL and use href
querystring.parse(str) new URLSearchParams(str)
querystring.stringify(obj) new URLSearchParams(obj).toString()

querystring itself is only marked legacy, not deprecated. It's slightly faster than URLSearchParams and turns repeated keys into arrays, but it's not standard and isn't available in browsers.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents