JAVASCRIPT
Client-Side API Response Caching with localStorage (JavaScript)
Boost performance by caching API responses in `localStorage` in JavaScript, reducing redundant network requests and improving user experience.
const API_CACHE_PREFIX = 'api_cache_';
const CACHE_DURATION_MS = 5 * 60 * 1000; // 5 minutes
/**
* Fetches data from an API, utilizing localStorage for caching.
* @param {string} url The API endpoint URL.
* @param {object} options Fetch options (e.g., headers, method).
* @returns {Promise<any>} The parsed JSON data from the API or cache.
*/
async function fetchWithCache(url, options = {}) {
const cacheKey = API_CACHE_PREFIX + btoa(url + JSON.stringify(options)); // Unique key for URL + options
// Try to retrieve from cache
const cachedData = localStorage.getItem(cacheKey);
if (cachedData) {
try {
const { data, timestamp } = JSON.parse(cachedData);
if (Date.now() - timestamp < CACHE_DURATION_MS) {
console.log(`Returning cached data for: ${url}`);
return data; // Return cached data if fresh
} else {
console.log(`Cache expired for: ${url}`);
localStorage.removeItem(cacheKey); // Remove expired cache
}
} catch (e) {
console.error('Error parsing cached data, fetching fresh:', e);
localStorage.removeItem(cacheKey); // Clear corrupted cache
}
}
// If no valid cache, fetch from API
console.log(`Fetching fresh data for: ${url}`);
const response = await fetch(url, options);
if (!response.ok) {
const errorBody = await response.text();
throw new Error(`HTTP error! Status: ${response.status}, Body: ${errorBody}`);
}
const data = await response.json();
// Store new data in cache
try {
const cacheEntry = {
data: data,
timestamp: Date.now(),
};
localStorage.setItem(cacheKey, JSON.stringify(cacheEntry));
} catch (e) {
console.error('Error saving data to cache:', e);
// Can happen if localStorage is full or security settings prevent it
}
return data;
}
// Example usage:
// (async () => {
// try {
// const posts = await fetchWithCache('https://jsonplaceholder.typicode.com/posts/1');
// console.log('Posts data:', posts);
// // Subsequent call within cache duration will return cached data
// // await new Promise(resolve => setTimeout(resolve, 1000)); // Wait 1 second
// // const cachedPosts = await fetchWithCache('https://jsonplaceholder.typicode.com/posts/1');
// // console.log('Cached Posts data:', cachedPosts);
// } catch (error) {
// console.error('Fetch error:', error);
// }
// })();
How it works: This JavaScript snippet provides a client-side caching mechanism for API responses using `localStorage`. The `fetchWithCache` function first checks if a fresh version of the requested data exists in `localStorage`. If it does and hasn't expired, the cached data is returned instantly. Otherwise, it fetches the data from the API, stores it in `localStorage` along with a timestamp, and then returns it. This approach significantly reduces network requests for frequently accessed, non-real-time data, improving application performance and responsiveness.