#How to get current page's ID in component

2 messages · Page 1 of 1 (latest)

west oakBOT
#

Hi @lunar lily. 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's ID in an Astro component, you should use the dynamic route parameter from Astro's routing system, not Astro.url.pathname. When you define a dynamic route like src/pages/posts/[id].astro, Astro will provide the id value via Astro.params:

---
// src/pages/posts/[id].astro
const { id } = Astro.params;
---
<h1>Post ID: {id}</h1>

Astro.url.pathname gives you the full path (e.g., /posts/123), but Astro.params.id gives you just the dynamic segment (e.g., 123) that matches the [id] in your file name. This is the recommended way to access the current page's ID in a component for dynamic routes Astro render context.

If you are using getStaticPaths, the params you return there will also be available as Astro.params in your component getStaticPaths().

If you are working within a Starlight site, you can access the current page's ID using Astro.locals.starlightRoute.id starlightRoute.

In summary:


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