Pages

Pages are a special type of Astro component that live in the src/pages/ subdirectory. They are responsible for handling routing, data loading, and overall page layout for every HTML page in your website.

Astro leverages a routing strategy called file-based routing. Every .astro file in your src/pages directory becomes a page on your site, creating a URL route based on the file path inside of the directory.

📚 Read more about Routing in Astro

Astro Pages must return a full <html>…</html> page response, including <head> and <body>. (<!doctype html> is optional, and will be added automatically.)

---
// Example: src/pages/index.astro
---
<html>
  <head>
    <title>My Homepage</title>
  </head>
  <body>
    <h1>Welcome to my website!</h1>
  </body>
</html>

To avoid repeating the same HTML elements on every page, you can move common <head> and <body> elements into your own layout components. You can use as many or as few layout components as you’d like.

---
// Example: src/pages/index.astro
import MySiteLayout from '../layouts/MySiteLayout.astro';
---
<MySiteLayout>
  <p>My page content, wrapped in a layout!</p>
</MySiteLayout>

📚 Read more about layout components in Astro.

Astro also treats any Markdown (.md) files inside of /src/pages/ as pages in your final website. These are commonly used for text-heavy pages like blog posts and documentation.

Page layouts are especially useful for Markdown files. Markdown files can use the special layout front matter property to specify a layout component that will wrap their Markdown content in a full <html>…</html> page document.

---
# Example: src/pages/page.md
layout: '../layouts/MySiteLayout.astro'
title: 'My Markdown page'
---
# Title

This is my page, written in **Markdown.**

📚 Read more about Markdown in Astro.

Non-HTML pages, like .json or .xml, or even non-text assets like images can be built using File Routes.

File Routes must end with the .js or .ts extension and the source file must exist within the src/pages/ directory.

Built filenames and extensions are based on the source file’s name, ex: src/pages/data.json.ts will be built to match the /data.json route in your final build.

// Example: src/pages/builtwith.json.ts
// Outputs: /builtwith.json

// File routes export a get() function, which gets called to generate the file.
// Return an object with `body` to save the file contents in your final build.
export async function get() {
  return {
    body: JSON.stringify({
      name: 'Astro',
      url: 'https://astro.build/',
    }),
  };
}

For a custom 404 error page, you can create a 404.astro file in /src/pages.

This will build to a 404.html page. Most deploy services will find and use it.