Performance: Why data fetching happens at build time
This affects the page load speed by preloading data before the user requests the page, reducing runtime delays.
--- // Fetches data once at build time (static by default) const res = await fetch('https://api.example.com/data'); const data = await res.json(); --- <html> <body> <div>{data.title}</div> </body> </html>
--- // Fetches data on every request in SSR mode const res = await fetch('https://api.example.com/data'); const data = await res.json(); --- <html> <body> <div>Loading...</div> </body> </html> // Note: Configure output: 'server' in astro.config.mjs for SSR
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Runtime data fetching (SSR) | Same DOM nodes | Multiple reflows possible due to loading states | Higher paint cost due to delayed content | [X] Bad |
| Build time data fetching (Static) | Same DOM nodes | Single reflow with full content | Lower paint cost with immediate content | [OK] Good |
getStaticPaths() to fetch data at build time for generating pages.getStaticProps() is from Next.js, not Astro; fetch() inside render runs at runtime, not build time.export async function getStaticPaths() to fetch data -> Option Dexport async function getStaticPaths() {
return [{ params: { id: '1' } }, { params: { id: '2' } }];
}
const data = { '1': 'Apple', '2': 'Banana' };
export default function Page({ params }) {
return {data[params.id]}
;
}export async function getStaticPaths() {
const response = await fetch('https://api.example.com/items');
const items = await response.json();
return items.map(item => ({ params: { id: item.id } }));
}
export default function Page({ params }) {
return {params.id}
;
}{ paths: [...] }, so returning only the array causes an error.Pass the test and this pattern moves unknown