Gatsby

Why your Gatsby links might be dropping query parameters or hashes after each service worker update

By Robert Caracaus · 19th of July, 2021

We recently discovered a rather interesting bug on one of our client's sites. The site uses Algolia to provide an interactive search page for its eCommerce products and has links from different parts of the site which take the user to the search page with specific filters applied. These filters are passed through to the search page via query parameters. We noticed that every now and again these links would drop the query parameters and take the user to the search page without any filters applied. The user then had to re-apply the filters they wanted to use.

Given that the bug was happening, at most, once every 30 minutes, we had a suspicion it might be correlated with our builds or even our service worker integration. So with that information in mind we went digging in the Gatsby core codebase and noticed these few lines.

// Ref: https://github.com/gatsbyjs/gatsby/blob/d86cd9ffd460f0840bc8ce572b628fb82d8004f8/packages/gatsby/cache-dir/navigation.js#L50-L65

let { pathname } = parsePath(to)
const redirect = maybeGetBrowserRedirect(pathname)

// If we're redirecting, just replace the passed in pathname
// to the one we want to redirect to.
if (redirect) {
  to = redirect.toPath
  pathname = parsePath(to).pathname
}

// If we had a service worker update, no matter the path, reload window and
// reset the pathname whitelist
if (window.___swUpdated) {
  window.location = pathname
  return
}

The expected behavior here is that, after a service worker update, any navigation done via Gatsby links will trigger a full refresh on the next page to reload the service worker. However this full refresh does not pass over the query parameter or hash from the link you are navigating to. The end result being that these values are dropped during the navigation.

Thankfully, after now pinpointing the bug, the fix was simple. We setup a PR to Gatsby and the team over there were quick to review and approve our changes. We've already updated our Gatsby version to the latest rolling release gatsby@3.11.0-next.0 to resolve this bug for our client but we encourage you to wait until the next full release is made before jumping in unless your site is critically impacted by this bug. These fixes are hot out of the oven and it's always best to give the latest release some time to rest before pulling it into your site.