JAVASCRIPT

Client-Side API Response Caching with localStorage and TTL

Implement simple client-side caching for API responses using JavaScript's `localStorage`, including a time-to-live (TTL) mechanism to ensure data freshness.

const CACHE_KEY_PREFIX = 'api_cache_';
const CACHE_TTL_HOURS = 1; // Cache duration in hours

async function fetchWithCache(url, options = {}) {
  const cacheKey = CACHE_KEY_PREFIX + url;
  const cachedData = localStorage.getItem(cacheKey);

  if (cachedData) {
    const { data, timestamp } = JSON.parse(cachedData);
    const now = new Date().getTime();
    const expirationTime = timestamp + (CACHE_TTL_HOURS * 60 * 60 * 1000);

    if (now < expirationTime) {
      console.log(`Returning cached data for ${url}`);
      return data; // Return cached data if not expired
    } else {
      console.log(`Cached data for ${url} expired, fetching new data.`);
      localStorage.removeItem(cacheKey); // Clear expired cache
    }
  }

  console.log(`Fetching live data for ${url}`);
  try {
    const response = await fetch(url, options);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const liveData = await response.json();

    // Store new data in cache with timestamp
    localStorage.setItem(cacheKey, JSON.stringify({
      data: liveData,
      timestamp: new Date().getTime(),
    }));

    return liveData;
  } catch (error) {
    console.error(`Error fetching data for ${url}:`, error);
    throw error;
  }
}

// Example Usage:
const API_URL_1 = 'https://jsonplaceholder.typicode.com/posts/1';
const API_URL_2 = 'https://jsonplaceholder.typicode.com/users/1';

// First call (fetches live, caches)
fetchWithCache(API_URL_1)
  .then(data => console.log('Data 1 (initial):', data))
  .then(() => fetchWithCache(API_URL_1)) // Second call (returns cached)
  .then(data => console.log('Data 1 (cached):', data))
  .catch(err => console.error(err));

// Call another endpoint
fetchWithCache(API_URL_2)
  .then(data => console.log('Data 2 (initial):', data))
  .catch(err => console.error(err));

// To test expiration, set CACHE_TTL_HOURS to a very small number like 0.0001 (about 0.36 seconds)
// and call again after that period.
How it works: This JavaScript snippet demonstrates how to implement a basic client-side caching mechanism for API responses using `localStorage`. The `fetchWithCache` function first checks if valid data for the given URL exists in `localStorage` and if it hasn't expired based on a defined Time-To-Live (TTL). If cached data is fresh, it's returned immediately. Otherwise, a live API request is made, and the fresh response is stored in `localStorage` along with a timestamp for future validation. This approach reduces network requests, improves application performance, and enhances user experience by displaying data more quickly.

Need help integrating this into your project?

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

Hire DigitalCodeLabs