Zen-Ventzi-Marinov
Zen-Ventzi-Marinov

Reputation: 4236

What to change to prevent double request from service worker?

Please do not mark as duplicate. This is not an exact duplicate of the other similar questions here on SO. It's more specific and fully reproducible.

  1. Clone this repo.
  2. yarn && yarn dev
  3. Go to localhost:3000 and make sure under (F12)->Applications->Service workers, the service worker is installed.
  4. Go to Network tab and refresh a few times(F5)
  5. Observe how the network requests are doubled.

Example of what I see: enter image description here


Or if you want to do it manually follow the instructions below:

  1. yarn create-next-app app_name
  2. cd app_name && yarn
  3. in public folder, create file called service-worker.js and paste the following code:
addEventListener("install", (event) => {
  self.skipWaiting();
  console.log("Service worker installed!");
});

self.addEventListener("fetch", (event) => {
  event.respondWith(
    (async function () {
      const promiseChain = fetch(event.request.clone()); // clone makes no difference
      event.waitUntil(promiseChain); // makes no difference
      return promiseChain;
    })()
  );
});
  1. open pages/index.js and just below import Head from "next/head"; paste the following code:
if (typeof window !== "undefined" && "serviceWorker" in navigator) {
  window.addEventListener("load", function () {
    // there probably needs to be some check if sw is already registered
    navigator.serviceWorker
      .register("/service-worker.js", { scope: "/" })
      .then(function (registration) {
        console.log("SW registered: ", registration);
      })
      .catch(function (registrationError) {
        console.log("SW registration failed: ", registrationError);
      });
  });
}
  1. yarn dev
  2. go to localhost:3000 and make sure the service worker has been loaded under (F12)Applications/Service Workers
  3. Go to the Network tab and refresh the page a few times. See how the service worker sends two requests for each one

What do I need to change in the service-worker.js code so that there are no double requests?

Upvotes: 5

Views: 5106

Answers (3)

Verbal Dancing
Verbal Dancing

Reputation: 11

If anyone is looking for an answer to the original question 'What to change to prevent double request from service worker?', specifically for network requests.

I've found a way to prevent it. Use the following in the serviceworker.js. (This also works for api calls etc.)

self.addEventListener('fetch', async function(event) {

    await new Promise(function(res){setTimeout(function(){res("fetch request allowed")}, 9999)})
    return false

});

Upvotes: 0

abraham
abraham

Reputation: 47913

This is how Chrome DevTools shows requests and is expected.

There is a request for a resource from the client JavaScript to the Service Worker and a request from the Service Worker to the server. This will always happen unless the service worker has the response cached and does not need to check the server for an update.

Upvotes: 11

Varun Goel
Varun Goel

Reputation: 475

Does not seems the right way to initialize service worker in Next.js.You may need to look into next-pwa plugin to do it right.Here is the tutorial PWA with Next.js

Upvotes: 0

Related Questions