To fetch data in Astro at build time, call fetch() with top-level await in a page’s frontmatter. On a static site, that code runs once during astro build and the response is baked into the HTML. Use getStaticPaths() to create one page per item, and move repeated or large fetches into a content loader so the data is fetched once, validated and shared by every page.
Key Takeaways
- Frontmatter runs at build time on prerendered pages, so
await fetch()there costs visitors nothing.getStaticPaths()turns an API list into static pages.- Content loaders fetch once per build, validate with a schema and keep data between dev reloads.
- Throw on a failed request, so an API outage fails the build instead of publishing empty pages.
Pattern 1: fetch in frontmatter
---
// src/pages/releases.astro
const res = await fetch('https://api.github.com/repos/withastro/astro/releases?per_page=5', {
headers: { Accept: 'application/vnd.github+json' },
});
if (!res.ok) throw new Error(`GitHub API returned ${res.status}`);
const releases: { name: string; html_url: string; published_at: string }[] = await res.json();
---
<ul>
{releases.map((r) => (
<li><a href={r.html_url}>{r.name}</a> ({new Date(r.published_at).toLocaleDateString('en-US')})</li>
))}
</ul>
fetch is global in Astro, no import needed. Components can fetch too, but each instance fetches separately, so put shared requests in the page or a module. Throwing on !res.ok matters: without it, a 500 from the API produces a page with an empty list that looks fine in CI.
Pattern 2: one page per item with getStaticPaths
---
// src/pages/products/[slug].astro
export async function getStaticPaths() {
const res = await fetch('https://api.example.com/products');
if (!res.ok) throw new Error(`Products API returned ${res.status}`);
const products: { slug: string; name: string; summary: string }[] = await res.json();
return products.map((product) => ({ params: { slug: product.slug }, props: { product } }));
}
const { product } = Astro.props;
---
<h1>{product.name}</h1>
<p>{product.summary}</p>
getStaticPaths() runs once per route during the build. Passing each item as props avoids a second request per page. The getStaticPaths guide covers pagination and params.
Pattern 3: a content loader
When several pages use the same data, or you want validation and getCollection(), define a loader:
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { z } from 'astro/zod';
const products = defineCollection({
loader: async () => {
const res = await fetch('https://api.example.com/products');
if (!res.ok) throw new Error(`Products API returned ${res.status}`);
const items: { slug: string }[] = await res.json();
return items.map((item) => ({ id: item.slug, ...item }));
},
schema: z.object({
name: z.string(),
summary: z.string(),
price: z.number(),
}),
});
export const collections = { products };
The inline loader returns an array of objects with an id. Astro fetches once per build (and on dev server start), validates each item and stores the results, so getCollection('products') in ten pages makes one request, not ten. For incremental updates, a full Loader object can use the meta store to save an ETag or last-sync time. Our content loaders guide shows that pattern.
Secrets, rate limits and rebuilds
- API keys: read them from server-only env vars declared with
astro:env. Build-time code never reaches the browser unless you print the value into the page. See the environment variables guide. - Rate limits: a site with 2,000 product pages using Pattern 2 still makes one request; a component fetching per card would make thousands. Fetch high, pass data down.
- Large responses: page through the API inside the loader rather than requesting everything in one call.
- Fresh data: build-time data is only as new as the last build. Trigger rebuilds from a webhook or a scheduled CI job, or render specific pages on demand with an adapter if they must be live. The live collections guide covers request-time data.
The Content Collections docs page explains how loaders fit into collections. Static output is what every Komal theme builds to, so these patterns work with any of them without an adapter.
FAQ
Does fetch in Astro frontmatter run on every request?
Only on pages rendered on demand. On prerendered pages, the default, frontmatter runs once during astro build, and visitors get static HTML with the data already in it.
How do I fetch data once and use it on many Astro pages?
Use a content loader in src/content.config.ts. It fetches once per build, validates the data and makes it available to every page through getCollection() and getEntry().
What happens if the API is down during the build?
If you throw on a failed response, the build fails and your previous deployment stays live. If you don’t check res.ok, the build may succeed with empty or broken pages, so always handle the error.