Astro pages, layouts, components and content
This page covers everything between npm create astro and npm run build: how files become routes, how components and layouts compose a page, how Markdown and content collections turn files into typed data, and how pages fetch data. The running example is an invented OrdersPortal docs site with release notes, a status page and a support page.
All samples belong to one project whose layout is shown on the introduction. They were run with Astro 7.4.12 on Node.js 22.23.4 through astro dev, and the outputs below are the relevant part of the HTML the dev server returned, with Astro’s development-only data-astro-source-* attributes removed. The island sample also used @astrojs/preact 6.1.6.
Topics on this page
Section titled “Topics on this page”| Topic | Use it for |
|---|---|
| Pages and routing | Files in src/pages becoming URLs, including dynamic routes |
| Components | .astro components, props, slots, scoped styles and framework islands |
| Layouts | A shared page shell for .astro and Markdown pages |
| Markdown and MDX | Writing pages in Markdown, and components inside MDX |
| Content collections | Typed, validated groups of content with getCollection() |
| Data fetching | Reading files and APIs at build time or per request |
Pages and routing
Section titled “Pages and routing”Astro uses file-based routing. Each supported file in src/pages/ becomes a route named after its path: src/pages/index.astro is /, src/pages/status.astro is /status, and src/pages/support.md is /support. .astro, .md, .mdx and .html files become pages; .js and .ts files become endpoints that return data such as JSON or RSS. A 404.astro page builds to 404.html, which most hosts serve automatically. Files and folders whose names start with _ are excluded from routing.
Dynamic routes use brackets in the file name: src/pages/releases/[id].astro matches /releases/anything/, and [...slug].astro matches any depth. In a static build, a dynamic page must export getStaticPaths(), which returns every params combination to build, optionally with props for each page. Parameters are strings (Astro 6 stopped accepting numbers). With on-demand rendering, getStaticPaths() is not needed and parameters are read from Astro.params per request.
When two routes could match a URL, Astro picks the more specific one: static segments beat dynamic ones, and named parameters beat rest parameters.
---import BaseLayout from '../../layouts/BaseLayout.astro';import { getCollection, render } from 'astro:content';
export async function getStaticPaths() { const releases = await getCollection('releases'); return releases.map((release) => ({ params: { id: release.id }, props: { release }, }));}
const { release } = Astro.props;const { Content } = await render(release);---<BaseLayout title={`Version ${release.data.version}`}> <h1>OrdersPortal {release.data.version}</h1> <Content /></BaseLayout>Output for /releases/v2-0/:
<main><h1>OrdersPortal 2.0</h1><p>Orders are now paged by default. Pass <code>pageSize</code> to change the page length.</p></main>Pitfalls:
- Forgetting
getStaticPaths(). A dynamic page in a static build without it fails the build with an error naming the route. - Number parameters.
params: { id: 2 }is rejected since Astro 6; convert withString(id). - Helpers in
src/pages/. Autils.tsthere becomes an endpoint. Keep helpers insrc/lib/or prefix them with_.
Components
Section titled “Components”An .astro component has two parts. The component script between the --- fences runs on the server (at build time for static pages) and can import other components, read Astro.props, and await data. The template below it is HTML with JSX-like expressions: {value}, {cond && <p/>} and {items.map(...)}. Declaring an interface Props gives the props type checking in editors and astro check. <slot /> renders the children passed between the component’s tags, and named slots (<slot name="footer" />) take content marked slot="footer". A <style> tag is scoped to the component by default; is:global opts out.
Framework components (React, Preact, Svelte, Vue, Solid, Alpine) are added with their integration and render to HTML on the server like any other component. They become interactive islands only with a client directive: client:load hydrates immediately, client:idle when the browser is idle, client:visible when the component scrolls into view, client:media="(max-width: 50em)" when a media query matches, and client:only="preact" skips server rendering entirely.
---interface Props { version: string; date: Date;}const { version, date } = Astro.props;---<article class="release"> <h2>OrdersPortal {version}</h2> <time datetime={date.toISOString()}>{date.toDateString()}</time> <slot /></article>
<style> .release { border-left: 4px solid #4f46e5; padding-left: 1rem; }</style>An island, using a small Preact component on a feedback page:
---// src/pages/feedback.astro (FeedbackButton.jsx keeps a vote count in useState)import BaseLayout from '../layouts/BaseLayout.astro';import FeedbackButton from '../components/FeedbackButton.jsx';---<BaseLayout title="Feedback"> <FeedbackButton page="static" /> <FeedbackButton page="islands" client:visible /></BaseLayout>Output (inline loader scripts and long attributes trimmed): the first button is plain HTML; only the second is wrapped in an <astro-island> that loads its JavaScript when it becomes visible.
<main> <button type="button">Was static helpful? (0)</button> <astro-island uid="p03MM" component-export="default" ssr client="visible" ...> <button type="button">Was islands helpful? (0)</button> </astro-island></main>Pitfalls:
- A framework component that never responds to clicks. Without a
client:*directive it is static HTML. This is the most common Astro surprise. - Passing functions to islands. Props sent to hydrated components must be serializable; functions and class instances are not.
client:*on an.astrocomponent. Astro components have no client runtime; the directive is an error. Use a<script>tag inside the component instead.
Layouts
Section titled “Layouts”A layout is an ordinary Astro component that provides the page shell: <html>, <head> metadata, header, footer and a <slot /> for the page content. By convention layouts live in src/layouts/. Pages import a layout and wrap their content in it, passing props such as the title. Layouts can nest: a MarkdownLayout can itself use BaseLayout, so the outer shell is defined once.
Markdown files in src/pages/ can name a layout with the special layout frontmatter property; the layout then receives the file’s frontmatter as Astro.props.frontmatter. That property only works for Markdown pages; for content collections you render entries inside a regular page instead.
---interface Props { title: string;}const { title } = Astro.props;---<html lang="en"> <head> <meta charset="utf-8" /> <title>{title} | OrdersPortal</title> </head> <body> <header><a href="/">OrdersPortal docs</a></header> <main> <slot /> </main> </body></html>---// src/layouts/MarkdownLayout.astro: used from Markdown frontmatterimport BaseLayout from './BaseLayout.astro';const { frontmatter } = Astro.props;---<BaseLayout title={frontmatter.title}> <h1>{frontmatter.title}</h1> <slot /></BaseLayout>Every page in the sample renders inside <main> from BaseLayout, and its <title> ends with | OrdersPortal.
Pitfalls:
- Unclosed tags in layouts. Astro 7’s Rust compiler rejects unclosed non-void elements, which layouts with hand-written
<html>and<body>often had. - Duplicated
<head>content. Put meta tags, canonical URLs and analytics in one base layout; per-page values come in as props. - Using
layoutfrontmatter with collections. It is ignored there; render collection entries from a page that applies the layout.
Markdown and MDX
Section titled “Markdown and MDX”Astro renders .md files out of the box. In src/pages/ a Markdown file is a page; elsewhere, Markdown is usually loaded through a content collection. Frontmatter (YAML between ---) carries metadata; headings get id attributes automatically; GitHub-flavored Markdown (tables, autolinks, task lists) and SmartyPants typography are on by default. Since Astro 7, Markdown and MDX are processed by Sätteri, a native pipeline; remark and rehype plugins require installing @astrojs/markdown-remark and selecting the unified() processor.
MDX (npx astro add mdx) lets you import and use components inside Markdown and write JavaScript expressions. Use it when a page needs a tab set, a chart or an interactive island; stay with plain Markdown otherwise, because it is simpler for writers and faster to process.
---layout: ../layouts/MarkdownLayout.astrotitle: Getting support---Email **support@example.test** with your order number.Output for /support (the email address was autolinked by GitHub-flavored Markdown):
<main><h1>Getting support</h1><p>Email <strong><a href="mailto:support@example.test">support@example.test</a></strong> with your order number.</p></main>Pitfalls:
- Expressions in
.md.{frontmatter.title}is literal text in a.mdfile; expressions and imports need.mdx. - Plugins silently skipped after upgrading. remark and rehype plugins configured in
markdown.remarkPluginsdo nothing in Astro 7 unless@astrojs/markdown-remarkis installed. - Raw HTML from untrusted Markdown. Markdown allows HTML; content from outside your team should be sanitized before rendering.
Content collections
Section titled “Content collections”A content collection is a named, typed set of entries such as blog posts, release notes or authors. Build-time collections are defined in src/content.config.ts with defineCollection(). Each one needs a loader: glob() reads a folder of Markdown, MDX, Markdoc, JSON, YAML or TOML files, file() reads one data file, and custom or third-party loaders pull from a CMS or API. An optional but recommended schema, written with Zod imported from astro/zod, validates frontmatter and gives you inferred TypeScript types; z.coerce.date() turns frontmatter dates into Date objects.
Query with getCollection('releases') (optionally with a filter function) or getEntry('releases', 'v2-0'), and render Markdown bodies with render(entry), which returns a <Content /> component and the headings. Entry ids are generated from file names in a URL-friendly form. Astro 6 and later also have live collections (getLiveCollection()) that fetch at request time on on-demand pages.
import { defineCollection } from 'astro:content';import { glob } from 'astro/loaders';import { z } from 'astro/zod';
const releases = defineCollection({ loader: glob({ base: './src/content/releases', pattern: '**/*.md' }), schema: z.object({ version: z.string(), date: z.coerce.date(), breaking: z.boolean().default(false), }),});
export const collections = { releases };---// src/pages/index.astro (src/content/releases/ holds v2-0.md and v2-1.md)import BaseLayout from '../layouts/BaseLayout.astro';import ReleaseCard from '../components/ReleaseCard.astro';import { getCollection } from 'astro:content';
const releases = (await getCollection('releases')) .sort((a, b) => b.data.date.getTime() - a.data.date.getTime());---<BaseLayout title="Release notes"> <h1>Release notes</h1> {releases.map((release) => ( <ReleaseCard version={release.data.version} date={release.data.date}> {release.data.breaking && <strong>Breaking change</strong>} <a href={`/releases/${release.id}/`}>Read the notes</a> </ReleaseCard> ))}</BaseLayout>Output for / (scoping attributes removed):
<main><h1>Release notes</h1><article class="release"><h2>OrdersPortal 2.1</h2><time datetime="2026-11-02T00:00:00.000Z">Mon Nov 02 2026</time><a href="/releases/v2-1/">Read the notes</a></article><article class="release"><h2>OrdersPortal 2.0</h2><time datetime="2026-10-01T00:00:00.000Z">Thu Oct 01 2026</time><strong>Breaking change</strong><a href="/releases/v2-0/">Read the notes</a></article></main>Pitfalls:
- The legacy API.
src/content/config.tswithout aloaderand the@astrojs/contentpackage are not part of current Astro; collections need a loader insrc/content.config.tssince Astro 6 removed the legacy API. zfromastro:content. It is deprecated since Astro 6; import Zod fromastro/zod.- Unsorted results.
getCollection()makes no ordering promise. Sort explicitly, as the sample does by date.
Data fetching
Section titled “Data fetching”Any .astro component can await in its script. On a static page the code runs once, at build time, and the result is baked into the HTML; on an on-demand page it runs per request. Use the global fetch() for APIs, import JSON or other modules directly, or read through a content collection loader when the data has a schema and many pages use it. Framework components can still fetch in the browser after hydration, for data that must be live on a static page.
Secrets used in a component script stay on the server; read them from astro:env or import.meta.env without the PUBLIC_ prefix so they are never sent to the client.
---import BaseLayout from '../layouts/BaseLayout.astro';import status from '../data/status.json';// Remote data works the same way with top-level await:// const status = await fetch('https://api.example.test/status').then((r) => r.json());const builtAt = new Date().toISOString();---<BaseLayout title="Status"> <h1>{status.service}: {status.healthy ? 'healthy' : 'degraded'}</h1> <p>Open incidents: {status.openIncidents}. Page built at {builtAt}.</p></BaseLayout>Output (with src/data/status.json containing { "service": "orders-api", "healthy": true, "openIncidents": 0 }; the timestamp is when the page rendered):
<main><h1>orders-api: healthy</h1><p>Open incidents: 0. Page built at 2026-11-18T10:29:37.763Z.</p></main>In a static build, that timestamp is the build time, which makes the trade-off visible: the status page is only as fresh as the last deployment.
Pitfalls:
- Stale “live” data. A static page that fetches prices or stock levels shows build-time values until the next build. Use on-demand rendering for that route (
export const prerender = falsewith an adapter), a server island, or a client-side fetch. - Failing builds on API errors. A build-time fetch that throws fails the whole build. Decide whether to fail loudly or fall back, and set a timeout.
- Leaking secrets into islands. Passing an API key as a prop to a hydrated component serializes it into the HTML. Keep the call in the component script or an endpoint.
Choosing between them
Section titled “Choosing between them”- Static pages with
getStaticPaths()for anything known at build time; on-demand rendering only for routes that need per-request data. .astrocomponents for structure and content; a framework island only where the user interacts, with the latestclient:*directive that works.- Markdown in a content collection for repeated content types (posts, releases); a Markdown page in
src/pages/for one-off pages; MDX only where components are needed.
Interview questions
Section titled “Interview questions”What does getStaticPaths() return, and when is it required?
An array of objects with params (and optionally props) for every page a dynamic route should produce. It is required for dynamic routes that are prerendered, which is the default; on-demand routes read Astro.params per request instead.
What is the difference between client:load and client:visible?
Both hydrate a framework component in the browser. client:load loads and hydrates it as soon as the page loads; client:visible waits until the component enters the viewport, using an IntersectionObserver, so below-the-fold widgets do not compete with the initial render.
Why use a content collection instead of importing Markdown files directly?
Collections validate frontmatter against a schema at build time, generate TypeScript types, give a consistent query API and ids, and can be backed by loaders for remote data. Direct imports give you none of that and fail only at runtime when a field is missing.
Where does code in an .astro component’s frontmatter run?
Only on the server: at build time for prerendered pages or per request for on-demand pages. It never runs in the browser, which is why it can use secrets and file system access.
Senior scenario: the OrdersPortal docs build takes 12 minutes because 3,000 release-note pages each fetch the same API. How do you fix it?
Move the API call into a content loader (or one cached fetch in a shared module) so data is fetched once and stored in the content layer, then have getStaticPaths() read from the collection. Check that pages do not call getCollection() with expensive filters in a loop, and that images use astro:assets with a cache so unchanged images are not reprocessed. If some data must be fresh, render only those routes on demand or with server islands instead of rebuilding everything, and use route caching for the on-demand routes.
Related pages
Section titled “Related pages”- Astro introduction, setup and project structure
- Astro integrations, build and deploy
- Static site generators compared