dustydojo
dustydojo

Reputation: 719

How do I troubleshoot automatic reload using VitePWA?

I am trying to leverage vite to automatically have the browser reload my PWA application when I push an update (I used the instructions here).

I added this to my vite.config.js file:

VitePWA({
  registerType: 'autoUpdate'
})

I also added this code to my index.jsx file:

import { registerSW } from 'virtual:pwa-register'

registerSW({ immediate: true })

The problem is that when I push an update (using firebase deploy), the client does not get the latest changes unless I refresh the page. I am trying to figure out how to troubleshoot this, so here are some questions:

  1. Are the changes I made sufficient for auto-reload?
  2. Do I need to update my package.json version number for the auto-reload to take effect?
  3. Do I need a custom service worker file, or will the auto-generated one suffice?
  4. Can I inspect any of the generated files (sw, workbox, etc.) to see if the proper code has been added?
  5. Can I use chrome dev tools somehow to troubleshoot?
  6. Is there somewhere I can add logs to help troubleshoot?

Upvotes: 5

Views: 2387

Answers (2)

Anonumos20
Anonumos20

Reputation: 11

For anyone still bumping into this, the solution is to add periodic service worker updates. Otherwise you'll discover the new worker only upon refresh or after closing the tab and re-open it. You can add as much time as you'd like in the interval

In your main file:

if ("serviceWorker" in navigator) {
    registerSW({
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    onRegistered(r: any) {
        r && setInterval(() => {
            console.log('Updating worker...');
            r.update();
        }, 1000 * 60 * 20)
    }
});

}

For more information, read HERE

Upvotes: 1

Bash
Bash

Reputation: 1618

I ran into the same issue too. I added the same code you did, had to add this to my tsconfig.json to fix a build error as well:

"types": [
  "vite-plugin-pwa/client"
]

In addition to your code, I added these meta tags in my index.html to disable the browser cache:

<meta http-equiv="Cache-Control" content="max-age=0, no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />

Finally, in my case I'm deploying my app to Cloudflare Pages, so I followed these instructions to setup a page rule that bypasses the cache: https://developers.cloudflare.com/cache/how-to/edge-browser-cache-ttl/create-page-rules/#cache-everything

In my testing, it gets triggered by a page load or refresh, then wait a few seconds for it to download the new files, then it will force-refresh.

Upvotes: 1

Related Questions