Serving service worker file in src in Vite dev mode

55 views Asked by At

I'm creating a Vite, React project and using FCM.

I have a src/firebase-messaging-sw.js service worker file that accesses environment variables via import.meta. The FCM SDK attempts to fetch the firebase-messaging-sw.js file at the root level via GET http://localhost:5173/firebase-messaging-sw.js.

I tried configuring Vite's dev server proxy to serve src/firebase-messaging-sw.js for requests to /firebase-messaging-sw.js. Now I'm getting Uncaught SyntaxError: Cannot use 'import.meta' outside a module (at firebase-messaging-sw.js:1:8) for the GET http://localhost:5173/firebase-messaging-sw.js request.

How can I fix this while keeping the firebase-messaging-sw.js file in the src folder?

export default defineConfig({
  // ...
  server: {
    proxy: {
      "/firebase-messaging-sw.js": {
        target: "http://localhost:5173/",
        changeOrigin: true,
        rewrite: (path) => (
          path.replace(
            /^\/firebase-messaging-sw.js/,
            "/src/firebase-messaging-sw.js"
          );
        ),
      },
    },
  },
  build: {
    target: "es2022",
    rollupOptions: {
      input: {
        "main": "./index.html",
        "firebase-messaging-sw": "./src/firebase-messaging-sw.js",
      },
      output: {
        entryFileNames: (chunkInfo) => {
          return chunkInfo.name === "firebase-messaging-sw"
            ? "[name].js" // Put FCM service worker in root
            : "assets/[name]-[hash].js"; // Other main app JS in `assets/`
        },
      },
    },
  },
}

There's a similar reddit posting here.

It seems most Firebase API keys are safe to hard code and env variables will ultimately still be exposed in the client. But I'd still like to use env variables instead of hard coding to avoid saving the values in the repo.

0

There are 0 answers