JAVASCRIPT
Implement Client-Side Caching for API Responses
Optimize web application performance by implementing client-side caching for API responses using sessionStorage, reducing redundant network requests and improving user experience.
async function fetchWithCache(url, options = {}, cacheDuration = 300000) { // 5 minutes
const cachedData = sessionStorage.getItem(url);
const now = new Date().getTime();
if (cachedData) {
const { timestamp, data } = JSON.parse(cachedData);
if (now - timestamp < cacheDuration) {
console.log(`Serving from cache: ${url}`);
return data;
} else {
console.log(`Cache expired for: ${url}`);
sessionStorage.removeItem(url); // Clear expired cache
}
}
console.log(`Fetching new data for: ${url}`);
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
sessionStorage.setItem(url, JSON.stringify({ timestamp: now, data }));
return data;
} catch (error) {
console.error("Fetch error:", error);
throw error;
}
}
// Example Usage:
// async function loadUserData() {
// try {
// const users = await fetchWithCache('https://api.example.com/users', {}, 60000); // Cache for 1 minute
// console.log('Users:', users);
// } catch (error) {
// console.error('Failed to load users:', error);
// }
// }
// loadUserData();
How it works: This snippet demonstrates how to implement a basic client-side caching mechanism for API responses using `sessionStorage`. When `fetchWithCache` is called, it first checks if data for the given URL exists in `sessionStorage` and if it's still within the specified `cacheDuration`. If valid cached data is found, it's returned immediately, avoiding a network request. Otherwise, a new fetch request is made, and the response data, along with a timestamp, is stored in `sessionStorage` for future use. This strategy reduces redundant API calls, improves application responsiveness, and saves bandwidth.