Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Pages and routing

Astro has no file that lists routes. A route, the match between an address and a page, is defined by the file itself: its path inside src/pages/ becomes the site address. This is called file-based routing.

A new page

Create the file src/pages/about.astro:

---
const author = 'Anna';
---
 
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>About me</title>
  </head>
  <body>
    <h1>About me</h1>
    <p>My name is {author}, I write about web development.</p>
  </body>
</html>

Open http://localhost:4321/about and the About page appears. No server restart is needed.

How files become addresses

FileAddress
src/pages/index.astro/
src/pages/about.astro/about
src/pages/posts/index.astro/posts
src/pages/posts/first-post.astro/posts/first-post
src/pages/404.astrothe "not found" page

An index file serves the address of its folder. Pages can be not only .astro but also .md and .mdx files, covered in a separate lesson.

There is no special link component: write an ordinary <a> tag. Add this to src/pages/index.astro:

<nav>
  <a href="/">Home</a>
  <a href="/posts">Posts</a>
  <a href="/about">About</a>
</nav>

Clicking a link loads the new page entirely, like on an ordinary site made of HTML files. Smooth transitions without a reload can be turned on later, in the lesson on view transitions.

A 404 page

Create src/pages/404.astro:

<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Page not found</title>
  </head>
  <body>
    <h1>Page not found</h1>
    <a href="/">Back to home</a>
  </body>
</html>

Open any address that does not exist, such as http://localhost:4321/nothing, and this page appears. The build turns it into a 404.html file, which hosting services show for unknown addresses.

What does not become a page

Files whose name starts with an underscore, such as src/pages/_draft.astro, are skipped. Keep components and layouts outside src/pages/, in src/components/ and src/layouts/, otherwise each of them gets its own address.

Common mistake

People put Header.astro into src/pages/ because "it is for pages". After that the component gets its own address that shows a bare piece of markup, and the build produces an extra HTML file. Only files that are separate pages belong in src/pages/.

Thanks for reading!

Donate to the site — we work hard for you.