Cloudflare worker env var problem
It's impossible to get public env var from client when it's on cloudflare worker? Like if I have a env var call
VITE_BACKEND_URL, it's impossible to get it from client?13 Replies
robust-apricot•3mo ago
can you share a complete reproducer project please?
we do have a cloudflare example now in the router repo so you might just use this as a basis
rising-crimsonOP•3mo ago
I've seen that example, but it seems like it just demonstrates getting env var by calling server function, but not directly gets it from the client (i.e. retrieve it from process.env or import.meta.env)
rising-crimsonOP•3mo ago
The project I'm working on is https://github.com/normalid-awa/ipsc-scoreboard but it might be a bit messy as I'm struggling on this issue
GitHub
GitHub - normalid-awa/ipsc-scoreboard
Contribute to normalid-awa/ipsc-scoreboard development by creating an account on GitHub.
rising-crimsonOP•3mo ago
My current direction is to inject the env var in to
globalThis object on client but I don't really know where should put the code, so that it runs on the first place before anything uses env var (api services initializations).robust-apricot•3mo ago
where is the env var coming from?
rising-crimsonOP•3mo ago
Defined in cloudflare dashboard, the env var is available on server, but not on client
robust-apricot•3mo ago
so is it accesible on the server then?
rising-crimsonOP•3mo ago
Yes, all env var is accesible on server, but not on client
robust-apricot•3mo ago
makes sense though , right?
you need to explicitly make them available on the client
if you dont know them at build time, you can't integrate it statically with the client build
so you could put it on the router context by using routers dehydrate/hydrate methods
rising-crimsonOP•3mo ago
I would try this, thanks for the advice
Well..., I've made a stupid mistake. It turns out vite bundle all env var in build time, and replace every
import.meta.env to the value it gets in build time, but cloudflare separate build time env var and runtime env var in to two settings, so setting the runtime env var can't do anything to the pre-bundled env var.robust-apricot•3mo ago
so it's working now?
rising-crimsonOP•3mo ago
Yep
The solution is to set the env var in build setting, not the runtime section
rising-crimsonOP•3mo ago

