0
0
Node.jsframework~5 mins

Relative vs absolute URL resolution in Node.js

Choose your learning style9 modes available
Introduction

We use relative and absolute URLs to tell programs where to find web pages or resources. Understanding how Node.js resolves these URLs helps us load the right files or links.

When you want to link to a file or page within the same website using a short path.
When you need to specify a full web address to access resources from anywhere on the internet.
When building a server that handles requests and needs to resolve paths correctly.
When combining base URLs with relative paths to get the full address.
When working with APIs that require full URLs or relative paths.
Syntax
Node.js
new URL(input, base);

input is the URL string you want to resolve.

base is the base URL used to resolve relative URLs. If input is absolute, base is ignored.

Examples
This resolves the relative path /path/page.html against the base URL https://example.com/folder/, resulting in https://example.com/path/page.html.
Node.js
const url = new URL('/path/page.html', 'https://example.com/folder/');
console.log(url.href);
This uses an absolute URL, so no base is needed. The output is the same URL.
Node.js
const url = new URL('https://google.com/search');
console.log(url.href);
This resolves a relative path without a leading slash, so it appends to the base path, resulting in https://example.com/gallery/images/photo.png.
Node.js
const url = new URL('images/photo.png', 'https://example.com/gallery/');
console.log(url.href);
Sample Program

This example shows how Node.js resolves different URLs using the URL class. It prints the full resolved URLs for relative and absolute inputs.

Node.js
import { URL } from 'url';

// Relative URL with base
const relativeUrl = new URL('docs/tutorial.html', 'https://site.com/start/');
console.log(relativeUrl.href);

// Absolute URL ignores base
const absoluteUrl = new URL('https://other.com/page');
console.log(absoluteUrl.href);

// Relative URL with leading slash replaces path
const rootRelativeUrl = new URL('/about', 'https://site.com/start/');
console.log(rootRelativeUrl.href);
OutputSuccess
Important Notes

Relative URLs without a leading slash append to the base path.

Relative URLs with a leading slash replace the path part of the base URL.

Absolute URLs ignore the base and stand alone.

Summary

Relative URLs depend on a base URL to form a full address.

Absolute URLs are complete and do not need a base.

Node.js URL class helps combine and resolve URLs correctly.