Minimal CacheStorage API Example

CacheStorage is a newer browser storage API that’s intended for caching HTTP responses, to enable PWAs to work offline. You can also use it to store HTTP response in other situations too, though.

There don’t seem to be a lot of examples of using it outside of a service worker context, though, or with the much cleaner await operator, so I put one together and added it to MDN’s docs.

Minimal Example

// Try to get data from the cache, but fall back to fetching it live.
async function getData() {
	const cacheVersion = 1;
	const cacheName    = `myapp-${ cacheVersion }`;
	const url          = 'https://jsonplaceholder.typicode.com/todos/1';
	let cachedData     = await getCachedData( cacheName, url );

	if ( cachedData ) {
		console.log( 'Retrieved cached data' );
		return cachedData;
	}

	console.log( 'Fetching fresh data' );

	const cacheStorage = await caches.open( cacheName );
	await cacheStorage.add( url );
	cachedData = await getCachedData( cacheName, url );
	await deleteOldCaches( cacheName );

	return cachedData;
}

// Get data from the cache.
async function getCachedData( cacheName, url ) {
	const cacheStorage   = await caches.open( cacheName );
	const cachedResponse = await cacheStorage.match( url );

	if ( ! cachedResponse || ! cachedResponse.ok ) {
		return false;
	}

	return await cachedResponse.json();
}

// Delete any old caches to respect user's disk space.
async function deleteOldCaches( currentCache ) {
	const keys = await caches.keys();

	for ( const key of keys ) {
		const isOurCache = 'myapp-' === key.substr( 0, 6 );

		if ( currentCache === key || ! isOurCache ) {
			continue;
		}

		caches.delete( key );
	}
}

try {
	const data = await getData();
	console.log( { data } );
} catch ( error ) {
	console.error( { error } );
}

Real World Example

For a bit more involved example, check out how Quick Navigation Interface fetches and caches the user’s content index.

That’s in a WordPress plugin, so it uses apiFetch() to automatically get a fetch() polyfill and add nonces to the XHR request. That has the side-effect of needing to use Cache.put() instead of the simpler Cache.add() from the example above.

Chrome and HTTP

CacheStorage is related to the service worker spec, but can be used independently. Because service workers require HTTPS, though, Chrome and Safari also require HTTPS to use CacheStorage. You can use it without HTTPS in Firefox, though.

Leave a Reply

Your email address will not be published. Required fields are marked *