Resolve API endpoints
Create absolute endpoints from service roots and relative resource paths.
Node.js · Class
The WHATWG URL class parses absolute URLs and resolves relative references against a base URL. It exposes structured URL components and serializes them back into standard URL strings.
The WHATWG URL class parses an absolute URL or resolves a relative URL against a base URL into structured components. Its properties expose parts such as the protocol, hostname, pathname, and query parameters, while serialization methods produce the resulting URL string.
new URL(input[, base])| Name | Type | Description |
|---|---|---|
input | string | The URL string or relative reference to parse. |
base | string | URL | The absolute base URL used when input is relative. |
A URL object containing properties for the URL's components.
import { URL } from 'node:url';
const endpoint = new URL('/users', 'https://api.example.com/v1/');
endpoint.searchParams.set('active', 'true');
console.log(endpoint.href);
console.log(endpoint.hostname);Constructs an absolute URL from a relative path and base, adds a query parameter, and reads parsed components.
Create absolute endpoints from service roots and relative resource paths.
Read or modify host, path, protocol, and query components without manual string parsing.
Build browser-compatible URLs for HTTP requests, redirects, and routing.
The WHATWG URL class is a browser-compatible URL implementation available through Node.js. It turns a URL string into an object whose properties represent its meaningful components.
Follow-up: How do you resolve a relative URL? Construct URL with the relative reference as the first argument and an absolute base URL as the second.
Use new URL(input, base) when the input may be relative; the base supplies the missing context. For an already absolute URL, new URL(input) is sufficient.
Follow-up: What happens if a relative input is supplied without a base? Construction cannot resolve it as an absolute URL and throws an error.
The URL object provides structured components, and toString() serializes the object back into a URL string. The class follows the WHATWG URL Standard, aligning its behavior with web browsers.
Follow-up: How should legacy URL parsing be treated? It remains available for compatibility, but the WHATWG API is the modern choice for new code.
URLSearchParamsurl.parse()url.format()url.resolve()