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

Service-worker not working at all #19944

Closed
Jensxy opened this issue Mar 28, 2023 · 2 comments
Closed

Service-worker not working at all #19944

Jensxy opened this issue Mar 28, 2023 · 2 comments

Comments

@Jensxy
Copy link

Jensxy commented Mar 28, 2023

Environment

  • Operating System: Windows_NT
  • Node Version: v16.16.0
  • Nuxt Version: 3.1.2
  • Nitro Version: 2.1.1
  • Package Manager: npm@9.6.2
  • Builder: vite
  • User Config: debug, ssr, imports, typescript, vite, css, modules, runtimeConfig, i18n
  • Runtime Modules: @nuxtjs/i18n@8.0.0-beta.10, @vueuse/nuxt@9.13.0, @pinia/nuxt@0.4.6
  • Build Modules: -

Reproduction

Service-Worker:

const tokenChannel = new BroadcastChannel("token_channel");
var token = "";
var refreshToken = "";

let baseURL = "";
if (location.host === "localhost:8080") {
  baseURL = "http://localhost/";
}

tokenChannel.onmessage = (event) => {
  token = event.data.token;
  refreshToken = event.data.refresh_token;
};

self.addEventListener("fetch", (event) => {
  event.respondWith(customHeaderRequestFetch(event));
});

function customHeaderRequestFetch(event) {
  let url = event.request.url;
  var headers = {};

  if (token != null && url.includes("/files-service/file/")) {
    url = url.replaceAll(":8080", "");
    headers = { ...event.request.headers, Authorization: "Bearer " + token };
  } else {
    headers = { ...event.request.headers };
  }

  const newRequest = new Request(url, {
    headers: headers,
    method: event.request.method,
    body: event.request.body,
    mode: "cors",
    credentials: "omit",
    cache: event.request.cache,
    redirect: event.request.redirect,
    referrer: event.request.referrer,
    integrity: event.request.integrity,
    duplex: "half",
  });
  return fetch(newRequest, { duplex: "half" });
}

app.vue
navigator.serviceWorker.register("/service-worker.js");

api-client.js

import TokenService from "@/services/token.service";
import { $fetch } from "ofetch";
import nProgress from "nprogress";

const instance = $fetch.create({
  onRequest: async ({ options }) => {
    nProgress.start();
    const token = TokenService.getLocalAccessToken();
    if (token) {
      options.headers = {
        ...options.headers,
        Authorization: `Bearer ${token}`,
      };
    } else {
      options.headers = {
        ...options.headers,
      };
    }
  },
  onRequestError({ request, options, error }) {
    nProgress.done();
  },
  onResponse({ request, response, options }) {
    nProgress.done();
    return response._data;
  },
  onResponseError: async ({ response, options }) => {
    if (response?.status === 401) {
      const refreshToken = TokenService.getLocalRefreshToken();
      if (!refreshToken) return localLogout();

      const { data, error } = await useFetch("/portal-service/refresh-token", {
        ...options,
        baseURL: useRuntimeConfig().config.public.baseUrl,
        method: "POST",
        body: {
          refresh_token: refreshToken,
        },
      });

      if (data?.token) {
        TokenService.updateLocalAccessToken(data.token);
        TokenService.updateLocalRefreshToken(data.refresh_token);
        return api(options);
      } else {
        return localLogout();
      }
    } else {
      throw response;
    }
  },
});

export default async (endpoint, options) => {
  const config = useRuntimeConfig();
  const baseURL = config.public.baseUrl;

  options = { ...options, baseURL };
  return await instance
    .raw(endpoint, options)
    .then((response) => {
      return response._data;
    })
    .catch(async (error) => {
      console.log(error);
      if (
        error.response?.status === 401 &&
        TokenService.getLocalRefreshToken()
      ) {
        const response = await instance.raw(endpoint, options);
        return response;
      }

      return error.response;
    });
};

Describe the bug

I migrated from Vue 3 to Nuxt 3 and now my service worker is not working anymore. The file service-worker.js is located in the public directory. However, when I send a request that needs a token, my API requests do not work anymore. If I do not register the service-worker, then everything works fine.

Additional context

No response

Logs

No response

@vinayakkulkarni
Copy link

There seems to be a bug with workers with Vite 4.2.1 – vitejs/vite#12611 (comment)

@github-actions
Copy link
Contributor

github-actions bot commented Aug 7, 2023

This issue was closed because it was open for 7 days without a reproduction.

@github-actions github-actions bot closed this as not planned Won't fix, can't repro, duplicate, stale Aug 7, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants