kit icon indicating copy to clipboard operation
kit copied to clipboard

Expose `$env/static/public` module to service workers

Open Rich-Harris opened this issue 2 years ago • 6 comments

Describe the problem

#5663 adds new modules with environment variables. In some cases it's useful to be able to access those env vars in a service worker.

It only makes sense to expose public environment variables for obvious reasons, so $env/static/private and $env/dynamic/private are out.

$env/dynamic/public could potentially be useful, but I have no idea how it would work. I think 'service workers can only use public environment variables that are known at build time' is a reasonable restriction.

Describe the proposed solution

Expose $env/static/public to service workers.

Alternatives considered

No response

Importance

nice to have

Additional Information

No response

Rich-Harris avatar Jul 26 '22 16:07 Rich-Harris

Rich, is it possible to expose dynamic vars to the service worker by sending a message to it containing the variables during the client initialization? If it happens then, it'd be guaranteed to preempt any messages sent by user code, right?

No, the service worker has to initialise before it's possible to send messages to it

Rich-Harris avatar Jul 31 '22 01:07 Rich-Harris

I just ran into this issue while adding a check to ignore cache for requests going to our proxy, whose url is set using a static public env var

For now I could workaround with our project but would be nice to see this feature implemented for other cases where workarounds might not be possible :+1:

Chooks22 avatar Sep 29 '22 16:09 Chooks22

This is REALLY NEEDED.

Today I updated to kit 1.0.3 coming from "@sveltejs/kit": "1.0.0-next.394" and the build is not replacing these anymore:

  • service-worker.ts:
registerRoute(
  new NavigationRoute(createHandlerBoundToURL("/index.html"), {
    denylist: [new RegExp(import.meta.env.VITE_SOME_ENV + "/")],
  })
);

VITE_SOME_ENV is in .env file.

Why?

Is there a work-around until this issue is closed (done)?

UPDATE: I was wrong. This is working using the VITE_ prefix. Not the Kit's defualt one PUBLIC_.

I think I need to find a work-around for now.

frederikhors avatar Jan 06 '23 12:01 frederikhors

@frederikhors

You are correct -- we don't touch Vite's env var handling, so that's a good escape hatch until we get this working. Keep in mind that it doesn't have the public/private protections of Kit's env vars -- don't accidentally expose secrets! 😁

I just ran into this issue as well. +1 from me.

kyllerss avatar Jun 10 '23 17:06 kyllerss