Skip to content

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

@ZYinMD

Description

@ZYinMD

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) {
  //...
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions