Lesson

Node.js URL Module

10 min reading
Free Course

Node.js URL Module: Modern Parsing with URL and URLSearchParams

The 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.

Parsing Incoming Request URLs and Query Parameters

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.

Resolving Relative Paths and Checking url Utilities

Use 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.

Common Mistakes to Avoid

  • Using deprecated url.parse(): Legacy url.parse() has security quirks with malformed hostnames and is deprecated in Node.js docs. Always prefer new URL().
  • Calling 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.
  • Splitting req.url manually with .split('?'): Manual string splitting skips percent-decoding (%2F, +) and breaks on repeated query keys like ?tag=a&tag=b.

Frequently Asked Questions

What happens if 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.

How do I iterate over all query parameters in URLSearchParams?

Use for (const [key, value] of url.searchParams.entries()) or Object.fromEntries(url.searchParams) for single-value parameters.

Can URL validate safe HTTP protocols?

Yes. Check parsed.protocol === 'https:' || parsed.protocol === 'http:' after constructing new URL() to reject javascript: or data: links.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
Node.js Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum