Course contentsShow
← Web Development
Lesson 949 of 2,98217. URL and History ManagementFree lesson

Building URLs Programmatically

Construct complex URLs safely by creating URL objects and setting properties rather than string concatenation.

Building URLs Programmatically

What you'll learn: You'll discover how to construct complex URLs safely using the URL API instead of manually gluing strings together.

Why Not Just Use String Concatenation?

When building URLs by joining strings with +, you risk forgetting to encode special characters, missing question marks or ampersands, or creating malformed URLs. It's like trying to assemble furniture without instructions—you might get it right, but one wrong piece breaks everything.

The Safe Way: Create and Configure

Instead of concatenating, create a URL object and set its properties. The API handles all the tricky encoding and formatting automatically:

// ❌ Risky: manual string building
const unsafe = "https://api.example.com/search?q=" + userInput + "&page=" + pageNum;

// ✅ Safe: programmatic construction
const url = new URL("https://api.example.com/search");
url.searchParams.append("q", userInput);
url.searchParams.append("page", pageNum);
const safe = url.href;

Building From Scratch

You can also construct the entire URL programmatically by setting each property:

const url = new URL("https://example.com");
url.pathname = "/api/users";
url.searchParams.set("role", "admin");
url.searchParams.set("active", "true");
url.hash = "results";

console.log(url.href);
// "https://example.com/api/users?role=admin&active=true#results"

The URL object automatically handles proper formatting—slashes, question marks, ampersands, and encoding all happen behind the scenes.

When to Use This Pattern

Use programmatic URL building whenever you're constructing URLs from user input, configuration data, or dynamic values. It prevents injection vulnerabilities and ensures your URLs are always valid.

Key Takeaway: Build complex URLs by creating URL objects and setting properties rather than concatenating strings—it's safer, cleaner, and handles encoding automatically.