Course contentsShow
← JavaScript
Lesson 2310 of 2,72347. Networking PrimitivesFree lesson

Resolving Relative URLs Against Base URLs

Understand how the URL constructor resolves relative paths using a base URL parameter for proper URL construction.

Resolving Relative URLs Against Base URLs

What you'll learn: How the URL constructor automatically resolves relative paths when given a base URL, so you can build complete URLs from fragments.

When working with web resources, you often encounter relative URLs like "../api/users" or "./images/logo.png". The URL constructor takes an optional second parameter—a base URL—that acts as the starting point for resolving these relative paths into absolute URLs.

How Resolution Works

Think of it like giving directions: "Go three blocks north" only makes sense if you know where you're starting from. Similarly, a relative URL needs a base URL to become meaningful.

The URL constructor follows standard URL resolution rules:

  • "./" means "current directory"
  • "../" means "parent directory"
  • Paths without prefixes are resolved relative to the base's current path

Using the Base Parameter

const base = "https://example.com/products/electronics/";

// Relative path resolved against base
const url1 = new URL("keyboards", base);
console.log(url1.href);
// "https://example.com/products/electronics/keyboards"

// Navigate up one level
const url2 = new URL("../clothing", base);
console.log(url2.href);
// "https://example.com/products/clothing"

// Absolute path from root
const url3 = new URL("/api/search", base);
console.log(url3.href);
// "https://example.com/api/search"

Notice how "/api/search" (starting with /) ignores the base's path and starts from the domain root, while relative paths like "keyboards" build upon the base's existing path.

This is especially useful when working with APIs that return relative links or when building URLs dynamically from a known starting point.

Key Takeaway: The URL constructor's second parameter resolves relative paths against a base URL using standard directory navigation rules, automatically producing complete, absolute URLs.