Tutorials Logic, IN info@tutorialslogic.com

Node.js URL API: Parse, Build, and Validate URLs

URL Modules in Node.js

Working with URLs is a common task in Node.js. Servers receive request URLs, APIs often build dynamic links, applications read query parameters for search and filtering, and many services need to combine base URLs with paths safely. Node.js provides tools for parsing, inspecting, and constructing URLs so that developers do not have to manipulate them with fragile string operations.

Use the WHATWG `URL` API for current Node.js URL parsing and construction. It matches the standard class used by modern JavaScript environments and makes base URLs, components, encoding, and search parameters explicit. Use legacy parsing only when maintaining an existing contract that requires it.

Importing URL Features

In many cases, you can use the global URL class directly without importing anything. However, some developers still use the built-in url module when they need specific helpers or when working with older code.

For most new code, prefer the URL class. It is easier to work with and matches how URLs are handled in modern JavaScript generally.

URL Usage Options

URL Usage Options
const myUrl = new URL("https://example.com/products?id=10");

Importing URL Features - JavaScript Example

Importing URL Features - JavaScript Example
const url = require("url");

Parsing a URL with the URL Class

The easiest way to understand the URL API is to create a URL object and inspect its properties. Once parsed, a URL becomes an object whose parts can be accessed cleanly without manual string splitting.

This is much safer than slicing strings manually. If your application receives URLs from requests, APIs, configuration files, or database records, the URL class gives a clear and predictable way to inspect them.

Parse URL Example

Parse URL Example
const myUrl = new URL("https://www.example.com:8080/products/list?page=2&sort=asc#top");

console.log(myUrl.href);      // full URL
console.log(myUrl.protocol);  // https:
console.log(myUrl.host);      // www.example.com:8080
console.log(myUrl.hostname);  // www.example.com
console.log(myUrl.port);      // 8080
console.log(myUrl.pathname);  // /products/list
console.log(myUrl.search);    // ?page=2&sort=asc
console.log(myUrl.hash);      // #top

Important URL Properties

The property searchParams is especially useful in real applications, because it gives a structured way to read and update query string values without having to parse them yourself.

Property Description
href The complete URL string.
protocol The protocol part, such as http: or https:.
host The hostname and port together.
hostname The domain or host name without the port.
port The port number as a string.
pathname The path part after the host.
search The query string beginning with ?.
searchParams An object-like interface for working with query parameters.
hash The fragment part beginning with #.

Reading Query Parameters with searchParams

Query parameters are commonly used for searching, filtering, sorting, pagination, and tracking. For example, a request like /products?page=2&category=books contains two query parameters: page and category. The searchParams API makes them easy to read.

If a parameter is missing, get() returns null. This is useful when validating optional query fields in a server route.

Read Search Params

Read Search Params
const myUrl = new URL("https://example.com/products?page=2&category=books&sort=price");

console.log(myUrl.searchParams.get("page"));      // 2
console.log(myUrl.searchParams.get("category"));  // books
console.log(myUrl.searchParams.get("sort"));      // price

Modifying Query Parameters

The searchParams object is not read-only. You can add, update, or remove query parameters and then read the updated URL. This is useful when building links dynamically for pagination, filtering, redirects, or external API requests.

This approach is safer than manually concatenating strings because it reduces the risk of malformed query strings and handles encoding more reliably.

Update Search Params

Update Search Params
const myUrl = new URL("https://example.com/products?page=1");

myUrl.searchParams.set("page", "3");
myUrl.searchParams.set("sort", "newest");
myUrl.searchParams.delete("unused");

console.log(myUrl.href);
// https://example.com/products?page=3&sort=newest

Using URL Objects in an HTTP Server

One of the most practical uses of the URL API is inside an HTTP server. When a Node.js server receives a request, req.url contains the path and query string, not the full absolute URL. To parse it with the modern URL class, you usually provide a base URL.

If the browser opens http://localhost:8080/products?page=4, the server can parse pathname as <code>/products</code> and query as <code>page=4</code>. That split is what lets one handler serve the same route for many filter or pagination values.

Parse Request URL in Server

Parse Request URL in Server
const http = require("http");

http.createServer((req, res) => {
    const requestUrl = new URL(req.url, "http://localhost:8080");
    const page = requestUrl.searchParams.get("page") || "1";

    res.writeHead(200, { "Content-Type": "text/plain" });
    res.end(`Requested path: ${requestUrl.pathname}, page: ${page}`);
}).listen(8080);

Building URLs Safely

Node.js applications often need to construct URLs dynamically, such as links to images, redirect destinations, API endpoints, or pages with filters. Instead of building long URL strings manually, you can start with a base URL and modify it step by step.

This pattern is safer because the URL API handles separators like ? and & automatically. It also reduces bugs caused by missing slashes or invalid concatenation.

Build a URL

Build a URL
const apiUrl = new URL("/search", "https://api.example.com");

apiUrl.searchParams.set("q", "node js");
apiUrl.searchParams.set("limit", "10");

console.log(apiUrl.toString());
// https://api.example.com/search?q=node+js&limit=10

Relative URLs and Base URLs

A relative URL does not contain a full protocol and host. For example, /users/1 is a relative path. The URL class can resolve it against a base URL. This is the modern replacement for older resolution helpers like url.resolve().

This is especially useful when generating links from a known site base or when converting request paths into absolute URLs for redirection or external references.

Resolve Relative URL

Resolve Relative URL
const fullUrl = new URL("/profile/settings", "https://example.com/account/");

console.log(fullUrl.href);
// https://example.com/profile/settings

Encoding URL Values

User input should never be inserted into URLs blindly. Special characters such as spaces, &, ?, and # can break the URL structure or create incorrect parameter values. The safest approach is to let the URL API or encoding helpers handle this conversion for you.

If you use searchParams.set(), the URL class usually handles the encoding for you automatically. Still, it is good to understand why encoding matters, especially when building URLs from form input or search values.

encodeURIComponent Example

encodeURIComponent Example
const keyword = "node js & express";
const safeKeyword = encodeURIComponent(keyword);

console.log(safeKeyword);
// node%20js%20%26%20express

Legacy url.parse() vs Modern URL

Older Node.js tutorials often use url.parse() from the legacy url module. While you may still encounter it in old codebases, modern Node.js development generally prefers new URL(). The modern API is closer to web standards, easier to reason about, and better aligned with browser JavaScript.

When maintaining older applications, you may still need to read legacy code, so it is helpful to recognize both styles. For new code, prefer the modern version unless the project has a strong compatibility reason not to.

Legacy and Modern Comparison

Legacy and Modern Comparison
// Older style
const url = require("url");
const parsed = url.parse("https://example.com/products?id=1", true);

console.log(parsed.pathname);
console.log(parsed.query.id);

Legacy url.parse() vs Modern URL - JavaScript Example

Legacy url.parse() vs Modern URL - JavaScript Example
// Preferred modern style
const parsed = new URL("https://example.com/products?id=1");

console.log(parsed.pathname);
console.log(parsed.searchParams.get("id"));

Common Beginner Mistakes

One common mistake is trying to parse a relative request path like /users?page=1 with new URL(req.url) directly. That fails because the URL constructor expects a full absolute URL unless a base is provided. Another mistake is manually splitting query strings with string methods instead of using searchParams. Developers also sometimes forget that query parameters are strings by default, so values like page numbers may need conversion before numerical use.

A third mistake is building URLs with plain concatenation. This often breaks when optional parameters, missing slashes, or special characters are involved. Letting the URL API manage structure and encoding is usually much safer.

Structured URL Parts

Think of the URL API as a structured parser and builder for web addresses. Instead of treating a URL as one fragile string, you treat it as an object with meaningful parts: protocol, host, path, query string, and fragment. That makes code easier to read and much more reliable, especially in servers and APIs where URLs are processed constantly.

WHATWG URL Contract

Use the WHATWG `URL` class for new code. An absolute URL parses directly; a relative reference requires a trusted base. Read protocol, hostname, port, pathname, searchParams, hash, username, and password through properties rather than substring operations. Setting properties applies URL parsing and percent-encoding rules.

Hostnames are normalized, credentials may be present, and default ports affect origin comparisons. For security decisions, compare the parsed protocol, exact hostname, and effective port against an allowlist. A string that merely starts with an approved domain can point somewhere else.

Use `URL.canParse` or a guarded constructor for validation, then apply product rules. Syntactic validity does not make a redirect or outbound request safe. Reject unexpected schemes, embedded credentials, local or private destinations where SSRF matters, and overlong inputs.

  • Parse components before comparing or modifying URLs.
  • Require a trusted base for relative references.
  • Allowlist scheme, host, and effective port.
  • Separate syntax checks from redirect and SSRF policy.

File URL Conversion

Use `fileURLToPath()` and `pathToFileURL()` when crossing between module URLs and operating-system paths. A file URL has percent encoding and platform-specific host and drive semantics; reading `.pathname` directly can produce incorrect paths for spaces, Unicode, network shares, or Windows drive letters.

In ECMAScript modules, derive a file location from `import.meta.url` through the URL APIs rather than assuming CommonJS globals. Resolve application assets relative to the module only when deployment preserves that relationship; writable runtime data should use an explicit configured directory.

Test URL behavior with encoded separators, Unicode, IPv6, default ports, repeated query values, and both supported path platforms. Do not decode repeatedly, because double decoding can change a harmless string into traversal or delimiter syntax.

  • Convert file URLs with dedicated Node APIs.
  • Use import.meta.url for ESM module location.
  • Keep writable data paths in explicit configuration.
  • Decode once and test platform-specific cases.
Before you move on

Node.js URL Module Parse Format URLs Mastery Check

5 checks
  • Working with URLs is a common task in Node.js.
  • Servers receive request URLs, APIs often build dynamic links, applications read query parameters for search and filtering, and many services need to combine base URLs with paths safely.
  • Node.js provides tools for parsing, inspecting, and constructing URLs so that developers do not have to manipulate them with fragile string operations.
  • Prefer the WHATWG URL API; keep legacy parsing only for a verified compatibility requirement.
  • Modern Node.js development usually prefers the WHATWG URL API, which is based on the standard URL class used in modern JavaScript environments.

Node JS Questions Learners Ask

URLs contain encoding, query strings, hashes, ports, protocols, and edge cases that simple string splitting handles poorly. The URL class parses those parts consistently and exposes properties such as pathname, searchParams, host, and protocol.

req.url is usually a relative path such as /products?page=2, but the URL constructor needs an absolute URL unless you provide a base. Use new URL(req.url, "http://localhost") or build the base from request headers when appropriate.

URLSearchParams.get() returns the first value for a key. If the URL contains repeated keys such as ?tag=node&tag=api, use getAll("tag") to read every value.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.