0
0
AstroHow-ToBeginner ยท 3 min read

How to Create Nested Routes in Astro: Simple Guide

In Astro, nested routes are created by organizing your src/pages folder with nested directories. Each folder can have an index.astro file or other page files, which Astro automatically maps to nested URLs reflecting the folder structure.
๐Ÿ“

Syntax

Astro uses the src/pages folder to define routes. Nested routes are created by placing folders inside src/pages. Each folder represents a URL segment. Inside folders, an index.astro file serves as the page for that route. Other files inside the folder become sub-routes.

For example, a file at src/pages/blog/index.astro maps to /blog, and src/pages/blog/post.astro maps to /blog/post.

plaintext
src/pages/
โ”œโ”€โ”€ index.astro       // maps to /
โ”œโ”€โ”€ about.astro       // maps to /about
โ””โ”€โ”€ blog/
    โ”œโ”€โ”€ index.astro   // maps to /blog
    โ””โ”€โ”€ post.astro    // maps to /blog/post
๐Ÿ’ป

Example

This example shows a nested route structure with a homepage, a blog section, and a blog post page. The URLs will be /, /blog, and /blog/post.

astro
---
---
<html>
  <body>
    <h1>Home Page</h1>
  </body>
</html>

---
---
<html>
  <body>
    <h1>Blog Home</h1>
  </body>
</html>

---
---
<html>
  <body>
    <h1>Blog Post</h1>
  </body>
</html>
Output
Visiting / shows 'Home Page'. Visiting /blog shows 'Blog Home'. Visiting /blog/post shows 'Blog Post'.
โš ๏ธ

Common Pitfalls

One common mistake is forgetting to add an index.astro file inside a folder, which causes the route to not resolve correctly. Another is naming files incorrectly or using uppercase letters, which can cause unexpected URLs.

Also, avoid placing multiple index.astro files in the same folder, as it will cause conflicts.

plaintext
// Wrong: Missing index.astro in blog folder
src/pages/blog/post.astro  // /blog/post works
// but /blog will 404 because no index.astro

// Right: Add index.astro
src/pages/blog/index.astro  // /blog works
src/pages/blog/post.astro   // /blog/post works
๐Ÿ“Š

Quick Reference

ConceptDescriptionExample PathURL
Root routeTop-level pagesrc/pages/index.astro/
Nested folderFolder creates URL segmentsrc/pages/blog//blog
Nested pageFile inside foldersrc/pages/blog/post.astro/blog/post
Index fileDefault page for foldersrc/pages/blog/index.astro/blog
โœ…

Key Takeaways

Organize nested routes by creating folders inside src/pages matching URL segments.
Use index.astro inside folders to define the default page for that route.
File names inside folders become sub-routes automatically.
Always include index.astro in nested folders to avoid 404 errors.
Keep file and folder names lowercase and consistent for predictable URLs.