Performance: Caching API responses
Caching API responses improves page load speed by reducing network requests and speeds up rendering by serving stored data quickly.
import { cache } from 'astro:cache'; const data = await cache(async () => { const response = await fetch('https://api.example.com/data'); return await response.json(); }, { ttl: 3600 }); return data;
const response = await fetch('https://api.example.com/data'); const data = await response.json(); return data;
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No caching, fetch on every load | Minimal | 1 per data update | Moderate due to delayed content | [X] Bad |
| Caching API responses with TTL | Minimal | 1 on cache miss | Low due to instant data | [OK] Good |
revalidate.{ revalidate: 60 } inside fetch().const data = await fetch('https://api.example.com/data', { revalidate: 120 }).then(res => res.json());revalidate: 120 means cache lasts 120 seconds (2 minutes).const data = await fetch('https://api.example.com/data').json();revalidate and why?revalidate: 3600 to update every hourrevalidate: 60 to update every minuterevalidate: 0 to never cacherevalidate: -1 to disable cachingPass the test and this pattern moves unknown