← Back to all snippets
JAVASCRIPT

Implement Basic Client-Side API Caching

Improve web application performance and reduce server load by implementing a simple client-side in-memory cache for frequently accessed API responses.

const apiCache = new Map();

async function fetchWithCache(url, options = {}, cacheDurationMs = 5 * 60 * 1000) {
  const now = Date.now();
  const cachedData = apiCache.get(url);

  if (cachedData && (now - cachedData.timestamp < cacheDurationMs)) {
    console.log(`Returning cached data for: ${url}`);
    return cachedData.data;
  }

  console.log(`Fetching fresh 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();
    apiCache.set(url, { data, timestamp: now });
    return data;
  } catch (error) {
    console.error(`Error fetching data for ${url}:`, error);
    throw error;
  }
}

// Example usage:
// async function loadData() {
//   const userUrl = 'https://api.example.com/users/current';
//   const productsUrl = 'https://api.example.com/products';

//   // First call - fetches data and caches it
//   const userData = await fetchWithCache(userUrl);
//   console.log('User Data (first call):', userData);

//   // Second call shortly after - returns cached data
//   const userDataCached = await fetchWithCache(userUrl);
//   console.log('User Data (second call, from cache):', userDataCached);

//   // Fetching different data
//   const productData = await fetchWithCache(productsUrl, {}, 10 * 1000); // Cache for 10 seconds
//   console.log('Product Data:', productData);
// }
// loadData();
How it works: This snippet implements a basic client-side in-memory cache for API responses using a JavaScript `Map`. Before making a network request, it checks if the data for the given URL exists in the cache and is still valid (within a defined `cacheDurationMs`). If so, it returns the cached data immediately. Otherwise, it fetches fresh data from the API, stores it in the cache with a timestamp, and then returns it. This technique significantly reduces redundant API calls and improves application responsiveness for frequently accessed data.

Need help integrating this into your project?

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

Hire DigitalCodeLabs