URL and URLSearchParamsThe Node.js URL API parses web addresses into structured properties—protocol, hostname, port, pathname, and query parameters—using the standard WHATWG URL class. Because URL and URLSearchParams are global in Node.js (and match browser JavaScript), you rarely need the legacy url.parse() function anymore.
When building an HTTP server, req.url arrives as a relative path like /products?category=books&page=2. Pass a base URL as the second argument to new URL(req.url, 'http://localhost') to extract clean pathnames and typed query parameters safely.
const incoming = new URL('/lessons?topic=nodejs&page=2&tag=fs&tag=http', 'https://kodersolution.com');
console.log('Pathname:', incoming.pathname);
console.log('Topic:', incoming.searchParams.get('topic'));
console.log('All tags:', incoming.searchParams.getAll('tag'));
console.log('Has sort?', incoming.searchParams.has('sort'));
// Update query strings without manual string concatenation
incoming.searchParams.set('page', '3');
incoming.searchParams.delete('topic');
console.log('Updated URL:', incoming.toString());
URLSearchParams handles URL encoding (%20, &, =) automatically, preventing broken query strings when values contain spaces or special characters.
url UtilitiesUse new URL('./avatar.png', 'https://cdn.example.com/users/') to resolve relative URLs reliably. When working with ES module paths, import { fileURLToPath, pathToFileURL } from 'node:url' converts directly between file:// URLs (import.meta.url) and local filesystem paths.
url.parse(): Legacy url.parse() has security quirks with malformed hostnames and is deprecated in Node.js docs. Always prefer new URL().new URL('/only-path') without a base URL: Relative paths throw a TypeError: Invalid URL unless you pass a base origin as the second parameter.req.url manually with .split('?'): Manual string splitting skips percent-decoding (%2F, +) and breaks on repeated query keys like ?tag=a&tag=b.new URL() receives a malformed URL string?It throws a TypeError. Always wrap new URL(userInput) inside a try / catch block when validating untrusted URLs from users.
URLSearchParams?Use for (const [key, value] of url.searchParams.entries()) or Object.fromEntries(url.searchParams) for single-value parameters.
URL validate safe HTTP protocols?Yes. Check parsed.protocol === 'https:' || parsed.protocol === 'http:' after constructing new URL() to reject javascript: or data: links.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.