Skip to content

The Cache API

The Cache API revolves around two objects: the global CacheStorage (accessed via caches) and the individual Cache objects it manages. All methods are async and return Promises.

Opens an existing named cache or creates a new one if it does not exist. Returns a Cache object. Cache names are arbitrary strings — use versioned names like app-shell-v2 to manage upgrades.

const cache = await caches.open('demo-cache-v1');

Stores a Request/Response pair. The first argument can be a Request object or a URL string; the second must be a Response. Any existing entry for the same request is replaced.

const cache = await caches.open('demo-cache-v1');
await cache.put('/api/hello', new Response('{"status":"ok"}', {
headers: { 'Content-Type': 'application/json' },
}));

Fetches the given URL and stores the resulting response in the cache. Equivalent to calling fetch(url) followed by cache.put(url, response). The request must succeed (2xx status) or the cache is not updated.

const cache = await caches.open('demo-cache-v1');
await cache.add('/images/logo.png'); // fetches then stores

Accepts an array of URL strings and fetches all of them atomically. If any request fails, none of the responses are stored. Use this when you need a group of assets to be cached together or not at all.

const cache = await caches.open('demo-cache-v1');
await cache.addAll([
'/index.html',
'/styles/main.css',
'/scripts/app.js',
]);

Looks up the cache for an entry matching the given request (URL string or Request). Returns the matching Response or undefined if no entry exists. The optional options object accepts ignoreSearch, ignoreMethod, and ignoreVary.

const cache = await caches.open('demo-cache-v1');
const response = await cache.match('/api/hello');
if (response) {
console.log(await response.json());
}

Like cache.match but searches across all named caches in the current origin, returning the first match found. Useful when you do not know which cache holds a particular response.

const response = await caches.match('/api/hello');

Removes the entry for the given request from the cache. Returns true if an entry was found and deleted, false otherwise.

const cache = await caches.open('demo-cache-v1');
const deleted = await cache.delete('/api/hello');
console.log('Deleted:', deleted); // true

Returns an array of all cache names for the current origin. Use it to enumerate or clean up caches.

const names = await caches.keys();
console.log('Open caches:', names);
// Delete all caches
for (const name of names) {
await caches.delete(name);
}
Browser Storage
What does cache.addAll([...urls]) do if one URL returns a 404?
What is the difference between cache.match() and caches.match()?
What does cache.delete(request) return?
Which method returns the names of all open caches for the current origin?