T
TanStack2w ago
harsh-harlequin

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
absent-sapphire
absent-sapphire2w 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
harsh-harlequin
harsh-harlequinOP2w 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)
harsh-harlequin
harsh-harlequinOP2w 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.
harsh-harlequin
harsh-harlequinOP2w 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).
absent-sapphire
absent-sapphire2w ago
where is the env var coming from?
harsh-harlequin
harsh-harlequinOP2w ago
Defined in cloudflare dashboard, the env var is available on server, but not on client
absent-sapphire
absent-sapphire2w ago
so is it accesible on the server then?
harsh-harlequin
harsh-harlequinOP2w ago
Yes, all env var is accesible on server, but not on client
absent-sapphire
absent-sapphire2w 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
harsh-harlequin
harsh-harlequinOP2w 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.
absent-sapphire
absent-sapphire2w ago
so it's working now?
harsh-harlequin
harsh-harlequinOP2w ago
Yep The solution is to set the env var in build setting, not the runtime section
harsh-harlequin
harsh-harlequinOP2w ago
No description
No description

Did you find this page helpful?