Caching API responses helps your website load faster by saving data from previous requests. This means users don't have to wait for the same information to be fetched again.
Caching API responses in Astro
export const revalidate = 3600; export default async function Page() { const response = await fetch('https://api.example.com/data'); const data = await response.json(); return ( <div>{/* use {data} here */}</div> ); }
revalidate tells Astro how many seconds to keep the cached data before fetching fresh data.
This example uses an async page component to fetch data at prerender time and cache it.
export const revalidate = 600; // cache for 10 minutes export default async function Page() { const response = await fetch('https://api.example.com/users'); const users = await response.json(); return ( <div>{/* use {users} here */}</div> ); }
export const revalidate = 86400; // cache for 24 hours export default async function Page() { const response = await fetch('https://api.example.com/posts'); const posts = await response.json(); return ( <div>{/* use {posts} here */}</div> ); }
export const revalidate = 300; // cache for 5 minutes export default async function Page() { const response = await fetch('https://api.example.com/weather'); const weather = await response.json(); return ( <div>{/* use {weather} here */}</div> ); }
This Astro component fetches product data from an API and caches it for 30 minutes. When users visit the page, they see the product list quickly without waiting for a fresh API call every time.
export const revalidate = 1800; // cache for 30 minutes export default async function ProductsPage() { const response = await fetch('https://api.example.com/products'); const products = await response.json(); return ( <main> <h1>Product List</h1> <ul> {products.map(product => ( <li key={product.id}>{product.name} - ${product.price}</li> ))} </ul> </main> ); }
Use caching to balance fresh data and fast loading times.
Set revalidate time based on how often your data changes.
Cached data is stored on the server, so users get faster responses.
Caching API responses speeds up your site by saving data from previous requests.
Use export const revalidate in your page component to control cache duration.
Choose cache time based on how often your data updates.