(Astro) Get current page URL
How to get the current page URL in Astro
・ 1 min read
Last updated:
Astro.url returns the current page URL from the Request object. The return value is a URL object which contains properties like pathname and origin.
const currentPath = Astro.url.pathname;
Useful when you need to highlight navigation links based on current page:
<a href="/me" class={currentPath === "/me" ? "active" : ""}>
About Me
</a>
Splitting nested URL pathsSection titled Splitting%20nested%20URL%20paths
Use String.split()
to split an input string into an array of substrings. It’s split based on a specified operator such as a slash (/
).
const currentPath = Astro.url.pathname; // "/foo/bar"
const firstPath = currentPath.split("/")[1];
console.log(firstPath); // returns 'foo'
currentPath.split("/")[0]; // returns '/'
currentPath.split("/")[2]; // returns 'bar'
Access a specific element of the resulting array by using the index number either at the end like in split()[2]
.