Skip to content

Canonical

Canonical renders a <link rel="canonical"> tag that identifies the primary URL for the current page. This helps search engines understand page versions and consolidate ranking signals. It is scoped to emitting the canonical link only and does not perform URL validation or canonicalization.

proptypedefaultrequireddescription
hrefstring | URL-NoExplicit canonical URL. When omitted, derives from Astro.site and current pathname.

Input:

<Canonical href="https://example.com/docs/page" />

Output:

<link rel="canonical" href="https://example.com/docs/page" />

Input:

<Canonical href={new URL("https://example.com/docs/page")} />

Output:

<link rel="canonical" href="https://example.com/docs/page" />

Derives canonical URL from Astro.site and the current page pathname. Renders nothing if Astro.site is not configured.

Input:

<Canonical />

Output (with Astro.site set to https://example.com and pathname /docs/page):

<link rel="canonical" href="https://example.com/docs/page" />

Auto-derivation from Astro.site and pathname

Section titled “Auto-derivation from Astro.site and pathname”

When no href is provided, Canonical constructs the canonical URL from Astro.site and the current pathname, removing the need to pass it on every page.

No rendering when href is omitted and site is unavailable

Section titled “No rendering when href is omitted and site is unavailable”

If href is not provided and Astro.site is not configured, Canonical renders nothing rather than emitting a tag with an incomplete or relative URL.

---
interface Props {
/**
* Canonical URL for the page. Can be a string or URL object.
* If omitted, derives from Astro.site and current pathname.
*/
href?: string | URL;
}
const { href } = Astro.props;
const defaultCanonical = Astro.site
? new URL(Astro.url.pathname, Astro.site)
: undefined;
const canonicalHref = href === undefined ? defaultCanonical : href;
---
{canonicalHref && <link rel="canonical" href={canonicalHref} />}