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

Environment Variables: In development, envars from .env are not loaded to worker when running vite dev #142

Open
dthyresson opened this issue Mar 2, 2025 · 1 comment

Comments

@dthyresson
Copy link

dthyresson commented Mar 2, 2025

Environment variables are available on the env parameter passed to your Worker's fetch event handler.

However, when running vite dev locally, any .env isn't loaded and one must define them in wrangler.toml. I suspect the issue is likely occurring because:

  • When running with wrangler, the environment variables from wrangler.toml are automatically injected into your worker's environment. Also, according to the docs and .env will be loaded, too.

But we don't run wrangler dev we run vite dev.

  • However, when running with Vite in development mode, these variables aren't automatically loaded from .env and set to the same env parameter as Vite has its own environment variable handling system.

Having to define envars in toml is an issue because I don't want to check into any public repo my secrets like API keys etc.

To reproduce

  • define an envar in wrangler.toml
  • define its type in worker-configuration.d.ts
  • use in a worker or in a server component/function
  • remove from toml
  • add to .env
  • try it
  • envar will be undefined
@dthyresson
Copy link
Author

dthyresson commented Mar 2, 2025

After some reading, looks like with Cloudflare and Vite, one defines the envars in .dev.vars.

See: https://developers.cloudflare.com/workers/configuration/secrets/#local-development-with-secrets

Now, when running pnpm dev:

> while true; do NODE_ENV=development vite dev; [ $? -eq 0 ] || break; done

Using vars defined in .dev.vars. <<<<<<----- this is new
Generating wrangler types...

  VITE v6.1.1  ready in 1689 ms

  ➜  Local:   http://localhost:2332/
  ➜  Network: use --host to expose
  ➜  press h + enter to show help

vars are loaded and don't need to define in toml.

Perhaps, this just need documentation?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant