How to Create Dynamic Routes in Astro: Simple Guide
In Astro, create dynamic routes by naming your page files with square brackets like
[param].astro. This lets you capture URL parts as parameters accessible in your component via Astro.params.Syntax
Dynamic routes in Astro use file names with square brackets to capture URL parameters. For example, src/pages/blog/[slug].astro matches URLs like /blog/my-post and captures my-post as the slug parameter.
Inside the page, you access the parameter with Astro.params.slug.
astro
src/pages/blog/[slug].astro
---
const { slug } = Astro.params;
---
<html>
<body>
<h1>Blog Post: {slug}</h1>
</body>
</html>Example
This example shows a dynamic route that displays the slug from the URL. If you visit /product/shoes, it will show "Product: shoes".
astro
---
const { productId } = Astro.params;
---
<html>
<body>
<h1>Product: {productId}</h1>
</body>
</html>Output
Visiting /product/shoes shows: Product: shoes
Common Pitfalls
- Forgetting to use square brackets in the file name means the route is static, not dynamic.
- Trying to access parameters with
Astro.propsinstead ofAstro.params. - Using nested folders incorrectly; dynamic segments must be in the file name, not folder name.
text
Wrong: src/pages/[id]/index.astro (dynamic folder - not supported) Right: src/pages/[id].astro (dynamic file name) Accessing params: const { id } = Astro.params; // Correct const { id } = Astro.props; // Wrong
Quick Reference
| Concept | Usage | Notes |
|---|---|---|
| Dynamic route file | [param].astro | Captures URL part as param |
| Access param | Astro.params.param | Use inside frontmatter |
| Example URL | /blog/my-post | Matches [slug].astro with slug='my-post' |
| Static route | filename.astro | No brackets means fixed path |
| Nested dynamic | pages/blog/[slug].astro | Works for nested paths |
Key Takeaways
Use square brackets in file names to create dynamic routes in Astro.
Access dynamic parameters inside the page with Astro.params.
Dynamic routes match URL parts and pass them as parameters.
Avoid using folders with brackets; use file names instead.
Double-check parameter names match between file and code.