Skip to content

URL API

This lesson explains URL API with clear examples, use cases, and best practices so you can use HTML5 APIs confidently in real web applications.

HTML5 URL API Overview

The HTML5 URL API provides a standard way to create, parse, and manipulate URLs in JavaScript. Instead of splitting strings manually, developers can use the URL interface and URLSearchParams to work with protocols, hosts, paths, query strings, and hash fragments reliably.

The URL API is widely used in routing, filtering, pagination, redirect handling, API request building, and shareable link generation. It helps prevent common bugs caused by manual string concatenation.

Feature Description
API Name URL API
Main Interfaces URL and URLSearchParams
Purpose Parse and build URLs safely
Query Handling searchParams on URL
Validation URL.canParse()
Common Uses Routing, filters, redirects, API URLs, blob links

Basic URL Parsing Example

const url =
  new URL(
    "https://example.com/products?page=2&sort=price#details"
  );

console.log(url.protocol);
console.log(url.hostname);
console.log(url.pathname);
console.log(url.search);
console.log(url.hash);

The URL constructor breaks a full URL into readable parts such as protocol, hostname, pathname, query string, and hash fragment.

How URL API Works

A URL string is parsed into structured properties. You can read those properties, update them, and then use url.href or url.toString() to generate the final URL again.

Step Description Example Syntax
Create URL Parse an absolute or relative URL. new URL("/docs", "https://example.com")
Read Parts Access protocol, host, path, and query values. url.pathname
Modify Parts Update URL segments directly. url.pathname = "/blog"
Manage Query Use URLSearchParams for key-value data. url.searchParams.set("page", "3")
Validate URL Check whether a string is a valid URL. URL.canParse(value)
Output Final URL Serialize the updated URL object. url.href

Common URL Properties

Property Description Example Value
href Full URL string. https://example.com/docs?page=1
protocol URL scheme including colon. https:
host Hostname and optional port. example.com:443
hostname Domain name without port. example.com
pathname Path portion of the URL. /docs
search Query string including ?. ?page=1&sort=name
hash Fragment identifier including #. #section-2
origin Protocol, host, and port combined. https://example.com

Resolve a Relative URL

const baseUrl =
  "https://example.com/blog/";

const articleUrl =
  new URL(
    "../articles/html5-url-api",
    baseUrl
  );

console.log(articleUrl.href);
// https://example.com/articles/html5-url-api

When the first argument is a relative path, pass a base URL as the second argument. This is useful for building links from the current page location.

Work with Query Parameters

const url =
  new URL("https://shop.example.com/search");

url.searchParams.set("q", "laptop");
url.searchParams.set("page", "1");
url.searchParams.set("sort", "price");

console.log(url.searchParams.get("q"));
console.log(url.searchParams.has("sort"));
console.log(url.href);

url.searchParams.delete("page");
url.searchParams.append("tag", "sale");
url.searchParams.append("tag", "featured");

console.log(
  url.searchParams.getAll("tag")
);

URLSearchParams makes it easy to add, read, update, and remove query string values without manual string building.

Update URL Parts Safely

const url =
  new URL(window.location.href);

url.pathname = "/dashboard";
url.searchParams.set("tab", "settings");
url.hash = "notifications";

history.replaceState(
  null,
  "",
  url.toString()
);

You can update the current page URL by changing properties on a URL object and then passing the result to the History API. This is a common pattern in single-page applications.

Build an API Request URL

function buildApiUrl(endpoint, params = {}) {
  const url =
    new URL(endpoint, "https://api.example.com");

  Object.entries(params).forEach(
    ([key, value]) => {
      if (value !== undefined && value !== null) {
        url.searchParams.set(
          key,
          String(value)
        );
      }
    }
  );

  return url.toString();
}

const usersUrl =
  buildApiUrl("/users", {
    page: 2,
    limit: 20,
    active: true
  });

console.log(usersUrl);

Helper functions built around the URL API make API request URLs cleaner and safer, especially when optional query parameters are involved.

Validate a URL String

function isValidUrl(value) {
  return URL.canParse(value);
}

function isValidHttpUrl(value) {
  if (!URL.canParse(value)) {
    return false;
  }

  const url = new URL(value);
  return url.protocol === "http:" ||
    url.protocol === "https:";
}

console.log(
  isValidUrl("https://example.com")
);

console.log(
  isValidHttpUrl("not-a-url")
);

Use URL.canParse() to check whether a string is a valid URL before using it in links, redirects, or form submissions.

Create a Blob URL

const text =
  "Hello from the URL API.";

const blob =
  new Blob([text], {
    type: "text/plain"
  });

const blobUrl =
  URL.createObjectURL(blob);

const downloadLink =
  document.createElement("a");

downloadLink.href = blobUrl;
downloadLink.download = "message.txt";
downloadLink.textContent = "Download file";
document.body.appendChild(downloadLink);

// Release memory when finished

URL.revokeObjectURL(blobUrl);

URL.createObjectURL() creates a temporary URL for files, blobs, and media sources. Always call URL.revokeObjectURL() when the URL is no longer needed.

Common URLSearchParams Methods

Method Description Common Use
set() Sets or replaces a query parameter. Update filters or pagination.
get() Reads the first value for a key. Read a single query value.
getAll() Reads all values for a repeated key. Handle multi-select filters.
has() Checks whether a key exists. Conditional query handling.
append() Adds another value for the same key. Tags or repeated categories.
delete() Removes a query parameter. Clear filters or reset state.
toString() Serializes params into a query string. Build request URLs.

Common URL API Use Cases

  • Building pagination, sorting, and search filter URLs.
  • Updating browser URLs in single-page applications.
  • Parsing redirect targets and external links safely.
  • Constructing API endpoints with optional query parameters.
  • Reading current page state from the query string.
  • Creating temporary download links for generated files.

URL API Best Practices

  • Prefer the URL API over manual string splitting and concatenation.
  • Use URLSearchParams for all query string changes.
  • Validate untrusted URLs before redirects or link rendering.
  • Use a base URL when resolving relative paths.
  • Encode values automatically through the API instead of hand-encoding.
  • Revoke blob URLs after downloads or previews finish.
  • Keep URL-building logic in small reusable helper functions.

Security Considerations

  • Never redirect users to unvalidated external URLs.
  • Check protocol and hostname before using a URL for navigation.
  • Be careful with user-supplied query values in redirects.
  • Do not assume a parsed URL is safe just because it is valid.
  • Sanitize displayed links and avoid javascript URL schemes.
  • Limit open redirects in authentication and logout flows.

Common URL API Mistakes

  • Building query strings manually with ? and & concatenation.
  • Forgetting the base URL when parsing relative paths.
  • Assuming searchParams.get() returns a boolean instead of a string.
  • Not revoking blob URLs and causing memory leaks.
  • Using set() when multiple values for one key are needed.
  • Redirecting to URLs without validating protocol and host.
  • Mutating the URL object without updating browser history when needed.

URL API vs Manual String Parsing

Feature URL API Manual String Parsing
Reliability Handles encoding and edge cases consistently. Easy to break with special characters.
Readability Clear property names such as pathname. Often requires custom regex or splits.
Query Handling Built-in URLSearchParams support. Requires custom parsing logic.
Maintenance Easier to test and reuse. More bug-prone over time.

Key Takeaways

  • The URL API provides structured parsing and building of URLs in JavaScript.
  • Use new URL() to read and update protocol, host, path, query, and hash values.
  • URLSearchParams is the safest way to manage query strings.
  • URL.canParse() helps validate URLs before redirects and link usage.
  • Blob URLs are useful for downloads but should always be revoked after use.

Pro Tip

Create one helper such as updateQueryParams() that accepts the current URL and a params object. This keeps routing, filters, and pagination logic consistent across your entire app.