JAVASCRIPT

Efficient Client-Side API Response Caching

Implement a generic client-side caching mechanism for API responses using `sessionStorage` in JavaScript to reduce redundant network requests and improve performance.

const apiCache = {
  get: (key) => {
    try {
      const cachedItem = sessionStorage.getItem(key);
      if (cachedItem) {
        const { data, timestamp, expiry } = JSON.parse(cachedItem);
        if (Date.now() < timestamp + expiry) {
          return data;
        } else {
          sessionStorage.removeItem(key); // Cache expired
        }
      }
    } catch (e) {
      console.error("Error reading from sessionStorage:", e);
      sessionStorage.removeItem(key); // Clear potentially corrupt data
    }
    return null;
  },
  set: (key, data, expiryMs = 5 * 60 * 1000) => { // Default 5 minutes
    try {
      const item = JSON.stringify({ data, timestamp: Date.now(), expiry: expiryMs });
      sessionStorage.setItem(key, item);
    } catch (e) {
      console.error("Error writing to sessionStorage:", e);
    }
  },
  clear: (key) => {
    sessionStorage.removeItem(key);
  },
  clearAll: () => {
    sessionStorage.clear();
  }
};

async function fetchAndCache(url, options = {}, cacheDurationMs) {
  const cacheKey = JSON.stringify({ url, options }); // Create unique key for URL + options
  const cachedData = apiCache.get(cacheKey);

  if (cachedData) {
    console.log(`Cache hit for ${url}`);
    return cachedData; // Return parsed data directly
  }

  console.log(`Cache miss for ${url}. Fetching...`);
  const response = await fetch(url, options);
  if (!response.ok) {
    throw new Error(`HTTP error! Status: ${response.status}`);
  }
  const data = await response.json(); // Assuming JSON response
  apiCache.set(cacheKey, data, cacheDurationMs);
  return data;
}

// Example Usage:
// async function loadData() {
//   try {
//     // Cache for 1 minute (60 * 1000 ms)
//     const users = await fetchAndCache('https://jsonplaceholder.typicode.com/users', {}, 60 * 1000);
//     console.log('Users:', users);
//   } catch (error) {
//     console.error('Failed to load data:', error);
//   }
// }
// loadData(); // First call fetches and caches
// setTimeout(loadData, 5000); // Second call will hit cache if within 1 minute
// setTimeout(loadData, 65000); // Third call will re-fetch after 1 minute expiry
How it works: This snippet provides a generic `apiCache` object and `fetchAndCache` function to manage client-side caching of API responses using `sessionStorage`. It stores data along with a timestamp and an expiry duration. Before making a network request, it checks if valid, unexpired data exists in the cache. If found, it returns the cached data, otherwise, it fetches from the network, stores the new data in the cache, and then returns it. This significantly reduces redundant API calls and improves application responsiveness.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs