Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

checkValidServiceWorker() currently doesn't cover the case where I forget to start local server #21

Open
ZYinMD opened this issue Apr 18, 2021 · 0 comments

Comments

@ZYinMD
Copy link

ZYinMD commented Apr 18, 2021

If I forget to start the local server to serve my build, but visit it in the browser anyway, the old sw can still serve the old assets, and I may not notice. I thought part of the intention of checkValidServiceWorker() was to cover this scenario, but seems it doesn't.

something like this will cover that:

export function register() {
  if (process.env.NODE_ENV === "production" && "serviceWorker" in navigator) {
    const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
    window.addEventListener("load", async () => {
      if (isLocalhost) await validateLocalServer(swUrl);
      registerSW(swUrl);
    });
  }
}

async function validateLocalServer(swUrl: string) {
  try {
    const res = await fetch(swUrl, { headers: { "Service-Worker": "script" } }); // this throws if server isn't running
    if (res.status === 404) throw new Error("404");
  } catch (err) {
    alert(`Local server is not running, or running but no sw found. \n${err.message}`);
    return Promise.reject();
  }
}

async function registerSW(swUrl: string) {
  //...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant