What is Routing in Astro?
In Astro, “routing” refers to how your website’s URLs are mapped to the content that gets displayed on those URLs. Astro employs a very intuitive and powerful file-based routing system. This means you don’t typically create a separate “routes” configuration file; instead, your project’s file structure directly dictates the URLs of your site.
Here’s a breakdown of routing in Astro:
1. File-Based Routing: The Core Concept
src/pages/
directory: This is the magic folder. Any supported file type you place directly insidesrc/pages/
(or in subdirectories within it) automatically becomes a page on your website.- Supported File Types: Astro automatically recognizes:
.astro
components (Astro’s own templating language).md
(Markdown) files.mdx
(MDX) files (with the MDX integration installed).html
files.js
or.ts
files (used for API endpoints, not typically for full pages)
- URL Mapping: The path and filename relative to
src/pages/
determine the URL.src/pages/index.astro
maps to/
(your homepage).src/pages/about.astro
maps to/about
.src/pages/blog/first-post.md
maps to/blog/first-post
.src/pages/products/index.astro
maps to/products
. (If a folder containsindex.astro
, the URL for the folder will lead to thatindex
file).src/pages/contact/form.astro
maps to/contact/form
.
2. Static Routes
- These are the simplest routes, as described above. You create a file, and it directly maps to a single URL.
- Astro is primarily a Static Site Generator (SSG) by default. This means that for static routes, Astro generates a complete HTML file for each page at build time. This results in incredibly fast loading times for your users because the browser just needs to download pre-built HTML, CSS, and optimized JavaScript.