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.
Why data fetching happens at build time in 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).
--- delimiters) and use it in the template.--- const res = await fetch('https://api.example.com/data'); const data = await res.json(); ---
props in paths.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 }; }
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.
--- 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>
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.
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.