JAVASCRIPT
Client-Side Caching for API Responses
Improve web application performance and reduce API calls by implementing a simple client-side cache for API responses using JavaScript's Map object.
const apiCache = new Map(); // Stores responses with URL as key
async function fetchWithCache(url, options = {}, cacheDurationMs = 300000) { // 5 minutes default
const cacheKey = JSON.stringify({ url, options }); // Create a unique key for the request
if (apiCache.has(cacheKey)) {
const { data, timestamp } = apiCache.get(cacheKey);
if (Date.now() - timestamp < cacheDurationMs) {
console.log(`Cache hit for ${url}`);
return data; // Return cached data if not expired
} else {
console.log(`Cache expired for ${url}`);
apiCache.delete(cacheKey); // Remove expired cache
}
}
console.log(`Fetching ${url} from API...`);
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
// Cache the new data
apiCache.set(cacheKey, { data, timestamp: Date.now() });
return data;
} catch (error) {
console.error('Error fetching data with cache:', error);
throw error;
}
}
// Example usage:
// const apiUrl = 'https://jsonplaceholder.typicode.com/posts/1';
//
// (async () => {
// // First call - fetches from API and caches
// let post = await fetchWithCache(apiUrl);
// console.log('First call:', post);
//
// // Second call within cache duration - retrieves from cache
// post = await fetchWithCache(apiUrl);
// console.log('Second call (cached):', post);
//
// // Wait for cache to expire (e.g., set cacheDurationMs to 100ms for testing)
// // await new Promise(resolve => setTimeout(resolve, 150));
//
// // Third call after cache expiry - fetches from API again
// // post = await fetchWithCache(apiUrl, {}, 100);
// // console.log('Third call (re-fetched):', post);
// })();
How it works: This snippet implements a simple client-side caching mechanism for API responses. It uses a `Map` to store fetched data along with a timestamp. Before making an API request, it checks if the data for the given URL and options is already in the cache and hasn't expired. If a valid cached response exists, it's returned immediately, reducing redundant network calls. Otherwise, it fetches the data from the API, stores it in the cache with the current timestamp, and then returns it, significantly improving performance and reducing server load for frequently accessed data.