Search code examples
reactjscreate-react-appprogressive-web-apps

API cache in PWA generated by Create React App v4


This is the template using cra-template-pwa-typescript. How do I cache external APIs and Images?


Solution

  • c-r-a v4 uses a model in which you have complete control over your Workbox-powered service worker file.

    The general guidance on caching in the Workbox docs should help: https://developers.google.com/web/tools/workbox/guides/handle-third-party-requests

    To give a concrete example, let's say you wanted to cache all cross-origin images with a stale-while-revalidate strategy. You could do that by adding this route to your service worker file:

    registerRoute(
      ({request, url}) => url.origin !== self.location.origin &&
                          request.destination === 'image',
    
      new StaleWhileRevalidate({
        cacheName: 'cross-origin-images',
        plugins: [
          // Ensure that once this runtime cache reaches a maximum size the
          // least-recently used images are removed.
          new ExpirationPlugin({ maxEntries: 50 }),
        ],
      })
    );