WHATWG URL Standard Implementation

16.0.1 · active · verified Tue Apr 21

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

Warnings

Install

Imports

Quickstart

Demonstrates the usage of `URL` and `URLSearchParams` for standard URL manipulation, and showcases the low-level `parseURL`, `basicURLParse`, and `serializeURL` functions for advanced parsing and serialization.

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

view raw JSON →