Skip to content

The Node.js URL Module – How to Parse and Manage URLs

Node.js provides a built-in URL module to simplify URL management.

To use the url module, add it to your project as follows:

import url from "node:url";

For CommonJS, use:

const url = require("node:url");

Once you’ve added the url module, you can use several of its APIs to work with URLs. Here are a few common ones:

  • URL constructor: Use this to parse URLs.
  • fileURLToPath function: This converts URLs into file paths for your system.
  • pathToFileURL function: This turns file paths into absolute file URLs.

Now, let’s look at these three APIs in more detail.

The URL constructor is an API in the node:url module that lets you parse URLs.

You can use the URL constructor to parse both absolute and relative URLs. Here’s how it looks with an absolute URL:

import { URL } from "node:url";
const urlObject = new URL(
"protocol://username:[email protected]:port/p/a/t/h?query=string#hash",
);

For CommonJS, use:

const URL = require("node:url").URL;
const urlObject = new URL(
"protocol://username:[email protected]:port/p/a/t/h?query=string#hash",
);

If you use a relative URL, you need to provide a base URL as the second argument. Here’s the syntax:

import { URL } from "node:url";
const urlObject = new URL(
"/p/a/t/h",
"scheme://username:[email protected]/",
);

For CommonJS, use:

const URL = require("node:url").URL;
const urlObject = new URL(
"/p/a/t/h",
"scheme://username:[email protected]/",
);

When you parse a URL with the url module, it returns a new URL object with properties for each part of the URL. Here’s an example:

// Add the URL module:
import { URL } from "node:url";
// Define the web address components:
const origin = "https://www.codesweetly.com";
const pathname = "/blog/react-image-grid-gallery-v3-release";
const search = "?q=grid";
const hash = "#breaking-changes";
// Parse the web address:
const urlObject = new URL(`${origin}${pathname}${search}${hash}`);
// Log the urlObject to the console:
console.log(urlObject);
// The invocation above will return:
URL {
href: 'https://www.codesweetly.com/blog/react-image-grid-gallery-v3-release?q=grid#breaking-changes',
origin: 'https://www.codesweetly.com',
protocol: 'https:',
username: '',
password: '',
host: 'www.codesweetly.com',
hostname: 'www.codesweetly.com',
port: '',
pathname: '/blog/react-image-grid-gallery-v3-release',
search: '?q=grid',
searchParams: URLSearchParams { 'q' => 'grid' },
hash: '#breaking-changes'
}
// Log one of the urlObject's values to the console:
console.log(urlObject.protocol);
// The invocation above will return: "https:"

The example above uses the url module to parse the specified URL.

In the example, we used a template literal string as the argument for the URL constructor. You can also use the property setter method. Here’s how:

// Add the URL module:
import { URL } from "node:url";
// Parse the web address:
const urlObject = new URL("https://www.codesweetly.com");
// Update the urlObject's properties:
urlObject.pathname = "/blog/react-image-grid-gallery-v3-release";
urlObject.search = "?q=grid";
urlObject.hash = "#breaking-changes";
// Log the urlObject to the console:
console.log(urlObject);
// The invocation above will return:
URL {
href: 'https://www.codesweetly.com/blog/react-image-grid-gallery-v3-release?q=grid#breaking-changes',
origin: 'https://www.codesweetly.com',
protocol: 'https:',
username: '',
password: '',
host: 'www.codesweetly.com',
hostname: 'www.codesweetly.com',
port: '',
pathname: '/blog/react-image-grid-gallery-v3-release',
search: '?q=grid',
searchParams: URLSearchParams { 'q' => 'grid' },
hash: '#breaking-changes'
}
// Log one of the urlObject's values to the console:
console.log(urlObject.protocol);
// The invocation above will return: "https:"

The URL constructor provides utilities for accessing or modifying a URL’s query string. Let’s go over the most common ones.

The URLSearchParams APIs for reading and writing to a URL’s query string

Section titled “The URLSearchParams APIs for reading and writing to a URL’s query string”

Here is a selection of essential URLSearchParams APIs for working with a URL’s query string.

searchParams.append() – Add new query to the URL

Section titled “searchParams.append() – Add new query to the URL”

The searchParams.append() method adds a new name-value pair to the end of a URL’s search parameters.

urlObject.searchParams.append(name, value);
  • name: (required) The name of the new query string you want to append to the URL’s search parameter.
  • value: (required) The value of the new query string you want to append to the URL’s search parameter.
import { URL } from "node:url";
const origin = "https://www.codesweetly.com";
const pathname = "/blog/react-image-grid-gallery-v3-release";
const search = "?q=grid";
const hash = "#breaking-changes";
const urlObject = new URL(`${origin}${pathname}${search}${hash}`);
urlObject.searchParams.append("name", "Oluwatobi");
console.log(urlObject.search);
// The invocation above will return: "?q=grid&name=Oluwatobi"

The example above uses the append() method to add the "name=Oluwatobi" query to the end of the URL’s search parameters.

searchParams.get() – Retrieve the first query string matching a specified name

Section titled “searchParams.get() – Retrieve the first query string matching a specified name”

The searchParams.get() method gets the value of the first query string with the name you provide. If it doesn’t find one, it returns null.

urlObject.searchParams.get(name);
  • name: (required) The name of the query string you want to retrieve from the URL’s search parameters.
import { URL } from "node:url";
const origin = "https://www.codesweetly.com";
const pathname = "/blog/react-image-grid-gallery-v3-release";
const search = "?q=grid&name=Oluwatobi";
const hash = "#breaking-changes";
const urlObject = new URL(`${origin}${pathname}${search}${hash}`);
const firstQSearch = urlObject.searchParams.get("q");
console.log(firstQSearch);
// The invocation above will return: "grid"

The example above uses the get() method to get the value of the first "q" query string.

searchParams.getAll() – Retrieves all query strings matching a specified name

Section titled “searchParams.getAll() – Retrieves all query strings matching a specified name”

The searchParams.getAll() method returns an array of all values for query strings whose name matches the specified name. If none exist, it returns an empty array.

urlObject.searchParams.getAll(name);
  • name: (required) The name of the query strings you want to retrieve from the URL’s search parameter.
import { URL } from "node:url";
const origin = "https://www.codesweetly.com";
const pathname = "/blog/react-image-grid-gallery-v3-release";
const search = "?q=grid&name=Oluwatobi";
const hash = "#breaking-changes";
const urlObject = new URL(`${origin}${pathname}${search}${hash}`);
const allQSearches = urlObject.searchParams.getAll("q");
console.log(allQSearches);
// The invocation above will return: ["grid"]

The example above uses the getAll() method to return an array with all the values of the "q" query strings.

searchParams.size – Find out the total number of search parameters in a URL

Section titled “searchParams.size – Find out the total number of search parameters in a URL”

The searchParams.size property displays the total number of query strings in a URL.

urlObject.searchParams.size;
import { URL } from "node:url";
const origin = "https://www.codesweetly.com";
const pathname = "/blog/react-image-grid-gallery-v3-release";
const search = "?q=grid&q=flexbox&q=multi-column&firstName=Oluwatobi";
const hash = "#breaking-changes";
const urlObject = new URL(`${origin}${pathname}${search}${hash}`);
const totalQueryStrings = urlObject.searchParams.size;
console.log(totalQueryStrings);
// The invocation above will return: 4

The example above uses the size property to show how many query strings are in the URL’s search parameters.

searchParams.set() – Set a query string’s value

Section titled “searchParams.set() – Set a query string’s value”

The searchParams.set() method sets the value of a specific query string parameter. If the name doesn’t exist, it adds a new name-value pair to the end of the URL’s search parameters.

urlObject.searchParams.set(name, value);
  • name: (required) The name of the query string whose value you want to set to the URL’s search parameter.
  • value: (required) The value you want to set to the URL’s search parameter.
import { URL } from "node:url";
const origin = "https://www.codesweetly.com";
const pathname = "/blog/react-image-grid-gallery-v3-release";
const search = "?q=grid&q=flexbox&q=multi-column&firstName=Oluwatobi";
const hash = "#breaking-changes";
const urlObject = new URL(`${origin}${pathname}${search}${hash}`);
urlObject.searchParams.set("q", "position");
console.log(urlObject.search);
// The invocation above will return: "?q=position&firstName=Oluwatobi"

The example above uses the set() method to set "position" as the new value for the "q" query string.

searchParams.delete() – Remove query strings from the URL

Section titled “searchParams.delete() – Remove query strings from the URL”

The searchParams.delete() method removes a specific query string from a URL’s search parameters.

urlObject.searchParams.delete(name, value);
  • name: (required) The name of the query strings you want to remove from the URL’s search parameter.
  • value: (optional) The value of the query strings you want to remove from the URL’s search parameter.
import { URL } from "node:url";
const origin = "https://www.codesweetly.com";
const pathname = "/blog/react-image-grid-gallery-v3-release";
const search = "?q=grid&name=Oluwatobi";
const hash = "#breaking-changes";
const urlObject = new URL(`${origin}${pathname}${search}${hash}`);
urlObject.searchParams.delete("q", "grid");
console.log(urlObject.search);
// The invocation above will return: "?name=Oluwatobi"

The example above uses the delete() method to remove all q=grid query strings from the URL.

fileURLToPath Function – Resolve URLs to Paths

Section titled “fileURLToPath Function – Resolve URLs to Paths”

The fileURLToPath function in the node:url module converts URLs into absolute file paths specific to your system.

The fileURLToPath function takes a file URL string (file://) or a URL object as its first argument. Here’s the syntax:

import { fileURLToPath } from "node:url";
const filePath = fileURLToPath("file:///p/a/t/h");

For CommonJS, use:

const { fileURLToPath } = require("node:url");
const filePath = fileURLToPath("file:///p/a/t/h");

When you use Node’s fileURLToPath function, it returns the fully resolved file path for your system. Here’s an example:

// Add the URL module:
import { fileURLToPath } from "node:url";
// Resolve a URL to file path:
const pathString = fileURLToPath("file:///C:/folder/child-folder/file.ext");
// Log the pathString to the console:
console.log(pathString);
// The invocation above will return (Windows):
// "C:\folder\child-folder\file.ext"

The example above uses the fileURLToPath function to turn a file URL into a system-specific file path.

pathToFileURL Function – Resolve Paths to URLs

Section titled “pathToFileURL Function – Resolve Paths to URLs”

The pathToFileURL function in the node:url module converts file paths into absolute file URLs (file://).

The pathToFileURL function takes a path string as its first argument. Here’s the syntax:

import { pathToFileURL } from "node:url";
const fileURL = pathToFileURL("/p/a/t/h");

For CommonJS, use:

const { pathToFileURL } = require("node:url");
const fileURL = pathToFileURL("/p/a/t/h");

When you use Node’s pathToFileURL function, it returns the matching file URL object. Here’s an example:

// Add the URL module:
import { pathToFileURL } from "node:url";
// Resolve a file path to URL:
const urlObject = pathToFileURL("/path/to/file.ext");
// Log the urlObject to the console:
console.log(urlObject);
// The invocation above will return (Windows):
URL {
href: 'file:///C:/path/to/file.ext',
origin: 'null',
protocol: 'file:',
username: '',
password: '',
host: '',
hostname: '',
port: '',
pathname: '/C:/path/to/file.ext',
search: '',
searchParams: URLSearchParams {},
hash: ''
}

The example above uses the pathToFileURL function to convert a file path to its absolute URL.

Before we finish, let’s review what the node:url module is for.

The node:url Module Provides APIs for Working with URLs

Section titled “The node:url Module Provides APIs for Working with URLs”

The node:url module comes with Node.js and gives you tools for working with URLs. Use it whenever your app needs to parse, modify, create, or resolve URLs.