url module
Last Updated : Oct 2026
url module is used to parse and manipulate URLs in Node.js. It provides a set of functions for working with URLs, such as parsing URLs, encoding and decoding URLs, and more.
Before staring url module, we need to first understand the url pattern,Let url is.
https://www.example.com/path/to/resource?param1=value1¶m2=value2
- https is the protocol.
- www.example.com is the hostname.
- /path/to/resource is the path.
- ?param1=value1¶m2=value2 is the query string.
- param1=value1 is a query parameter.
- value1 is the value of the query parameter.
Importing the url module using CommonJS:
const url = require("node:url");
Importing the url module using ESM:
import url from "node:url";
Some Common properties of the url module are:
- url.parse: The method to parse a URL string into a URL object.
const parsedUrl = url.parse("https://example.com");
console.log(parsedUrl);
- url.URL: The class to represent a URL object.
const parsedUrl = new url.URL("https://example.com");
console.log(parsedUrl);
- searchParams: The property to access the query parameters of a URL object.
const parsedUrl = new url.URL(
"https://example.com?param1=value1¶m2=value2",
);
const searchParams = parsedUrl.searchParams;
console.log(searchParams);
console.log(searchParams.get("param1"));
console.log(searchParams.get("param2"));
// Appending a query parameter
searchParams.append("param3", "value3");
console.log(parsedUrl.href);
- url.format: The method to format a URL object into a string.
const formattedUrl = url.format(parsedUrl);
console.log(formattedUrl);
