How to Fetch API Data in Astro: Simple Guide with Examples
In Astro, you fetch API data on the server side using the
fetch function inside your page or component scripts. You can also fetch data on the client side using standard JavaScript fetch inside client components or scripts.Syntax
Astro uses the standard fetch API to get data from external sources. You typically fetch data inside the Astro component script or in server-side code. The basic syntax is:
const response = await fetch(url);- fetches data from the URL.const data = await response.json();- parses the response as JSON.
This runs on the server during build or request time, so the data is ready when the page renders.
javascript
const response = await fetch('https://api.example.com/data'); const data = await response.json();
Example
This example shows how to fetch data from a public API in an Astro page and display it. The fetch runs on the server, so the data is available when the page loads.
astro
--- const response = await fetch('https://api.agify.io?name=michael'); const data = await response.json(); --- <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Astro Fetch Example</title> </head> <body> <h1>Age Prediction for Name</h1> <p>Name: <strong>{data.name}</strong></p> <p>Predicted Age: <strong>{data.age}</strong></p> </body> </html>
Output
<h1>Age Prediction for Name</h1>
<p>Name: <strong>michael</strong></p>
<p>Predicted Age: <strong>69</strong></p>
Common Pitfalls
Common mistakes when fetching API data in Astro include:
- Trying to use
fetchdirectly inside the component's HTML without the frontmatter script block. - Not awaiting the
fetchcall, causing unresolved promises. - Fetching data on the client side without using client directives, which can cause hydration issues.
- Not handling errors from
fetch, which can break the build or page.
Always fetch data inside the frontmatter script and handle errors gracefully.
astro
--- // Wrong: fetch inside HTML (won't work) // <p>{await fetch('https://api.example.com').then(res => res.json())}</p> --- --- // Right: fetch inside frontmatter const response = await fetch('https://api.example.com'); const data = await response.json(); ---
Quick Reference
Tips for fetching API data in Astro:
- Use
await fetch()inside the frontmatter script for server-side data fetching. - Use client directives like
client:loadfor client-side fetching in components. - Always handle errors with
try/catchor check response status. - Remember Astro renders pages on the server by default, so data is fetched before sending HTML.
Key Takeaways
Fetch API data inside Astro frontmatter using await fetch for server-side rendering.
Use client directives for client-side fetching when needed.
Always await fetch and parse response with response.json().
Handle errors to avoid build or runtime failures.
Astro fetch runs on the server by default, so data is ready at page load.