JavaScript Fetch with Caching

Implement a cached fetch wrapper in vanilla JavaScript using the Cache API with stale-while-revalidate strategy, request deduplication, and automatic cache.

JavascriptData Fetching

Code

snippet
const cache = new Map();
const pending = new Map();

export async function cachedFetch(url, { ttl = 60000 } = {}) {
  const entry = cache.get(url);
  if (entry && Date.now() - entry.time < ttl) {
    return entry.data;
  }
  if (entry && Date.now() - entry.time < ttl * 2) {
    if (!pending.has(url)) {
      pending.set(url, fetch(url).then(r => r.json()).then(d => {
        cache.set(url, { data: d, time: Date.now() });
        pending.delete(url);
      }));
    }
    return entry.data;
  }
  const data = await (await fetch(url)).json();
  cache.set(url, { data, time: Date.now() });
  return data;
}

What the code does

Count the function cachedFetch as the entire surface area of JavaScript Fetch with Caching.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

Watch out for

  • This is browser-side code — fetch will not resolve in Node.

Applying it

Entry signature: export async function cachedFetch(url, { ttl = 60000 } = {})

Callers only need cachedFetch — everything else stays internal.

Statements that matter

pending.set(url, fetch(url).then(r => r.json()).then(d => {
cache.set(url, { data: d, time: Date.now() });
pending.delete(url);
}));
const data = await (await fetch(url)).json();
const pending = new Map();

Interactive Tools for This Topic

FAQ

Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced. The file defines `cachedFetch` at load time.