0
0
Astroframework~5 mins

Why data fetching happens at build time in Astro

Choose your learning style9 modes available
Introduction

Data fetching at build time helps create fast websites by getting all needed data before users visit. This means pages load quickly without waiting for data to arrive.

When you want your website to load instantly with pre-filled content.
When your data changes rarely and can be updated during site builds.
When you want to reduce server load by avoiding data requests on every visit.
When you want better SEO because search engines see full content immediately.
When you want to avoid delays caused by slow or unreliable data sources.
Syntax
Astro
export async function getStaticPaths() {
  // fetch data here
  return {
    paths: [{ params: { /* path params */ } }],
    fallback: false
  };
}

getStaticPaths defines which dynamic pages to build ahead of time and can provide fetched data via props.

For non-dynamic pages, fetch data directly in the frontmatter (between --- blocks).

Examples
Fetch data once at build time in the page frontmatter (between --- delimiters) and use it in the template.
Astro
---
const res = await fetch('https://api.example.com/data');
const data = await res.json();
---
Generate static pages for each item by fetching all item IDs at build time. Fetch per-item data in the page or via props in paths.
Astro
export async function getStaticPaths() {
  const res = await fetch('https://api.example.com/items');
  const items = await res.json();
  const paths = items.map(item => ({ params: { id: item.id.toString() } }));
  return { paths, fallback: false };
}
Sample Program

This Astro page fetches a post at build time in the frontmatter and renders its title and body. The data is embedded, so users see content immediately with no loading delay.

Astro
---
const res = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const post = await res.json();
---

<article>
  <h1>{post.title}</h1>
  <p>{post.body}</p>
</article>
OutputSuccess
Important Notes

Fetching data at build time means the site needs to be rebuilt to update content.

Good for blogs, documentation, or product pages that don't change often.

Not ideal for real-time or user-specific data that changes frequently.

Summary

Data fetching at build time makes pages load faster by preloading content.

It improves SEO because content is ready for search engines.

Best for mostly static content that updates occasionally.