0
0
AstroHow-ToBeginner ยท 3 min read

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.props instead of Astro.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

ConceptUsageNotes
Dynamic route file[param].astroCaptures URL part as param
Access paramAstro.params.paramUse inside frontmatter
Example URL/blog/my-postMatches [slug].astro with slug='my-post'
Static routefilename.astroNo brackets means fixed path
Nested dynamicpages/blog/[slug].astroWorks 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.