How Routing Works in Astro: Simple Guide to Astro Routing
In Astro, routing works by creating files and folders inside the
src/pages directory, where each file corresponds to a route URL. Dynamic routes use square brackets like [param] to capture URL parts, and Astro automatically maps these files to routes without extra configuration.Syntax
Astro uses a file-based routing system where the file path inside src/pages defines the URL path. Dynamic segments are wrapped in square brackets [ ]. For example, src/pages/about.astro maps to /about, and src/pages/blog/[slug].astro maps to dynamic URLs like /blog/my-post.
src/pages/index.astroโ/src/pages/contact.astroโ/contactsrc/pages/blog/[id].astroโ/blog/123whereidis dynamic
plaintext
src/pages/ index.astro // maps to / about.astro // maps to /about blog/ [slug].astro // maps to /blog/:slug (dynamic route)
Example
This example shows a dynamic blog post route that reads the slug from the URL and displays it on the page.
astro
--- const { slug } = Astro.params; --- <html lang="en"> <head> <title>Blog Post: {slug}</title> </head> <body> <h1>Blog Post: {slug}</h1> <p>This page shows the blog post with slug: <strong>{slug}</strong>.</p> </body> </html>
Output
<h1>Blog Post: my-first-post</h1>
<p>This page shows the blog post with slug: <strong>my-first-post</strong>.</p>
Common Pitfalls
Common mistakes include:
- Placing route files outside
src/pagesfolder, so Astro won't recognize them. - Forgetting to use square brackets for dynamic routes, which makes the route static.
- Not accessing
Astro.paramscorrectly inside dynamic route files. - Using file extensions other than
.astro,.jsx, or.tsxsupported by Astro for pages.
astro
--- // Wrong: static route file instead of dynamic // src/pages/blog/slug.astro --- <p>This will not capture dynamic slug.</p> --- // Right: dynamic route file // src/pages/blog/[slug].astro --- const { slug } = Astro.params; --- <p>Slug is {slug}</p>
Quick Reference
Summary tips for Astro routing:
- Put pages inside
src/pagesfolder. - Use
index.astrofor root route/. - Use square brackets
[param]for dynamic routes. - Access dynamic parts with
Astro.params.param. - Supported page extensions:
.astro,.jsx,.tsx.
Key Takeaways
Astro routing is file-based: file paths in src/pages map to URLs.
Use square brackets [param] in filenames for dynamic routes.
Access dynamic route parameters via Astro.params inside the page.
Keep all route files inside src/pages for Astro to detect them.
Supported page files include .astro, .jsx, and .tsx extensions.