Tony CantaveCaching API Data in the Browser with localStorage: Keep the Last Good Copy
By Tony Cantave ·
A lot of my JavaScript work involves calling APIs, and most of the attention usually goes to the request itself: timeouts, retries, checking response.ok. This post is about the other half of the problem. What should a page show when every retry has failed? For the screen management software I am building, the answer is simple. Show the last content that worked, and keep trying quietly in the background. A blank screen in a shop is worse than a screen that is a few hours behind.
The browser already has a simple tool for this: localStorage.
Why localStorage, and where it stops
localStorage is built into every modern browser. It stores strings by key, it survives reloads and restarts, and its API is small and synchronous. That makes it a good fit for caching a few small JSON responses like settings, a schedule or a playlist.
It has limits worth knowing before you lean on it. It only stores strings, so everything goes through JSON. Most browsers give each site only a few megabytes. Writes can throw when that space is full, and some privacy settings block storage entirely. And any script running on the same site can read it, so it is never the place for tokens, passwords or personal data. For large files or binary content, IndexedDB or the Cache API is the better tool.
Save with a timestamp
A cached value is only useful if you know how old it is, so I always store the time alongside the data:
const CACHE_PREFIX = "cache:";
function saveToCache(key, data) {
const entry = { savedAt: Date.now(), data };
try {
localStorage.setItem(CACHE_PREFIX + key, JSON.stringify(entry));
return true;
} catch (error) {
console.warn(`Could not cache ${key}: ${error.message}`);
return false;
}
}The try and catch is not decoration. setItem throws a QuotaExceededError when storage is full, and caching is a bonus feature. A failure to cache should never break the page that is trying to use it.
Read it back defensively
Anything in storage might have been written by an older version of your code, or edited by hand in the browser dev tools. Treat anything unexpected as a cache miss instead of crashing on it:
function readFromCache(key) {
try {
const raw = localStorage.getItem(CACHE_PREFIX + key);
if (raw === null) return null;
const entry = JSON.parse(raw);
if (typeof entry.savedAt !== "number" || !("data" in entry)) return null;
return entry;
} catch {
return null;
}
}Decide what fresh means
I use two ages. A short one where the cached copy is good enough to skip the network entirely, and a long one past which the copy is too old to show at all. Between the two, the page shows the cached copy and tries to refresh.
function isFresh(entry, maxAgeMs) {
return entry.savedAt + maxAgeMs > Date.now();
}Put it together
Here is the loader I start from. fetchWithRetry stands for any function that returns parsed JSON or throws, ideally one with a timeout and a few retries built in:
const MINUTE = 60 * 1000;
const DAY = 24 * 60 * MINUTE;
async function loadWithFallback(key, url, { freshMs = 5 * MINUTE, maxStaleMs = 2 * DAY } = {}) {
const cached = readFromCache(key);
if (cached && isFresh(cached, freshMs)) {
return { data: cached.data, source: "cache" };
}
try {
const data = await fetchWithRetry(url);
saveToCache(key, data);
return { data, source: "network" };
} catch (error) {
if (cached && isFresh(cached, maxStaleMs)) {
console.warn(`Using cached ${key} after error: ${error.message}`);
return { data: cached.data, source: "stale cache" };
}
throw error;
}
}Returning the source along with the data is a small habit that pays off. The page can show a quiet "last updated" note when it is running on an older copy, and the logs show how often the fallback is actually being used. If that number climbs, something upstream needs attention.
Only cache data you have checked
One trap catches almost everyone once. A server returns a 200 with valid JSON in the wrong shape, the code caches it, and now the last good copy has been replaced with a bad one. Validate the response first, then save it:
const data = assertPlaylist(await fetchWithRetry(url));
saveToCache("playlist", data);The check can be a few lines that confirm the fields the rest of the code depends on. What matters is the order.
Clean up old entries
The prefix on every key makes housekeeping easy. On startup, remove anything that is past its useful age so old entries do not slowly fill the space:
function clearOldCache(maxAgeMs) {
for (const fullKey of Object.keys(localStorage)) {
if (!fullKey.startsWith(CACHE_PREFIX)) continue;
const entry = readFromCache(fullKey.slice(CACHE_PREFIX.length));
if (!entry || !isFresh(entry, maxAgeMs)) {
localStorage.removeItem(fullKey);
}
}
}What I take from this
Years in delivery and logistics operations taught me that the plan for when a system is down matters as much as the system itself. Pages that depend on a network deserve the same thinking. Decide ahead of time what the user sees when the request fails, keep the last good copy, label it honestly, check data before you trust it, and make sure the cache itself can never become a new way for the page to break.