Pages and routing

Write an Astro page

Combine a server-side component script with the HTML template it renders.

An Astro page is a component under src/pages/ that answers a route with a complete HTML document. Like every Astro component, it has two parts: a component script and a template.

---
import SiteHeader from '../components/SiteHeader.astro'

const title = 'About'
---

<html lang="en">
  <head>
    <title>{title}</title>
  </head>
  <body>
    <SiteHeader />
    <main>
      <h1>{title}</h1>
    </main>
  </body>
</html>

The fenced script between the two --- markers runs while Astro renders. It can import components, read props, load data, and calculate values. Astro removes this script from the HTML response, so nothing you write there reaches the visitor’s browser. That makes it the right place for work you would never ship to a client, like reading files or preparing data.

The template below the fence describes the output. Expressions such as {title} are evaluated during rendering, and the resulting HTML is what gets sent.

What separates a page from an ordinary component is responsibility for the document. This file emits <html>, <head>, and <body> itself. A button component only produces its own fragment; a page owns the whole response for its URL. Once several pages repeat that shell, you extract it into a layout, which a later lesson covers.

The title is dynamic at build or request time, but it is not reactive in the browser. Changing a browser variable later will not rerender this Astro component. This trips up people arriving from React or Vue: the component script is not a live client runtime, it runs once per render on the server side.

If the page needs browser behavior, use a normal <script> tag or a hydrated framework component. Keep server-only work in the component script.

View the page source and search for SiteHeader, const title, and the final heading. The import and the variable are gone. Only the rendered HTML should remain, with the header component already expanded into its markup.

Lesson completed

Take this course offline

Get every free book, course edition, and software download.

Get the download library →