Repository navigation
Description
TL;DR
- Problem: Workers ignore .env at runtime, and monorepo cwd differences create missing env/bindings.
- Solution: one root .dev.vars + explicit Wrangler bindings (vars + secrets) + a readDevVars helper for Node tools.
- Scope: Cloudflare-deployed templates only (wrangler/alchemy).
Scope (Cloudflare templates only)
- Applies only when web/server deploy targets are Cloudflare (wrangler/alchemy).
- Not intended for node-only or other runtimes.
Context
Cloudflare Workers do NOT read .env files at runtime. They only receive environment variables
through explicit bindings injected by Wrangler or Alchemy. In a monorepo, commands run from
different directories (apps/web vs apps/server), which changes where env files are discovered.
This leads to inconsistent env injection across dev, build, and deploy.
Bindings vs env (quick mental model)
- Worker runtime: values come from Wrangler bindings (env).
.envfiles are ignored. - Node tooling: values come from process.env (dotenv, readDevVars, DEV_VARS).
Problem variants (from existing issues)
- [BUG] dotenv fails to load backend env when auth/db run inside SvelteKit SSR. #651 [BUG] dotenv fails to load backend env when auth/db run inside SvelteKit SSR. #651
SSR runs in apps/web and only sees web envs, so backend secrets are missing and auth/db fail. - No database connection string was provided to
neon(). Perhaps an environment variable has not been set? #607 No database connection string was provided toneon(). Perhaps an environment variable has not been set? #607
Web builds fail with missing DB env because the build runs from web and never sees server env. - Alchemy + Better Auth not reading in env + minor type issue #697 Alchemy + Better Auth not reading in env + minor type issue #697
Workers do not auto-inherit bindings; shared packages imported by web still need server bindings. - Error Please provide required params for D1 HTTP driver: #702 Error Please provide required params for D1 HTTP driver: #702
D1 HTTP driver errors show required Cloudflare params missing; env assumptions are unclear. - BUG: .env files needs moving from apps folder to packages/env #761 BUG: .env files needs moving from apps folder to packages/env #761
Bun auto-loads env files; pnpm/npm do not, so the same template behaves differently. - Injecting env (4) from ../../apps/server/.env -- tip: 🔐 prevent building .env in docker: #636 Injecting env (4) from ../../apps/server/.env -- tip: 🔐 prevent building .env in docker: #636
BUG: drizzle env loading #765 BUG: drizzle env loading #765
Drizzle configs with per-app .env paths are brittle and break in monorepos.
Verified behaviors (Wrangler 4.56.0 local test)
- --env-file bypasses .dev.vars auto-load. If a key is missing from the env-file, it is not
sourced from .dev.vars. Wrangler prints "Using vars defined in " and does not
mention .dev.vars in this case. - .dev.vars. is NOT merged with base .dev.vars. With --env staging, only
.dev.vars.staging loads (keys present only in .dev.vars are missing). - Multiple -c configs in
wrangler devonly expose the first Worker over HTTP. The second
config is not reachable via its own port. This matches the docs warning: multi-config dev
is experimental and secondary Workers are accessed only via service bindings.
Root causes
- Env loading is cwd-dependent (apps/web vs apps/server).
- Workers only get vars via Wrangler/Alchemy bindings, not arbitrary .env files.
- Tooling differences (bun vs pnpm/npm) change env loading behavior.
- Alchemy throws early if required env is missing (before it writes wrangler config).
Proposal (Cloudflare templates only)
- Use a single repo-root .dev.vars for local development.
- Always pass it to Workers via Wrangler so web + server share identical bindings.
- Add a readDevVars helper that merges .dev.vars, DEV_VARS, and process.env.
This keeps CI working without a file on disk. - Keep wrangler.jsonc values as safe placeholders; inject real values at deploy time.
- If using Alchemy, load .dev.vars before any alchemy.env access and pass process.env
into bindings so config generation does not fail.
Clarifications / implementation details
- Wrangler env resolution (observed 4.56.0): if you pass --env-file, Wrangler does not
auto-load .dev.vars. If you want .dev.vars, pass it explicitly (it is dotenv-compatible). - Env file path resolution (observed 4.56.0): with
--config apps/server/wrangler.jsonc --env-file .dev.vars,
Wrangler resolves the env file relative to the config path, not the repo root. Missing files are silent.
Use an absolute path (or a path relative to the config file) to point at the repo-root .dev.vars. - Environment-specific dev vars: .dev.vars. is exclusive (no merge with .dev.vars).
- Node-only tooling: drizzle-kit and other CLI tools run in Node, not Workers; they must
explicitly load .dev.vars (or DEV_VARS). Vite is a special case: when using the official
@cloudflare/vite-plugin, it already loads .dev.vars/.env for vite dev. If not using that
plugin, you still need explicit loading. - Deploy nuance: secrets should remain secrets (wrangler secret put), vars should be injected
via wrangler deploy --var; optionally auto-detect workers.dev URL for CORS/BETTER_AUTH_URL if
custom domains are not provided. - Runtime access: inside Worker code, prefer
envfrom cloudflare:workers instead of process.env.
process.env is empty unless nodejs_compat_populate_process_env is enabled. - Alchemy is third-party, not Cloudflare. It reads process.env / alchemy.secret and does not
auto-load .dev.vars, so load dotenv yourself before alchemy.env access. - Env names: use the exact variable names defined in the template env package (server/web) to
avoid mismatches (some templates use singular CORS_ORIGIN, others CORS_ORIGINS).
Adoption steps (local dev → CI → deploy)
- Move required vars into repo-root .dev.vars.
- Update dev scripts to pass --env-file .dev.vars for each Worker.
- Add readDevVars to Node-only tooling (drizzle-kit, auth CLI, any scripts).
- Keep wrangler.jsonc values as placeholders; inject vars/secrets at deploy time.
Why this fixes each issue
- [BUG] dotenv fails to load backend env when auth/db run inside SvelteKit SSR. #651/No database connection string was provided to
neon(). Perhaps an environment variable has not been set? #607: Cwd differences no longer matter because Wrangler always loads the same root file. - Alchemy + Better Auth not reading in env + minor type issue #697: Both workers get the same bindings from the shared env file; fewer missing-binding surprises.
- BUG: .env files needs moving from apps folder to packages/env #761: Works the same on bun/pnpm/npm because env is passed explicitly to Wrangler.
- Error Please provide required params for D1 HTTP driver: #702: Clarifies that D1/Alchemy rely on explicit bindings, not cwd dotenv.
- Injecting env (4) from ../../apps/server/.env -- tip: 🔐 prevent building .env in docker: #636/BUG: drizzle env loading #765: Removes per-app env paths; one shared source of truth.
Examples
Local dev (two Workers, two HTTP ports)
Option A: two terminals
wrangler dev -c apps/server/wrangler.jsonc --port 3000 --env-file .dev.vars
wrangler dev -c apps/web/wrangler.jsonc --port 3001 --env-file .dev.vars
Option B: one command (requires a runner like concurrently)
concurrently \
"wrangler dev -c apps/server/wrangler.jsonc --port 3000 --env-file .dev.vars" \
"wrangler dev -c apps/web/wrangler.jsonc --port 3001 --env-file .dev.vars"
Note: wrangler dev -c a -c b is experimental and only the first Worker is exposed over HTTP.
The second Worker is reachable only via service bindings.
.repo-root/.dev.vars
VITE_SERVER_URL=http://localhost:3000
CORS_ORIGIN=http://localhost:3001
BETTER_AUTH_URL=http://localhost:3001
BETTER_AUTH_SECRET=your-secret
readDevVars helper (scripts/env.mjs)
import { existsSync, readFileSync } from "node:fs";
import dotenv from "dotenv";
export function readDevVars(path, envName) {
const envPath = envName && existsSync(`${path}.${envName}`)
? `${path}.${envName}`
: path;
const fileEnv = existsSync(envPath) ? dotenv.parse(readFileSync(envPath, "utf8")) : {};
const devVarsEnv = process.env.DEV_VARS ? dotenv.parse(process.env.DEV_VARS) : {};
return { ...fileEnv, ...devVarsEnv, ...process.env };
}
Deploy injection (explicit)
wrangler secret put BETTER_AUTH_SECRET --config apps/server/wrangler.jsonc
wrangler deploy --config apps/server/wrangler.jsonc \
--var CORS_ORIGIN:... --var BETTER_AUTH_URL:... --var R2_ACCOUNT_ID:...
Auto-population example (minimal)
#!/usr/bin/env node
import { spawnSync } from "node:child_process";
import { randomBytes } from "node:crypto";
import { readDevVars } from "./env.mjs";
const env = readDevVars(".dev.vars", "production");
const webConfig = "apps/web/wrangler.jsonc";
const apiConfig = "apps/server/wrangler.jsonc";
const envName = "production";
const putSecret = (name, value) => {
const res = spawnSync(
"wrangler",
["secret", "put", name, "--config", apiConfig, "--env", envName],
{ input: value, stdio: ["pipe", "inherit", "inherit"] }
);
if (res.status !== 0) throw new Error(`secret put failed: ${name}`);
};
if (!env.BETTER_AUTH_SECRET) {
putSecret("BETTER_AUTH_SECRET", randomBytes(32).toString("base64"));
} else {
putSecret("BETTER_AUTH_SECRET", env.BETTER_AUTH_SECRET);
}
const webDeploy = spawnSync(
"wrangler",
["deploy", "--config", webConfig, "--env", envName, "--json"],
{ encoding: "utf8" }
);
if (webDeploy.status !== 0) throw new Error("web deploy failed");
const webUrl = JSON.parse(webDeploy.stdout)?.url;
const cors = env.CORS_ORIGIN ?? webUrl;
const authUrl = env.BETTER_AUTH_URL ?? webUrl;
const apiDeploy = spawnSync(
"wrangler",
[
"deploy",
"--config",
apiConfig,
"--env",
envName,
"--var",
`CORS_ORIGIN:${cors}`,
"--var",
`BETTER_AUTH_URL:${authUrl}`,
],
{ stdio: "inherit" }
);
if (apiDeploy.status !== 0) throw new Error("api deploy failed");
Alchemy preload
import { readDevVars } from "../../scripts/env.mjs";
Object.assign(process.env, readDevVars("../../.dev.vars"));
Tradeoffs / gotchas
- Workers still require explicit bindings; shared packages importing server env may still need
bindings on web in edge cases, but now they come from the same source. - This is Cloudflare-specific and should not affect non-Cloudflare templates.
Question
Should this become the default for Cloudflare-deployed templates + docs, or remain opt-in?
Activity
feat(cli,template-generator,types): implement 6 issue-based plans
AmanVarshney01 commentedon Oct 21, 2026
The per-app env setup this proposes was replaced by Alchemy v2 (#1144) and Varlock with native Cloudflare bindings (#1224). If you still see this on the latest version, please reopen or open a new issue with the details.