0
0
AstroHow-ToBeginner ยท 3 min read

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 โ†’ /contact
  • src/pages/blog/[id].astro โ†’ /blog/123 where id is 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/pages folder, so Astro won't recognize them.
  • Forgetting to use square brackets for dynamic routes, which makes the route static.
  • Not accessing Astro.params correctly inside dynamic route files.
  • Using file extensions other than .astro, .jsx, or .tsx supported 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/pages folder.
  • Use index.astro for 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.