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
