Language: EN


How to work with URLs with Node.js

In Node.js, the url module provides utilities to parse, construct, modify, and validate URLs easily.

This is very important, because we will very frequently use Node.js for tasks associated with URLs, such as serving or downloading a resource.

Examples of using the URL module

Parsing a URL

The first step to working with a URL is to parse it to extract its components. The URL method of the url module allows us to do this easily:

import { URL } from 'node:url';

const urlText = '';
const myUrl = new URL(urlText);

console.log('Protocol:', myUrl.protocol);
console.log('Path:', myUrl.pathname);
console.log('Search parameters:', myUrl.searchParams);

Building a URL

We can also construct a URL from its components using the URL constructor:

import { URL } from 'node:url';

const baseUrl = '';
const path = '/path/subpath';
const params = new URLSearchParams({
  param1: 'value1',
  param2: 'value2'

const completeUrl = new URL(path, baseUrl); = params.toString();

console.log('Complete URL:', completeUrl.href);

Modifying URL parameters

We can dynamically manipulate the parameters of a URL using the URLSearchParams class:

import { URLSearchParams } from 'node:url';

const url = new URL('');

// Get parameters
console.log('Parameter 1:', url.searchParams.get('param1'));
console.log('Parameter 2:', url.searchParams.get('param2'));

// Add parameter
url.searchParams.append('param3', 'value3');
console.log('URL with new parameter:', url.href);

// Delete parameter
console.log('URL without param2:', url.href);

Resolving relative URLs

The url module allows us to resolve relative URLs in the context of a base URL:

import { resolve } from 'node:path';

const baseUrl = '';
const relativeUrl = 'subfolder/file.html';

const resolvedUrl = new URL(relativeUrl, baseUrl);
console.log('Resolved URL:', resolvedUrl.href);

Validating a URL

Finally, we can check if a string is a valid URL using the URL constructor within a try-catch block:

import { URL } from 'node:url';

function isValidURL(url) {
  try {
    new URL(url);
    return true;
  } catch (error) {
    return false;

console.log('Is the URL valid?', isValidURL('')); // true
console.log('Is the URL valid?', isValidURL('this is not a URL')); // false