Pages and routing
Create routes with files
Map files under src/pages to URLs without creating a separate route table.
In Astro, a file under src/pages/ is a route. The file’s path decides the URL:
src/pages/index.astro → /
src/pages/about.astro → /about/
src/pages/docs/install.astro → /docs/install/
There is no route table to maintain and no router object to configure. Adding a route means creating a file. Removing a route means deleting one.
This is file-based routing. If you used Next.js or a static site generator, you’ve seen it before.
Why I like it
The mapping works in both directions. Given a file, you know its URL. Given a URL, you know which file renders it.
That second direction is the useful one. When /docs/install/ breaks, you open src/pages/docs/install.astro. No searching. So keep the folder hierarchy obvious, because the source tree is your sitemap.
Not only .astro files
Pages can be .astro components, Markdown files, MDX when you add the integration, plain .html, or endpoint files like .ts.
The extension decides what the route produces. An .astro page renders its template. A Markdown page renders its content. A .ts endpoint returns whatever Response your code builds. We’ll cover each of these in this module.
Add two routes
Let’s create a contact page and a guides section:
mkdir -p src/pages/guides
touch src/pages/contact.astro src/pages/guides/index.astro
Give each file a heading, like <h1>Contact</h1>. Open /contact/ and /guides/ in the dev server. Both work, with no configuration.
Now run npm run build and look inside dist/. You’ll find dist/contact/index.html and dist/guides/index.html. One folder with an index.html per route. That’s the default output shape.
Two things to watch
First, don’t create two files that want the same URL. src/pages/blog.astro and src/pages/blog/index.astro both map to /blog/. You shouldn’t have to remember which one wins. Keep one.
Second, trailing slashes. In development, /about and /about/ both work. Your host may not be so relaxed. Some platforms redirect one to the other, some return a 404. Check your important URLs on the deployed site, not only in dev.
Lesson completed