liveBook · Manning

Canonical URL

As explained in Vanilla Web

A canonical URL is the preferred URL designated as the authoritative address for a page or resource among equivalent URL variants.

A canonical URL identifies the preferred address for public content that may appear under multiple URL variants. Declare it in the document’s <head> to help consolidate those variants. section 10.1.1 section 10.1.10

Keep canonical metadata aligned with routing decisions:

  • Choose consistent route shapes and avoid unnecessary variants, including differences in case, trailing slashes, or default query parameters. section 10.1.10
  • For multilingual content, give each translated page its own canonical URL and use hreflang links for equivalent language versions. section 10.1.10
  • Serve the correct canonical URL in initial HTML when possible; update it during client-side navigation as a consistency layer, not as the sole discoverability strategy. section 10.1.10
function setCanonical(path) {
  const url = new URL(path, location.origin);

  let link = document.querySelector('link[rel="canonical"]');
  if (!link) {
    link = document.createElement("link");
    link.rel = "canonical";
    document.head.append(link);
  }

  link.href = url.href;
}

setCanonical("/products/espresso-maker");

A small browser-native helper creates the canonical link when needed and updates its absolute URL for the current route. section 10.1.10

How Vanilla Web covers it

How deep it goes
Demonstrate document markup and client-side updates, while emphasizing initial HTML and deferring discoverability to server-rendered metadata when needed.
Examples
Compare product-list URL variants and show canonical links for product lists and product details.
What you can do after
Configure a canonical link in HTML or update it with browser APIs during client-side route changes.
How it connects
Connect canonical URLs to routing, query parameters, hreflang, and document metadata.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Vanilla Web. The section links point to the parts of the book it draws on.