JAVASCRIPT
Cache API Responses in Browser's localStorage
Optimize web application performance by caching API responses in the browser's localStorage, reducing redundant network requests and improving page load times.
async function fetchAndCache(url, options = {}, cacheDurationMinutes = 5) {
const cacheKey = `api_cache_${url}`;
const cachedData = localStorage.getItem(cacheKey);
const now = new Date().getTime();
if (cachedData) {
const { data, timestamp } = JSON.parse(cachedData);
if (now - timestamp < cacheDurationMinutes * 60 * 1000) {
console.log('Returning cached data for:', url);
return data;
} else {
console.log('Cache expired for:', url);
localStorage.removeItem(cacheKey);
}
}
console.log('Fetching fresh data for:', url);
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const freshData = await response.json();
localStorage.setItem(cacheKey, JSON.stringify({ data: freshData, timestamp: now }));
return freshData;
} catch (error) {
console.error('Error fetching or caching data:', error);
throw error;
}
}
// Usage example:
// fetchAndCache('https://api.example.com/products', {}, 10) // Cache for 10 minutes
// .then(products => console.log('Products:', products))
// .catch(error => console.error('Failed to get products:', error));
// fetchAndCache('https://api.example.com/users', { method: 'GET' }, 1) // Cache for 1 minute
// .then(users => console.log('Users:', users))
// .catch(error => console.error('Failed to get users:', error));
How it works: This snippet demonstrates how to implement client-side caching for API responses using `localStorage`. The `fetchAndCache` function first checks if a response for the given URL exists in `localStorage` and if it's still within its `cacheDurationMinutes`. If valid cached data is found, it's returned immediately. Otherwise, a fresh request is made to the API, and the new data, along with a timestamp, is stored in `localStorage` for future use. This strategy reduces network requests, improves perceived performance, and decreases server load.