Every web application works with URLs.
Whenever you visit a website like:
https://example.com/products?id=101&category=laptop
your browser sends this URL to the server.
The server then needs to answer questions like:
- Which page was requested?
- What is the hostname?
- Which protocol is being used?
- What are the query parameters?
- What is the pathname?
Node.js provides a built-in URL module that makes working with URLs simple and efficient.
In this article, we'll learn how to use the URL module step by step with practical examples.
Let's get started!
What is the URL Module?
The URL module is a built-in Node.js module used to create, parse, inspect, and manipulate URLs.
Using the URL module, you can:
- Parse URLs
- Read query parameters
- Modify URLs
- Encode URLs
- Decode URLs
- Work with search parameters
- Build URLs dynamically
Since it's built into Node.js, you don't need to install any package.
Importing the URL Module
const url = require("url");
Or, using ES Modules:
import url from "node:url";
Note: Modern Node.js applications typically use the global
URLclass instead of the olderurl.parse()API. We'll focus on the modern approach first.
Understanding URL Structure
Consider this URL:
https://www.example.com:8080/products/mobile?id=101&brand=apple#reviews
Let's break it down.
https://www.example.com:8080/products/mobile?id=101&brand=apple#reviews
│ │ │ │ │ │
│ │ │ │ │ │
│ │ │ │ │ └── Hash
│ │ │ │ └── Query Parameters
│ │ │ └── Pathname
│ │ └── Port
│ └── Hostname
└── Protocol
Each part provides useful information to your application.
Creating a URL Object
The modern way to work with URLs is using the URL class.
const myURL = new URL(
"https://www.example.com/products?id=101"
);
console.log(myURL);
This creates a URL object that exposes many useful properties.
Understanding URL Properties
href
Returns the complete URL.
const myURL = new URL(
"https://www.example.com/products?id=101"
);
console.log(myURL.href);
Output:
https://www.example.com/products?id=101
protocol
Returns the protocol.
console.log(myURL.protocol);
Output:
https:
hostname
Returns only the domain name.
console.log(myURL.hostname);
Output:
www.example.com
host
Returns the hostname along with the port (if present).
const myURL = new URL(
"https://localhost:3000/products"
);
console.log(myURL.host);
Output:
localhost:3000
port
Returns the port number.
console.log(myURL.port);
Output:
3000
pathname
Returns the path.
const myURL = new URL(
"https://example.com/users/profile"
);
console.log(myURL.pathname);
Output:
/users/profile
search
Returns the query string.
const myURL = new URL(
"https://example.com/products?id=101&brand=apple"
);
console.log(myURL.search);
Output:
?id=101&brand=apple
hash
Returns the fragment (hash).
const myURL = new URL(
"https://example.com/products#reviews"
);
console.log(myURL.hash);
Output:
#reviews
Understanding URLSearchParams
Query parameters are extremely common in web applications.
Example:
https://example.com/products?id=101&category=laptop
Node.js provides the URLSearchParams API to work with them.
Read Query Parameters
const myURL = new URL(
"https://example.com/products?id=101&category=laptop"
);
console.log(myURL.searchParams.get("id"));
console.log(myURL.searchParams.get("category"));
Output:
101
laptop
Check if a Query Parameter Exists
console.log(
myURL.searchParams.has("category")
);
Output:
true
Add Query Parameters
const myURL = new URL(
"https://example.com/products"
);
myURL.searchParams.append("id", 101);
myURL.searchParams.append("category", "laptop");
console.log(myURL.href);
Output:
https://example.com/products?id=101&category=laptop
Update Query Parameters
myURL.searchParams.set("category", "mobile");
console.log(myURL.href);
Output:
https://example.com/products?id=101&category=mobile
Delete Query Parameters
myURL.searchParams.delete("id");
console.log(myURL.href);
Output:
https://example.com/products?category=mobile
Loop Through Query Parameters
const myURL = new URL(
"https://example.com?name=John&age=25"
);
for (const [key, value] of myURL.searchParams) {
console.log(key, value);
}
Output:
name John
age 25
Modifying URL Properties
The URL object is mutable.
const myURL = new URL(
"https://example.com"
);
myURL.pathname = "/users";
myURL.searchParams.append("id", 10);
console.log(myURL.href);
Output:
https://example.com/users?id=10
Building Dynamic URLs
Suppose you're creating profile links.
const baseURL = new URL(
"https://myapp.com"
);
baseURL.pathname = "/profile";
baseURL.searchParams.append("userId", 101);
console.log(baseURL.href);
Output:
https://myapp.com/profile?userId=101
Encoding URLs
Some URLs contain spaces or special characters.
const myURL = new URL(
"https://example.com/search"
);
myURL.searchParams.append("query", "Node JS Tutorial");
console.log(myURL.href);
Output:
https://example.com/search?query=Node+JS+Tutorial
Notice that the space is automatically encoded.
Decoding Query Parameters
const myURL = new URL(
"https://example.com/search?query=Node%20JS"
);
console.log(
myURL.searchParams.get("query")
);
Output:
Node JS
The encoded value is automatically decoded when you retrieve it.
Legacy url.parse() API
Before the URL class was introduced, developers used url.parse().
const url = require("url");
const parsedURL = url.parse(
"https://example.com/products?id=101",
true
);
console.log(parsedURL);
Output (simplified):
Url {
protocol: 'https:',
host: 'example.com',
pathname: '/products',
query: {
id: '101'
}
}
Note: While you'll still encounter
url.parse()in older projects, theURLclass is the recommended approach for modern Node.js development.
Build a URL Analyzer
Let's create a simple application that analyzes a URL.
const myURL = new URL(
"https://example.com:3000/products?id=100&brand=apple#details"
);
console.log("Full URL:", myURL.href);
console.log("Protocol:", myURL.protocol);
console.log("Host:", myURL.host);
console.log("Hostname:", myURL.hostname);
console.log("Port:", myURL.port);
console.log("Path:", myURL.pathname);
console.log("Query:", myURL.search);
console.log("Hash:", myURL.hash);
console.log("Product ID:", myURL.searchParams.get("id"));
console.log("Brand:", myURL.searchParams.get("brand"));
Output:
Full URL: https://example.com:3000/products?id=100&brand=apple#details
Protocol: https:
Host: example.com:3000
Hostname: example.com
Port: 3000
Path: /products
Query: ?id=100&brand=apple
Hash: #details
Product ID: 100
Brand: apple
Real-World Use Cases
The URL module is commonly used for:
- Reading query parameters
- Building API URLs
- Creating dynamic links
- OAuth authentication
- Payment gateway redirects
- URL validation
- Web scraping
- Proxy servers
Almost every backend application works with URLs.
Comparison of Common URL Properties
href - Complete URL
protocol - URL protocol
hostname - Domain name
host - Domain with port
port - Port number
pathname - URL path
search - Query string
searchParams - Query parameter manager
hash - Fragment identifier
Best Practices
When working with URLs:
- Prefer the modern
URLclass overurl.parse(). - Use
URLSearchParamsto read and modify query parameters. - Avoid manually concatenating query strings.
- Let the
URLclass handle encoding and decoding automatically. - Validate user-provided URLs before processing them.
Common Beginner Mistakes
Here are some common mistakes developers make:
- Building URLs using string concatenation.
- Parsing query parameters manually.
- Confusing
hostwithhostname. - Forgetting that
protocolincludes the trailing colon (https:). - Using the legacy
url.parse()API in new projects.
Final Thoughts
The URL module is an essential part of Node.js development. It provides a clean and reliable way to parse, inspect, and manipulate URLs without manually handling strings.
In this article, you learned:
- What the URL module is
- How to create URL objects
- How to access different parts of a URL
- How to work with query parameters using
URLSearchParams - How to build dynamic URLs
- How to encode and decode URLs
- The difference between the modern
URLAPI and the legacyurl.parse()API
As you continue building backend applications, you'll frequently work with URLs for APIs, authentication, routing, redirects, and third-party integrations. Mastering the URL module will make these tasks much easier and less error-prone.
Happy Coding! 🚀