The node:url module provides utilities for URL resolution, parsing, serialization, and search query string manipulation adhering to the modern standard WHATWG URL API specification.
flowchart LR
A["https://user:[email protected]:8080/v1/users?role=admin#details"]
A --> B["protocol: 'https:'"]
A --> C["hostname: 'api.example.com'"]
A --> D["port: '8080'"]
A --> E["pathname: '/v1/users'"]
A --> F["searchParams: { role: 'admin' }"]
A --> G["hash: '#details'"]
import { URL, URLSearchParams } from 'node:url';
// 1. Parsing full URL string
const requestUrl = 'https://store.example.com:8443/products/search?category=laptops&sort=price_asc#results';
const parsedUrl = new URL(requestUrl);
console.log(`Protocol: ${parsedUrl.protocol}`); // 'https:'
console.log(`Host: ${parsedUrl.host}`); // 'store.example.com:8443'
console.log(`Pathname: ${parsedUrl.pathname}`); // '/products/search'
console.log(`Port: ${parsedUrl.port}`); // '8443'
// 2. Manipulating Search Parameters (Query String)
const params = parsedUrl.searchParams;
console.log(`Category Filter: ${params.get('category')}`); // 'laptops'
// Add dynamic query parameters
params.append('inStock', 'true');
params.set('page', '2'); // update or insert
console.log(`Updated Query String: ${parsedUrl.search}`);
// '?category=laptops&sort=price_asc&inStock=true&page=2'
// 3. Constructing URLs programmatically
const baseApiUrl = new URL('/api/v2/metrics', 'https://dash.analytics.io');
baseApiUrl.searchParams.set('range', '7d');
console.log(`Constructed Target URL: ${baseApiUrl.href}`);
// 'https://dash.analytics.io/api/v2/metrics?range=7d'
URL global: The legacy url.parse() method is deprecated in modern Node.js environments; use the WHATWG new URL() constructor instead.url.searchParams.get() before passing them into SQL or file queries.http://localhost) when parsing relative incoming request paths (like req.url).Parse the string 'https://api.github.com/repos/nodejs/node?per_page=100' and extract the repository name path and the per_page param value.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With