Fetching data from the network in Astro
By Flavio
Published · Updated
Tagged: Astro
How to fetch data from an API in Astro with fetch() and top-level await: when the request runs (build time or request time), handling errors, creating one page per item with getStaticPaths, and keeping API keys secret.
One thing I really like about Astro is the frontmatter.
We can put any JavaScript in there, and one of the most useful things we can do is to fetch data at build time.
We do so using fetch(), the Fetch API.
The nice thing about Astro is that it makes it possible to use top-level await in the frontmatter, so we don’t have to do anything fancy like an IIFE or calling an async function in order to use fetch(), which is a promise-based API.
In other words, you can use await directly:
---
const res = await fetch('https://jsonplaceholder.typicode.com/users')
const users = await res.json()
---
<ul>
{users.map((user) => (
<li>{user.name}</li>
))}
</ul>
fetch() is available globally, you don’t need to import anything. Always use a full URL, with https:// and the domain.
When does the request run?
It depends on how the page is rendered.
Prerendered pages (the default). By default Astro prerenders your whole site. The request runs at build time, so it’s done just once when the site is deployed. The HTML that visitors get already contains the data, and the API is never called from their browser.
And of course it runs again when the site is deployed again.
So any time we make a change in the API, if you want the site to show the new data, you have to trigger a rebuild which is something all platforms offer via webhooks.
On-demand rendered pages. If you need fresh data on every visit, render the page on demand. You need an adapter for your host first, for example:
npx astro add netlify
Astro has official adapters for Cloudflare, Netlify, Node and Vercel. Then add this line to the page frontmatter:
---
export const prerender = false
const res = await fetch('https://jsonplaceholder.typicode.com/users')
const users = await res.json()
---
Now the fetch runs on the server every time someone requests the page.
If most of your pages need this, set output: 'server' in astro.config.mjs and opt single pages back into static with export const prerender = true.
In development. With npm run dev the fetch runs again every time the page reloads, so you see API changes right away, even on pages that will be static in production.
Handle errors
fetch() doesn’t throw when the server answers with a 404 or a 500. It only throws when the request fails completely, like when the domain doesn’t resolve. So check res.ok before you read the body:
---
const res = await fetch('https://jsonplaceholder.typicode.com/users')
if (!res.ok) {
throw new Error(`Failed to load users: ${res.status}`)
}
const users = await res.json()
---
On a prerendered page an error thrown here stops the build. I tested it by pointing the URL to a path that returns 404: astro build printed Failed to load users: 404 and exited with code 1, so nothing broken got deployed.
That’s usually what you want. If the data is optional, catch the error and render a fallback instead:
---
let users = []
try {
const res = await fetch('https://jsonplaceholder.typicode.com/users')
if (res.ok) users = await res.json()
} catch (error) {
console.error(error)
}
---
{users.length === 0 ? <p>No users right now</p> : (
<ul>{users.map((user) => <li>{user.name}</li>)}</ul>
)}
One page for each item with getStaticPaths
A common need is to fetch a list and create a page for each element. Do it in a dynamic route like src/pages/users/[id].astro, with getStaticPaths():
---
export async function getStaticPaths() {
const res = await fetch('https://jsonplaceholder.typicode.com/users')
const users = await res.json()
return users.map((user) => ({
params: { id: String(user.id) },
props: { user },
}))
}
const { user } = Astro.props
---
<h1>{user.name}</h1>
<p>{user.email}</p>
At build time this generated 10 pages, from /users/1/ to /users/10/, one for each user returned by the API.
A few things to know:
getStaticPaths()runs once, before the pages are built, in its own scope. You can’t use variables defined outside it, apart from imports.- Pass the data you already fetched as
props, so you don’t need to call the API again for each page. paramsvalues must match the file name:[id].astroneeds anidparam. I convert the number to a string withString().
Keep API keys secret
Most real APIs need a key. Put it in a .env file at the root of the project:
API_KEY=your-key-here
and read it in the frontmatter:
---
const res = await fetch('https://api.example.com/items', {
headers: { Authorization: `Bearer ${import.meta.env.API_KEY}` },
})
---
The frontmatter only runs on the server (or at build time), so the key never reaches the browser. Astro only exposes to client-side code the variables whose name starts with PUBLIC_, so never give a secret that prefix.
Add .env to .gitignore, and set the same variable in your hosting dashboard so the build there can read it.
For type-checked variables, Astro also has astro:env: you declare each variable in astro.config.mjs and import it with import { API_KEY } from 'astro:env/server'.
Fetching in the browser
Everything above runs before the HTML is sent. If you need to fetch data again after the page loads, for example to refresh it every few seconds or after a click, do it in a <script> tag in your Astro component, or in a framework component (React, Svelte, Vue…) loaded with a client:* directive.
Want me to talk about your product? You can sponsor this site.
Related posts about astro: