WHATWG URL Standard Implementation
whatwg-url provides a comprehensive and standards-compliant implementation of the WHATWG URL Standard's URL API and its underlying parsing mechanisms. It includes the `URL` and `URLSearchParams` classes, which mirror browser behavior, as well as a suite of lower-level parsing, serialization, and utility functions that are critical for projects needing fine-grained control or deep integration, such as jsdom. The current stable version is 16.0.1, with releases typically aligning with updates to the WHATWG URL specification and Node.js LTS cycles. This library differentiates itself by its strict adherence to the official specification, offering both high-level user-friendly APIs and internal algorithms for advanced use cases, ensuring consistency across different environments.
Common errors
-
ERR_REQUIRE_ESM
cause Attempting to use `require()` to import an ESM-only package or a package that primarily targets ESM in a CommonJS context without proper configuration.fixEnsure your project is configured for ESM (e.g., `"type": "module"` in `package.json`, `.mjs` extension) and use `import { Name } from 'whatwg-url';`. If you must use CommonJS, consider using a dynamic `import()` or transpilation. -
TypeError: URL.parse is not a function
cause `URL.parse()` was added in v14.1.0. This error indicates you are likely using an older version of `whatwg-url`.fixUpgrade `whatwg-url` to version 14.1.0 or later. Alternatively, use the `new URL(input)` constructor, which is available in all versions. -
Error: The "input" argument must be of type string. Received type object
cause The `URL` constructor or parsing functions expect a string as the first argument, but an object or `null`/`undefined` was provided.fixEnsure the input to `new URL()` or `parseURL()` is always a valid string representation of a URL. Validate your input before passing it to the library.
Warnings
- breaking Node.js minimum version requirement has incrementally increased. Version 16.0.0 requires `^20.19.0 || ^22.12.0 || >=24.0.0`. Older versions required Node.js v20 (v15.0.0), v18 (v14.0.0), v16 (v13.0.0). Ensure your Node.js environment meets these requirements.
- gotcha The `URL.parse()` static method (added in v14.1.0) in versions prior to 16.0.1 returned an internal implementation object, not a proper `URL` instance. This meant `URL.parse(x) instanceof URL` would return `false`.
- gotcha For `file:` URLs, `whatwg-url` strictly follows the WHATWG spec, which leaves the origin concept unspecified for `file:` URLs. As such, `myFileUrl.origin` will serialize to `"null"` (an opaque origin).
- breaking The low-level parsing functions `parseURL()` and `basicURLParse()` gained an `encoding` option in v16.0.0. While this is an enhancement, it changes the signature of these functions if you were previously relying on fixed default behavior (though `URL` API always uses UTF-8).
Install
-
npm install whatwg-url -
yarn add whatwg-url -
pnpm add whatwg-url
Imports
- URL
const { URL } = require('whatwg-url');import { URL } from 'whatwg-url'; - URLSearchParams
import URLSearchParams from 'whatwg-url';
import { URLSearchParams } from 'whatwg-url'; - parseURL
const parseURL = require('whatwg-url').parseURL;import { parseURL } from 'whatwg-url';
Quickstart
import { URL, URLSearchParams, parseURL, basicURLParse, serializeURL } from 'whatwg-url';
// Using the high-level URL and URLSearchParams classes
const urlString = 'https://user:pass@example.com:8080/path/to/resource?query=value&foo=bar#fragment';
const myUrl = new URL(urlString);
console.log(`Href: ${myUrl.href}`);
console.log(`Origin: ${myUrl.origin}`);
console.log(`Hostname: ${myUrl.hostname}`);
console.log(`Pathname: ${myUrl.pathname}`);
console.log(`Search: ${myUrl.search}`);
const params = myUrl.searchParams;
console.log(`Query parameter 'query': ${params.get('query')}`);
params.append('newParam', 'newValue');
console.log(`Updated search: ${myUrl.search}`);
// Using low-level parsers and serializers
const urlRecord = parseURL('http://example.com/test?a=1', { baseURL: 'http://base.com/' });
if (urlRecord) {
console.log('\nLow-level parseURL result (scheme):', urlRecord.scheme);
console.log('Low-level parseURL result (host):', serializeURL(urlRecord, true));
}
const anotherUrlRecord = basicURLParse('/path', { baseURL: 'http://foo.com/', url: null, stateOverride: 'path or authority' });
if (anotherUrlRecord) {
console.log('\nLow-level basicURLParse result:', serializeURL(anotherUrlRecord, false));
}
const fileUrl = new URL('file:///path/to/file.txt');
console.log(`\nFile URL origin: ${fileUrl.origin}`); // Expects 'null' per WHATWG spec