Search code examples
javascriptnode.jsgatsbyservice-worker

Gatsby Site Requires Refresh to View New Data


I have a blog run on Gatsby, and every time I push and deploy new blog posts I need to do a refresh on my page to see the new data.

I tried following the suggestions from this post and adding an onServiceWorkerUpdate function but that doesn't seem to have done anything.

Anyone have workarounds to this issue, and if so will there be a way to test locally? Changes already automatically update when I test in gatsby develop mode.

This is the entirety of my gatsby-browser.js file

export const onServiceWorkerUpdateReady = () => window.location.reload();

Solution

  • You need to install gatsby-plugin-offline first. Leaving your gatsby-config.js with something similar to:

    {
      plugins: [
        {
          resolve: `gatsby-plugin-manifest`,
          options: {
            ...
          }
        },
        'gatsby-plugin-offline'
      ]
    }
    

    Note: plugin's order matters in this case.

    The plugin will register a service worker and will load it into the client.

    Then, in your gatsby-browser.js file you can simply add:

    export const onServiceWorkerUpdateReady = () => {
      const answer = window.confirm(
        `This application has been updated. ` +
          `Reload to display the latest version?`
      )
    
      if (answer === true)  window.location.reload()
    }
    

    Additionally, you may want to add the following hack (very common across the repositories):

    export const onRouteUpdate = () => {
      navigator.serviceWorker.register('/sw.js').then((reg) => {
        reg.update();
      });
    };
    

    Basically, it forces the registration of the service-worker across the site upon the onServiceWorkerUpdateReady refresh.

    Check this interesting thread for further caveats and workarounds for some specific scenarios: https://github.com/gatsbyjs/gatsby/issues/9087#issuecomment-774680408