Search code examples
service-workerprogressive-web-appsworkbox

Workbox: clean up cache


It doesn't seem like workbox cleans up old caches. For example, if I specify a cache version like this:

var version = 'v2';
workbox.core.setCacheNameDetails({
  suffix: version
});

...I would have expected workbox to clean up older versions of the cache once the new service worker activates, but my cache storage looks like this:

enter image description here

Is it safe to manually clean up caches myself? For example in my service worker:

self.addEventListener('activate', function(event) {
  event.waitUntil(
    caches
      .keys()
      .then(keys => keys.filter(key => !key.endsWith(version)))
      .then(keys => Promise.all(keys.map(key => caches.delete(key))))
  );
});

Solution

  • You are changing the suffix property value to a string that you are as a version. But Workbox only uses it to name the bucket for caching.

    From the Workbox docs.

    The main use case for the prefix and suffix is that if you use Workbox for multiple projects and use the same localhost for each project, setting a custom prefix for each module will prevent the caches from conflicting with each other.

    Workbox doesn't think of x-v2 as the new replacement for x-v1.

    You can use your cache eviction strategy just fine since Workbox will no longer use the previously named caches.

    However you shouldn't need to use suffix to version your assets. Workbox has a number of tools to make sure assets are updated correctly. Plus your suffix implementation will always start out with a fresh cache and download everything.

    precache

    Precache has revisions for assets so as the assets change, you generate a new build, and deploy the changed assets will update and the unchanged assets will be left alone.

    strategies

    Strategies is where most of the work will be done. When you are defining routes you will define the caching strategy the fits best with that type of asset. staleWhileRevalidate is a great approach where the on-device cache will be used but Workbox will also hit the network in parallel and check if there are updates to that resource.

    expiration

    You can also make sure that old assets purged if they become older than the defined expiration length.