is this Service Worker configuration risky?

269 views Asked by At

I am working on one e-commerce using Next JS. I am trying to improve the page load speed, this website loads a lot of JS files due to the amount of third parties vendors it has (and can't delete). I am planning to cache some static assets with Service Workers.

I am going to use the library next-offline that uses the workbox-webpack-plugin. This is the configuration I am planning to use:

workboxOpts: {
              swDest: '../public/service-worker.js',
              maximumFileSizeToCacheInBytes: 20000000,
              runtimeCaching: [
                {
                  urlPattern: /https:\/\/fonts\.googleapis\.com\/icon[\w\-_\/\.\:\?\=\&\+]*/,
                  handler: 'CacheFirst',
                  options: {
                    cacheName: 'google-fonts',
                    expiration: {
                      maxEntries: 10,
                      maxAgeSeconds: 30 * 24 * 60 * 60, // 1 month
                    },
                  },
                },
                {
                  urlPattern: /[\w\-_\/\.:]*\.(jpeg|png|jpg|ico|svg)\??.*/,
                  handler: 'CacheFirst',
                  options: {
                    cacheName: 'cache-img',
                    expiration: {
                      maxEntries: 15,
                      maxAgeSeconds: 2 * 24 * 60 * 60, // 2 days
                    },
                  },
                },
                {
                  urlPattern: /^((?!monetate).)*\.(js)$/,
                  handler: 'StaleWhileRevalidate',
                },
                {
                  urlPattern: /\/(browse.*|catalogsearch.*)$/,
                  handler: 'StaleWhileRevalidate',
                },
              ],
            },

So, my questions are the following:

  1. do you think that this configuration is risky? Would you change something? I mean, I had several problems in the past with Service Workers caching JS files where I had to set a version for every file to make it work. However, now it seems that workbox fixed this issue.
  2. Should I set a maxAge for the Stale while revalidation strategy? I want to revalidate the data every time the user reload the page. However here it says that it will use the cache without revalidate until the maxAge time is complete. What happens if I don't set in the workbox settings a maxAge?

I am testing this on a Vercel deploy (in a testing environment) and it seems it is working fine and I am thinking to move it to production.

Thanks,

1

There are 1 answers

0
Sandeep Kumar On

You can use next-offline(i haven't used it much), or you can go ahead with using workbox-webpack-plugin. There is take cares of what file to refetch after caching(uses revision & hash(on url)). Read this section : https://developers.google.com/web/tools/workbox/modules/workbox-precaching#how_workbox-precaching_works