Search code examples
service-workerbrowser-cacheworkbox

Workbox: how to remove a request from the cache


I'm using staleWhileRevalidate Workbox v3 strategy for all of my API Get calls. However, sometimes I want to remove a particular request from the cache at runtime.

Example: I have a yes/no state that can be updated by the client. Initially, the UI displays the "no" state (taken from the cache) while executing a request that also returns a "no" result. The result of the request is cached by Workbox.

Now, the user switches it to "yes", the system updates the server and sends another query after some time to get the latest value. But the cache still stores the "no" value which is displayed in the UI while the new request returns "yes" which is now stored in the cache.

What I need here is to remove the "no" result from the cache right when I send the update request from the server. How do I do that? How can I access the Workbox's cache from the page code?


Solution

  • Workbox uses the browser's Cache Storage API for its caching. You can access the same caches directly, either via the window context or inside of a service worker, from your own code.

    It's easier to do this if you configure your Workbox strategy to use a specific cache name, rather than the default cache name, since you'd otherwise need to reverse-engineer some of the Workbox logic to create the default cache name inside of the window context. Assuming you know the cache name and the URL to delete, you can call the following function from within the window context to use the Cache Storage API to delete the entry:

    async function deleteFromCache(cacheName, urlOrPath) {
      const cache = await caches.open(cacheName);
      await cache.delete(urlOrPath);
    }
    
    // Later:
    await deleteFromCache('runtime-cache', '/path/to/entry');