JAVASCRIPT

Client-Side API Response Caching in Local Storage

Implement client-side caching for API responses using `localStorage` with a configurable expiry time, reducing redundant requests and improving application performance.

const CACHE_PREFIX = 'api_cache_'; // Prefix for cache keys
const DEFAULT_CACHE_DURATION = 5 * 60 * 1000; // 5 minutes in milliseconds

async function fetchCachedData(url, options = {}, cacheDuration = DEFAULT_CACHE_DURATION) {
    const cacheKey = CACHE_PREFIX + btoa(url + JSON.stringify(options)); // Unique key for URL + options
    const cachedItem = localStorage.getItem(cacheKey);

    if (cachedItem) {
        const { data, timestamp } = JSON.parse(cachedItem);
        if (Date.now() - timestamp < cacheDuration) {
            console.log(`Cache hit for ${url}`);
            return data; // Return cached data if not expired
        } else {
            console.log(`Cache expired for ${url}`);
            localStorage.removeItem(cacheKey); // Remove expired cache
        }
    }

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

    // Cache the new data with current timestamp
    localStorage.setItem(cacheKey, JSON.stringify({ data: liveData, timestamp: Date.now() }));
    return liveData;
}

// Usage Example:
/*
(async () => {
    const url = 'https://jsonplaceholder.typicode.com/todos/1';

    // First call - fetches and caches
    let data1 = await fetchCachedData(url, {}, 10 * 1000); // Cache for 10 seconds
    console.log('Data 1:', data1);

    // Second call within 10 seconds - uses cache
    let data2 = await fetchCachedData(url, {}, 10 * 1000);
    console.log('Data 2 (cached):', data2);

    // Wait for cache to expire, then fetch again
    setTimeout(async () => {
        let data3 = await fetchCachedData(url, {}, 10 * 1000);
        console.log('Data 3 (after expiry):', data3);
    }, 12 * 1000); // Wait 12 seconds
})();
*/
How it works: This JavaScript snippet demonstrates how to implement client-side caching for API responses using the browser's `localStorage`. It stores fetched data along with a timestamp. Before making a new API request, it checks if a valid, unexpired cached version exists for the given URL and options. If found, it returns the cached data immediately, reducing network requests and improving loading times. If the cache is expired or not found, it fetches fresh data, stores it, and then returns it. This technique is highly effective for data that doesn't change frequently.

Need help integrating this into your project?

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

Hire DigitalCodeLabs