Building request URLs
Construct an endpoint from a service origin and a relative route, then add query parameters safely.
Node.js · Module
The node:url module supplies URL parsing, resolution, construction, and query-string utilities. Prefer its WHATWG-compatible URL and URLSearchParams APIs for new code; the module also retains a deprecated legacy API.
The module offers Node.js URL utilities through both the browser-compatible WHATWG API and an older Node-specific API. Prefer the URL and URLSearchParams classes for constructing, resolving, inspecting, and modifying URLs; the legacy functions parse and format older URL objects.
import { URL, URLSearchParams } from 'node:url';
new URL(input[, base])
new URLSearchParams(init)import { URL, URLSearchParams } from 'node:url';
const endpoint = new URL('/search', 'https://api.example.com');
endpoint.searchParams.set('q', 'node:url');
endpoint.searchParams.set('page', '2');
console.log(endpoint.href);
console.log(endpoint.searchParams.get('q'));Creates a standards-based URL from a relative path, adds encoded query parameters, and reads one parameter.
Construct an endpoint from a service origin and a relative route, then add query parameters safely.
Read protocol, host, pathname, and query values from incoming or configured URL strings.
Normalize or resolve relative links against a known absolute base URL.
Manipulate query parameters while preserving correct URL encoding.
The module provides two URL APIs: a Node-specific legacy API and a newer API implementing the WHATWG URL Standard. The WHATWG API is generally the appropriate choice for new code.
Follow-up: How would you resolve a relative URL? Construct new URL(relative, base), supplying an absolute base URL.
new URL(input, base) constructs a URL object and can resolve a relative input against a base. Its properties expose URL components, while href provides the serialized URL.
Follow-up: How can query data be changed? Use the URL object's searchParams, such as set, append, get, or delete, then read the updated serialization.
url.parse() and what is its status?The legacy url.parse() function accepts a URL string and returns a legacy URL object. That API is Node-specific and deprecated, so it should normally be replaced with the WHATWG URL API.
Follow-up: When might legacy behavior matter? Existing code may depend on the legacy object shape or parsing semantics, so migration should include tests for serialized URLs and edge cases.
URLURLSearchParamsurl.parse()url.format()url.resolve()urlToHttpOptions()