#Get current page URL

2 messages · Page 1 of 1 (latest)

ocean nacelleBOT
#

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

#

To get the current page URL in Astro with static output, you can use the Astro.url property. This property provides a URL (https://developer.mozilla.org/en-US/docs/Web/API/URL) object constructed from the current Astro.request.url URL string value.

Here's how you can use it:

---
const currentURL = Astro.url;
---

<h1>The current URL is: {currentURL}</h1>
<h1>The current URL pathname is: {currentURL.pathname}</h1>
<h1>The current URL origin is: {currentURL.origin}</h1>

It's important to note that for static sites, if the site configuration is not set, Astro.url will use localhost in development mode Astro.url (https://docs.astro.build/en/reference/api-reference/#astrourl).

You can also use Astro.url to construct new URLs. For example, to create a canonical URL:

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

<link rel="canonical" href={canonicalURL} />

This approach is recommended over the deprecated Astro.canonicalURL Removed: Astro.canonicalURL (https://docs.astro.build/en/guides/upgrade-to/v2/#removed-astrocanonicalurl).

Remember that Astro.url is equivalent to doing new URL(Astro.request.url), providing you with all the properties and methods of the URL (https://developer.mozilla.org/en-US/docs/Web/API/URL) object.

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