How to Get the Current Page URL in Astro

  • 289Words
  • 1Minutes
  • 07 Aug, 2024

In Astro, we sometimes need to get the address of the current page for redirections or other purposes. Astro provides useful tools and global variables that can help us achieve this.

Using Astro.url.pathname

Astro provides Astro.url.pathname, a global object containing the URL path of the current request. We can use it in page components to get the current page URL. For example:

1
---
2
import { Astro } from "astro";
3
const currentPath = Astro.url.pathname;
4
---
5
6
<!doctype html>
7
<html lang="en">
8
<head>
9
<meta charset="UTF-8" />
10
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
11
<title>My Astro Blog</title>
12
</head>
13
<body>
14
<h1>Welcome to My Blog</h1>
15
<p>Current Page Path: {currentPath}</p>
16
</body>
17
</html>

Using Astro.request.url

Another method is to use Astro.request.url to get the full URL of the current page. This is useful when you need the complete URL. For example:

1
---
2
import { Astro } from "astro";
3
const currentUrl = Astro.request.url;
4
---
5
6
<!doctype html>
7
<html lang="en">
8
<head>
9
<meta charset="UTF-8" />
10
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
11
<title>My Astro Blog</title>
12
</head>
13
<body>
14
<h1>Welcome to My Blog</h1>
15
<p>Current Page Full URL: {currentUrl}</p>
16
</body>
17
</html>

Using slug in Frontmatter

Astro provides slug path information for pages generated from Markdown, which we can use to construct the page URL. For example:

1
---
2
title: "My Blog Post"
3
---

In the page component, we can use it like this:

1
---
2
import { Astro } from "astro";
3
const { slug } = Astro.props;
4
const currentPath = `/posts/${slug}`;
5
---
6
7
<!doctype html>
8
<html lang="en">
9
<head>
10
<meta charset="UTF-8" />
11
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
12
<title>My Astro Blog</title>
13
</head>
14
<body>
15
<h1>Welcome to My Blog</h1>
16
<p>Current Page Path: {currentPath}</p>
17
</body>
18
</html>

Conclusion

We can choose different methods to get the current page URL in Astro based on our needs. Whether using Astro’s global objects or utilizing information from Frontmatter, these approaches can help us access URL information in the generated pages.