Fetch and Cache JSON APIs with One Request
In this article
Fetching and caching JSON APIs with a single request involves creating a wrapper function that checks for existing data in local storage before initiating a network call. This pattern reduces server load, minimizes API costs, and ensures your application remains responsive even when the network is unstable or the API has strict rate limits. By implementing a "stale-while-revalidate" or a simple "cache-first" logic, you can serve data instantly to the user while updating the background cache for future visits.
What You'll Need
- A modern web browser supporting the Fetch API and Web Storage API (localStorage or sessionStorage).
- A valid JSON API endpoint (URL) that allows CORS (Cross-Origin Resource Sharing) requests.
- Basic knowledge of JavaScript, specifically async/await syntax and JSON parsing.
- A code editor such as VS Code or a browser-based environment like CodePen.
Step-by-Step
- Define Your Cache Configuration: Establish a unique key for your API data and a Time-to-Live (TTL) value. The TTL determines how long the cached data remains valid (e.g., 3600 seconds for one hour) before the application is forced to fetch a fresh copy from the server.
- Create the Wrapper Function: Write an asynchronous function that accepts the API URL and the cache key as parameters. This function will act as the single point of entry for all your data requests, abstracting the caching logic away from your UI components.
- Check for Cached Data: Inside the function, use
localStorage.getItem(cacheKey)to retrieve any stored data. If the data exists, parse it from a JSON string back into a JavaScript object. - Validate the Cache Age: If cached data is found, check the timestamp associated with that data. Compare the current time with the stored timestamp; if the difference is less than your defined TTL, return the cached object immediately and exit the function.
- Execute the Network Request: If no cache exists or the cache has expired, use the
fetch()method to request the data from the API endpoint. Ensure you handle the response by checkingresponse.okto verify the request was successful. - Parse and Store the Response: Once the API returns the JSON data, create a wrapper object that contains both the API response and a current timestamp. Convert this wrapper object into a string using
JSON.stringify()and save it tolocalStorage.setItem(cacheKey, dataString). - Return the Final Data: Return the parsed JSON data to the calling function so it can be rendered in the application.
Common Mistakes
- Forgetting to Stringify: LocalStorage only stores strings. Attempting to save a JavaScript object directly will result in the value
[object Object]being stored, which is useless upon retrieval. - Ignoring CORS Errors: Many APIs block requests from unauthorized domains. If your fetch fails with a CORS error, you cannot solve this in client-side JavaScript; you must either configure the API server or use a backend proxy.
- Overfilling LocalStorage: LocalStorage has a limit (usually around 5MB). Caching massive JSON payloads from multiple APIs can lead to
QuotaExceededError. Always monitor the size of the data you are caching. - Neglecting Error Handling: Failing to use
try...catchblocks aroundJSON.parse()can crash your application if the cached data becomes corrupted or is manually edited in the browser console.
Tips
- Use SessionStorage for Temporary Data: If the data should only persist for the duration of the browser tab session, use
sessionStorageinstead oflocalStorage. - Implement a Manual Refresh: Provide a "Refresh" button in your UI that clears the specific cache key and triggers a new fetch, allowing users to force-update their data.
- Use an Object for Multiple Keys: Instead of creating dozens of individual keys, store a single "api_cache" object in LocalStorage and manage different endpoints as properties within that object.
- Consider IndexedDB for Large Sets: If your JSON responses are several megabytes in size, migrate from LocalStorage to IndexedDB, which offers significantly more storage space and asynchronous access.
Troubleshooting
If your application is not caching data, first open the Browser Developer Tools (F12), go to the Application tab, and check the Local Storage section. If the key is missing, your setItem logic is failing. If the key exists but the app still fetches from the network, check your TTL logic; you may be using milliseconds where seconds are expected, or vice versa.
If the API request fails entirely, check the Network tab. A 403 or 401 error indicates an authentication issue (missing API key), while a 429 error means you have hit the rate limit. In the case of a 429 error, increasing your TTL is the most effective way to reduce the number of requests sent to the server.
Frequently Asked Questions
Does this method work with POST requests?
Generally, no. Caching is intended for GET requests where the data is retrieved. POST requests usually change data on the server, and caching those responses can lead to outdated or incorrect state management.
How do I clear the cache for a specific API?
Use localStorage.removeItem('your_cache_key'). This deletes only the data associated with that specific key without affecting other stored settings.
Will this improve my page load speed?
Yes. Retrieving data from LocalStorage is significantly faster than making a network request, as it eliminates the latency involved in DNS lookup, TCP handshakes, and server processing.
Is LocalStorage secure for API data?
LocalStorage is not encrypted and is accessible by any script running on your page. Never cache sensitive information, such as user passwords, private API keys, or personally identifiable information (PII).
What happens if the API structure changes?
If the API changes its JSON schema, the cached version may be incompatible with your new code. To prevent this, include a version number in your cache key (e.g., api_data_v1) and increment it when you update your app's data handling.