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.
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.
const myUrl = new URL("https://example.com/products?id=10");
const url = require("url");
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.
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
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 #. |
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.
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
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.
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
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.
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);
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.
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
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.
const fullUrl = new URL("/profile/settings", "https://example.com/account/");
console.log(fullUrl.href);
// https://example.com/profile/settings
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.
const keyword = "node js & express";
const safeKeyword = encodeURIComponent(keyword);
console.log(safeKeyword);
// node%20js%20%26%20express
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.
// 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);
// Preferred modern style
const parsed = new URL("https://example.com/products?id=1");
console.log(parsed.pathname);
console.log(parsed.searchParams.get("id"));
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.
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.
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.
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.
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.
Explore 500+ free tutorials across 20+ languages and frameworks.