Skip to content

Cloudflare templates: consistent env injection via root .dev.vars + explicit Wrangler bindings #787

Closed as not planned

Description

@jroth1111

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). .env files are ignored.
  • Node tooling: values come from process.env (dotenv, readDevVars, DEV_VARS).

Problem variants (from existing issues)

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 dev only 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

  1. Env loading is cwd-dependent (apps/web vs apps/server).
  2. Workers only get vars via Wrangler/Alchemy bindings, not arbitrary .env files.
  3. Tooling differences (bun vs pnpm/npm) change env loading behavior.
  4. Alchemy throws early if required env is missing (before it writes wrangler config).

Proposal (Cloudflare templates only)

  1. Use a single repo-root .dev.vars for local development.
  2. Always pass it to Workers via Wrangler so web + server share identical bindings.
  3. Add a readDevVars helper that merges .dev.vars, DEV_VARS, and process.env.
    This keeps CI working without a file on disk.
  4. Keep wrangler.jsonc values as safe placeholders; inject real values at deploy time.
  5. 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 env from 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)

  1. Move required vars into repo-root .dev.vars.
  2. Update dev scripts to pass --env-file .dev.vars for each Worker.
  3. Add readDevVars to Node-only tooling (drizzle-kit, auth CLI, any scripts).
  4. Keep wrangler.jsonc values as placeholders; inject vars/secrets at deploy time.

Why this fixes each issue

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

  1. AmanVarshney01 commented on Oct 21, 2026

    @AmanVarshney01
    Owner

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions