Data Fetching
Guidelines for fetching remote data in Astro projects.
astro
## Astro Data Fetching Guidelines
1. Primary Method: Use the standard global `fetch()` API within the component script (`---` fences) of `.astro` files.
- Top-level `await` is supported and recommended for cleaner code.
```astro
---
const response = await fetch('https://api.example.com/data');
const data = await response.json();
---
<div>{data.message}</div>
```
2. Timing of Fetch:
- Static Site Generation (SSG - Default): `fetch()` calls run at build time. The fetched data is used to generate static HTML. Data is fetched only once during the build process.
- Server-Side Rendering (SSR / On-Demand): `fetch()` calls run at request time (runtime) whenever the page or component is requested.
3. Fetching in UI Framework Components:
- The global `fetch()` is also available within UI framework components (.jsx, .tsx, .svelte, .vue, etc.).
- If the component is server-rendered (or pre-rendered during build), the fetch behaves similarly to `.astro` files (build time for static, request time for SSR).
- If the component is client-rendered (`client:*` directive), fetching might occur both on the server (if pre-rendered) and again on the client during hydration, or solely on the client depending on the setup. Be mindful of where and when the fetch executes.
4. Using Fetched Data:
- Render the data directly within the Astro component's template (`{data.property}`).
- Pass the data as props to child components (both `.astro` and UI framework components).
5. GraphQL:
- Use `fetch()` with `method: 'POST'`, `headers: { 'Content-Type': 'application/json' }`, and a `body` containing the JSON-stringified GraphQL query and variables.
6. CMS / API Integration:
- Fetch data from headless CMSs or APIs within component scripts.
- Often used in conjunction with dynamic routes (`src/pages/[slug].astro`) to generate pages based on fetched content.
7. Client-Side Fetching:
- For data that needs to be fetched or re-fetched _after_ the initial page load (client-side), use standard JavaScript `fetch()` within a `<script>` tag in an `.astro` component or within the logic of a client-rendered UI framework component.
Reference: [Astro Data Fetching Docs](mdc:https:/docs.astro.build/en/guides/data-fetching)