JAVASCRIPT

Basic Client-Side API Response Caching with LocalStorage

Improve web application performance and reduce unnecessary API calls by implementing a simple client-side caching mechanism for API responses using localStorage.

async function fetchWithCache(url, cacheDurationMinutes = 5) {
  const cacheKey = `api_cache_${url}`;
  const cachedData = localStorage.getItem(cacheKey);
  const now = new Date().getTime();

  if (cachedData) {
    const { timestamp, data } = JSON.parse(cachedData);
    // Check if cached data is still valid
    if (now - timestamp < cacheDurationMinutes * 60 * 1000) {
      console.log('Serving from cache:', url);
      return data;
    } else {
      console.log('Cache expired for:', url);
      localStorage.removeItem(cacheKey); // Remove expired cache
    }
  }

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

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

    return data;
  } catch (error) {
    console.error("Failed to fetch data:", error);
    return null;
  }
}

// Example usage:
async function loadPosts() {
  const posts = await fetchWithCache('https://jsonplaceholder.typicode.com/posts?_limit=5', 1); // Cache for 1 minute
  if (posts) {
    const container = document.getElementById('posts-container');
    container.innerHTML = '';
    posts.forEach(post => {
      const div = document.createElement('div');
      div.textContent = post.title;
      container.appendChild(div);
    });
    console.log('Posts loaded:', posts.length);
  }
}

// Call it multiple times, only the first one (or after cache expires) will hit the API
loadPosts(); 
// setTimeout(loadPosts, 30 * 1000); // Try again after 30 seconds (should be cached)
// setTimeout(loadPosts, 70 * 1000); // Try again after 70 seconds (cache expired, new fetch)

// Example HTML: <div id="posts-container"></div>
How it works: This snippet illustrates a basic client-side caching mechanism for API responses using `localStorage`. The `fetchWithCache` function first checks if a response for the given URL exists in `localStorage` and if it's still within its valid `cacheDurationMinutes`. If valid, it returns the cached data; otherwise, it makes a new API request. Upon a successful fetch, the new data, along with a timestamp, is stored in `localStorage` for future use, reducing redundant API calls and improving performance.

Need help integrating this into your project?

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

Hire DigitalCodeLabs