reactjscreate-react-appprogressive-web-appsservice-workerworkbox

problem to cache json file in react pwa service worker(create with cra)


i create pwa app using cra template. my problem is service worker didnt cache my locales folder(contain json file for translation) after running app and in offline mode everything works well except 2 json file that contain language translation

build folder

service worker

how can i add json files to service worker precache(using workbox by default)


Solution

  • If your JSON files are located in the public folder or within your project, you can use the following code to cache them:

        registerRoute(
      /\.(?:json)$/i,
      new StaleWhileRevalidate({
        cacheName: CACHE_NAME + 'static-json-assets',
      }),
      'GET'
    );
    

    This code registers a route for JSON files and caches them using the "Stale-While-Revalidate" caching strategy.

    If the JSON files are fetched from an API, you should use the fetch event to cache these files.

        self.addEventListener('fetch', event => {
      if (event.request.url.includes('.json')) {
        event.respondWith(
          caches.open('json-cache').then(cache => {
            return cache.match(event.request).then(response => {
              return response || fetch(event.request).then(networkResponse => {
                cache.put(event.request, networkResponse.clone());
                return networkResponse;
              });
            });
          })
        );
      }
    });