Prompt
How do I cache API responses in a web app?
Latest observation
Caching API responses in a web app usually means storing previously fetched data so you can reuse it instead of calling the server every time. This can improve speed, reduce bandwidth, and lower load on your backend.
Common places to cache
1. Browser/client-side cache
Good for:
- Repeated reads
- Improving perceived performance
- Offline support
Options:
- HTTP caching headers set by your API
- In-memory cache in your app
- localStorage / sessionStorage for small, simple data
- IndexedDB for larger or structured data
- Service Worker Cache API for offline/network control
2. Server-side cache
Good for:
- Reusing expensive API responses
- Protecting databases
- Shared cache across users
Options:
- Redis
- Memcached
- App-level in-memory cache
- CDN edge caching for public GET endpoints
Best practice: use HTTP caching first
If your API is under your control, configure cache headers so browsers and CDNs can cache responses.
Example headers:
Cache-Control: public, max-age=60, stale-while-revalidate=300
ETag: "abc123"
Last-Modified: Tue, 14 Oct 2025 12:00:00 GMT
What they do
Cache-Control: max-age=60→ cache for 60 secondsstale-while-revalidate=300→ serve stale data while fetching fresh data in backgroundETag/Last-Modified→ enable conditional requests so the server can reply304 Not Modified
Simple client-side cache example
In-memory cache
const cache = new Map();
async function fetchWithCache(url) {
if (cache.has(url)) {
return cache.get(url);
}
const response = await fetch(url);
const data = await response.json();
cache.set(url, data);
return data;
}
This is fast, but the cache disappears when the page reloads.
Cache with expiration
const cache = new Map();
const TTL = 60 * 1000; // 60 seconds
async function fetchWithCache(url) {
const cached = cache.get(url);
if (cached && Date.now() < cached.expiresAt) {
return cached.data;
}
const response = await fetch(url);
const data = await response.json();
cache.set(url, {
data,
expiresAt: Date.now() + TTL
});
return data;
}
Use localStorage for small persisted cache
async function fetchWithLocalStorageCache(url) {
const key = `cache:${url}`;
const cached = JSON.parse(localStorage.getItem(key) || "null");
if (cached && Date.now() < cached.expiresAt) {
return cached.data;
}
const response = await fetch(url);
const data = await response.json();
localStorage.setItem(key, JSON.stringify({
data,
expiresAt: Date.now() + 60 * 1000
}));
return data;
}
Note: localStorage is synchronous and not ideal for large data or frequent access.
Use a data-fetching library
In modern web apps, libraries like:
- React Query
- SWR
- RTK Query
handle caching, deduping, revalidation, retries, and stale data automatically.
Example with SWR:
import useSWR from 'swr';
const fetcher = (url) => fetch(url).then(res => res.json());
function Profile() {
const { data, error, isLoading } = useSWR('/api/profile', fetcher, {
revalidateOnFocus: true,
dedupingInterval: 5000
});
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error</div>;
return <div>{data.name}</div>;
}
Important caching rules
Don’t cache everything
Avoid caching:
- User-specific sensitive data unless properly scoped
- Frequently changing data without invalidation
- POST/PUT/DELETE responses unless you know what you’re doing
Use cache keys carefully
Include things like:
- URL
- Query parameters
- User ID or auth context if data is user-specific
- Locale or feature flags if relevant
Invalidate when data changes
If the user updates data, clear or refresh related cache entries.
A good strategy
- Set proper HTTP cache headers on API responses
- Use a client-side caching library in the frontend
- Add server-side cache for expensive endpoints
- Define invalidation rules carefully
If you want, I can also show:
- how to do this in React
- how to implement Redis caching on the backend
- how to use ETag/304 responses for efficient caching