#how to use canonical

7 messages · Page 1 of 1 (latest)

deft swift
#

how to use canonical url in astro? what is the recommended way of doing it

drifting lintelBOT
#

Hi @deft swift. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

In Astro v2, Astro.canonicalURL was removed. The recommended way is to build the canonical URL yourself using Astro.url and Astro.site.[Upgrade v2]

Example in a page component:

---
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
---

<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="canonical" href={canonicalURL.toString()} />
    <title>My Page</title>
  </head>
  <body>
    <!-- page content -->
  </body>
</html>

This uses the current request path (Astro.url.pathname) and your configured site URL (Astro.site) to generate the canonical URL.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@deft swift Kapa.ai is still learning and improving, please let me know how I did by reacting below.

deft swift
#

@drifting lintel we are already on astro 5 why version 2

drifting lintelBOT
#

Let me check the knowledge base for you again. One moment! :books:

#

Astro’s main docs are always written for the latest version (like v5), but the upgrade guides explain what changed between versions. [Upgrade Astro]

The canonical URL info I referenced is from the “Upgrade to v2” guide because that’s where Astro officially:

  • Deprecated and then removed Astro.canonicalURL
  • Recommended the new pattern using Astro.url + Astro.site [Upgrade to v2]

That recommendation (constructing the canonical URL with new URL(Astro.url.pathname, Astro.site)) is still the documented way to do it in later versions; the guide just happens to live under the v2 upgrade docs because that’s when the breaking change happened.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: