Performance: Fetching APIs in frontmatter
This affects the page load speed by determining when and how data is fetched before rendering the page.
---
const dataPromise = fetch('https://api.example.com/data').then(res => res.json());
---
<html>
<body>
<Suspense fallback={<p>Loading data...</p>}>
<AsyncData dataPromise={dataPromise} />
</Suspense>
</body>
</html>--- const response = await fetch('https://api.example.com/data'); const data = await response.json(); --- <html> <body> <pre>{JSON.stringify(data)}</pre> </body> </html>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Blocking API fetch in frontmatter | Minimal DOM nodes initially | 0 during fetch, but blocks rendering | Paint delayed until data arrives | [X] Bad |
| Deferred API fetch with Suspense | DOM nodes for shell render immediately | 0 during initial render | Paint happens early, data painted later | [OK] Good |
data.message in the component?
---
const response = await fetch('https://api.example.com/greet');
const data = await response.json();
---
{data.message}
Assuming the API returns JSON: { "message": "Hello, Astro!" }---
const data = fetch('https://api.example.com/data');
const json = data.json();
------
// Option A
const res = await fetch('https://api.example.com/users');
const users = await res.json();
---
Pass the test and this pattern moves unknown