File Based Routing in Astro: How It Works and When to Use
Astro means that the pages you create inside the src/pages folder automatically become routes on your website. Each file corresponds to a URL path, so you don't need to manually configure routes.How It Works
File based routing in Astro works like a map where each file in the src/pages folder is a stop on your website's journey. When you add a new file, Astro automatically creates a route for it based on the file's name and folder structure. For example, a file named about.astro becomes the /about page.
This is similar to how a library catalog works: each book (file) has a place on the shelf (folder), and you find it by its label (filename). You don’t have to write extra instructions to tell Astro where the page lives; it figures it out from the file layout.
Folders inside src/pages create nested routes. For example, a file at src/pages/blog/post.astro becomes the route /blog/post. This makes organizing your site simple and intuitive.
Example
This example shows how creating files in src/pages automatically sets up routes.
src/pages/ index.astro // route: / about.astro // route: /about blog/ post.astro // route: /blog/post --- // src/pages/about.astro --- <html> <body> <h1>About Page</h1> <p>Welcome to the about page.</p> </body> </html>
When to Use
Use file based routing in Astro when you want a simple, automatic way to create website pages without manually setting up routes. It is perfect for blogs, portfolios, documentation sites, and small to medium websites where the URL structure matches the file organization.
This approach saves time and reduces errors because you don’t have to write routing code. It also helps keep your project organized, as the folder structure directly reflects your site’s navigation.
Key Points
- Each file in
src/pagesbecomes a route automatically. - Folder structure creates nested routes.
- No manual route configuration needed.
- Great for simple and organized site navigation.