Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

Node.js URL Module Parse Format URLs: Tutorial, Examples, FAQs & Interview Tips

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.

Historically, Node.js exposed a legacy url module with functions like url.parse(). Modern Node.js development usually prefers the WHATWG URL API, which is based on the standard URL class used in modern JavaScript environments. This API is clearer, more consistent, and better suited for current applications. When learning URL handling today, it is best to understand the modern URL class first.

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.

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

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

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.

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

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.

Important URL Properties

PropertyDescription
hrefThe complete URL string.
protocolThe protocol part, such as http: or https:.
hostThe hostname and port together.
hostnameThe domain or host name without the port.
portThe port number as a string.
pathnameThe path part after the host.
searchThe query string beginning with ?.
searchParamsAn object-like interface for working with query parameters.
hashThe fragment part beginning with #.

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.

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.

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

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

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.

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

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

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.

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);

If the browser opens http://localhost:8080/products?page=4, the server can read /products from pathname and 4 from the query string. This is a very common pattern in Node.js APIs.

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.

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

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

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().

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

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

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.

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.

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

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

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.

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.

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);
// Preferred modern style
const parsed = new URL("https://example.com/products?id=1");

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

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.

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.

A Practical Mental Model

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.

Key Takeaways
  • The modern URL class is the preferred way to parse and construct URLs in Node.js.
  • href, protocol, host, hostname, pathname, search, and hash expose structured URL parts.
  • searchParams provides a clean API for reading, setting, and deleting query parameters.
  • When parsing request URLs in an HTTP server, pass a base URL to new URL(req.url, base).
  • Use the URL API or encodeURIComponent() to handle special characters safely.
  • The legacy url.parse() style still appears in older code, but the modern URL class is preferred for new applications.

Ready to Level Up Your Skills?

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