How to Use Params in Astro Route for Dynamic Pages
In Astro, you use
[param] in your route file name to capture URL parameters dynamically. Access these params inside your page using the Astro.params object to customize content based on the URL.Syntax
Astro uses file-based routing where you define dynamic segments by wrapping the segment name in square brackets in the filename. For example, src/pages/blog/[slug].astro captures the slug part of the URL.
Inside the Astro component, you access the parameter via Astro.params.slug. This lets you use the dynamic value in your page.
astro
---
const { slug } = Astro.params;
---
<html>
<body>
<h1>Blog Post: {slug}</h1>
</body>
</html>Example
This example shows a dynamic blog post page that uses the URL parameter slug to display the post title.
astro
--- const { slug } = Astro.params; --- <html lang="en"> <head> <title>Post: {slug}</title> </head> <body> <h1>Welcome to the blog post: {slug}</h1> <p>This page shows content for the post with slug <strong>{slug}</strong>.</p> </body> </html>
Output
<h1>Welcome to the blog post: my-first-post</h1>
<p>This page shows content for the post with slug <strong>my-first-post</strong>.</p>
Common Pitfalls
- Forgetting to wrap the param name in square brackets in the filename, e.g., using
slug.astroinstead of[slug].astro. - Trying to access params outside the
Astroobject or before destructuringAstro.params. - Not matching the param name in the filename and in the code (e.g., filename uses
[id]but code usesAstro.params.slug).
astro
--- // Wrong filename: src/pages/blog/slug.astro const { slug } = Astro.params; // slug will be undefined --- // Correct filename: src/pages/blog/[slug].astro const { slug } = Astro.params; // slug contains the URL segment
Quick Reference
Use these tips to work with params in Astro routes:
- Wrap dynamic segments in square brackets in filenames:
[param]. - Access params inside the component with
Astro.params.param. - Use multiple params by adding multiple bracketed segments, e.g.,
[category]/[post].astro. - Params are always strings from the URL.
Key Takeaways
Use square brackets in filenames to define dynamic route params in Astro.
Access route params inside your component with Astro.params.paramName.
Param names in filenames and code must match exactly.
Params come as strings from the URL and can be used to customize page content.
Multiple params can be used by nesting bracketed segments in the route path.