Astro: Adding more pages

Now let’s try adding more pages to your Astro site.

Create a about.astro file under src/pages

This file will create a new page that listens on the route /about

If you visit http://localhost:4321/about, it works:

It shows a blank page, but no error like you’d get if you went to a route not defined, for example http://localhost:4321/test:

Now you could add a simple HTML tag to the component, like we did before with the Test component:

If you open the DevTools you’d see a simple HTML structure, without all the <head> and <body> tags and everything that makes an HTML page “correct”:

(the DOCTYPE and the script were added by Astro automatically)

You could now add the HTML directly in the component:

But what you’d usually do is use a layout:

---
import Layout from '../layouts/Layout.astro'
---

<Layout title='About'>
  <p>test</p>
</Layout>

and the src/layouts/Layout.astro will provide the base markup shared with src/pages/index.astro too.

This is a common way to have a base layout.

You can have multiple layouts, for example if you want to have a layout for single pages, and a different one with a sidebar for blog posts. I have 4 different layouts in my site.

To link pages with each other we use plain HTML <a> elements.

So we can link back to / using:

---
import Layout from '../layouts/Layout.astro'
---

<Layout title='About'>
  <p>test</p>
  <a href="/">back to the home page</a>
</Layout>

Astro does not provide client-side navigation by default, so all links do a full-page refresh, like it happens in plain HTML pages.

However you can easily add view transitions to add client-side navigation, as we’ll see later.

Lessons in this unit:

0: Introduction
1: Your first Astro site
2: The structure of an Astro site
3: Astro components
4: ▶︎ Adding more pages
5: Dynamic routing
6: Markdown in Astro
7: Images
8: Content collections
9: CSS in Astro
10: JavaScript in Astro
11: Client-side routing and view transitions
12: SSR in Astro
13: API endpoints in Astro