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.
| prop | type | default | required | description |
|---|---|---|---|---|
href | string | URL | - | No | Explicit canonical URL. When omitted, derives from Astro.site and current pathname. |
Examples
Section titled “Examples”Input:
<Canonical href="https://example.com/docs/page" />Output:
<link rel="canonical" href="https://example.com/docs/page" />URL object
Section titled “URL object”Input:
<Canonical href={new URL("https://example.com/docs/page")} />Output:
<link rel="canonical" href="https://example.com/docs/page" />Automatic
Section titled “Automatic”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" />Decisions Made
Section titled “Decisions Made”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.
Source code
Section titled “Source code”---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} />}