Chapter 27: Node.js URL Module

1. What is the url module and why do you need it?

The node:url module is a built-in core module that helps you parse, format, resolve, and manipulate URLs in a safe, standard-compliant way.

Why not just use string methods or regex?

URLs look simple, but they have many tricky rules:

  • Different protocols (http, https, file, data, ws, mailto…)
  • Authentication (http://user:pass@host.com)
  • Ports (:8080)
  • Path segments with /, ../, //, encoded characters
  • Query strings (?page=2&sort=desc)
  • Fragments (#section-2)
  • Internationalized domain names (IDN)
  • Edge cases that break naive string splitting

Doing this manually is very error-prone → you will eventually write bugs that only appear on certain URLs or browsers.

The url module solves all of this — it follows the WHATWG URL Standard (same standard browsers use).

Modern rule (2025–2026):

Always use node:url when you need to:

  • Parse an incoming URL
  • Build or modify a URL
  • Resolve relative URLs
  • Extract hostname, pathname, search params, etc.

2. Modern import style

JavaScript

3. The two most important classes

Class Purpose When you use it most often
URL Represents a complete URL (parse, format, resolve) Almost every time you work with URLs
URLSearchParams Handles the query string part (?key=value&…) Reading or building query parameters

4. The URL class – your main tool

4.1 Basic parsing

JavaScript

4.2 Very common real-world example – parsing incoming request URL

JavaScript

Try:

text

Response:

JSON

Important note: When parsing req.url in http server, you must provide a base (because req.url is relative).

JavaScript

4.3 Working with URLSearchParams (query string handling)

JavaScript

Very common pattern – clean query builder

JavaScript

5. Resolving relative URLs (very powerful)

JavaScript

Very common pattern – building API endpoints

JavaScript

6. Common mistakes & how to avoid them

Mistake Consequence Correct way
new URL(req.url) without base TypeError: Invalid URL Always new URL(req.url, base)
Logging url.password in production Passwords leak in logs Never log url.password or url.username
Using + to build URLs Wrong escaping, broken paths Always use new URL() + searchParams
Forgetting to call .toString() or .href Get URL object instead of string Use url.toString() when you need the full URL
Assuming search is parsed url.search is just string Use url.searchParams for easy get/set/delete

Summary – Quick decision guide 2025–2026

You want to… Use this Typical real-world use case
Parse incoming request URL new URL(req.url, base) Almost every HTTP/Express/Fastify route
Read or modify query parameters url.searchParams Pagination, filters, sorting
Build a new URL safely new URL(path, base) API links, redirect URLs, external service calls
Resolve relative paths / URLs new URL(relative, base) HTML <base>, link rewriting, sitemap generation
Get full normalized URL string url.toString() or url.href Logging, redirects, database storage

Would you like to go much deeper into any specific area?

  • URLSearchParams tricks (sorting, bulk operations, encoding)
  • Building robust API URL helpers with validation
  • Handling redirects and relative URLs correctly
  • Parsing complex URLs (auth, IPv6, data: URLs, file: URLs)
  • Complete example – API client with URL building & query params

Just tell me which direction feels most useful right now — I’ll continue with detailed, production-ready examples. 😊

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *