Skip to main content
A complete WHATWG-style URL implementation:

new URL(input, base?)

With a base, relative inputs resolve against it:

Properties

Setting a component updates the whole URL:

Methods

Statics

Prefer URL.parse when input is untrusted:

URLSearchParams

Reached through url.searchParams or constructed directly:

Methods

The view is one-way

Edits to the URL re-parse the params — but edits to the params never touch the URL:

Patterns

Build a query safely

Nothing here percent-encodes: set() stores values verbatim, toString() emits them verbatim, and the URL parser percent-decodes %XX on the way in (so a decoded & or = silently splits fields — %26 becomes a field separator, %23 truncates at #). encodeURIComponent exists — use it, and keep encoded text out of new URL / .search:
Two things that look right but aren’t: fetch(urlObject) throws Invalid URL — always pass a string (fetch(u.href)) — and u.searchParams.set(...) followed by fetch(u.href) sends the old query, because param edits never reach the URL.

Parse a request URL

Gotchas

  • searchParams.size and Headers.size are functions — call them (sp.size()), they are not numeric properties.
  • Query values are never percent-encoded on output — but the URL parser decodes %XX on input. Encode with encodeURIComponent and keep encoded strings out of new URL / .search.
  • fetch() takes a URL string, not a URL object (fetch(u) throws Invalid URL — use fetch(u.href)).
  • for...of doesn’t work on URLSearchParams (or Headers) — loop over .entries() instead.
  • URL.parse returns null; the constructor throws. Pick per context.
  • Input longer than the internal buffer falls back to heap allocation — there is no documented length cap, but absurd URLs are waste.
  • origin is read-only; use href = … to change the host.
  • No URL.canParse in very old environments — it exists here.

See also