Skip to content

fix(env): reload changed .env values when vite dev restarts - #5041

Merged
james-elicx merged 7 commits into
mainfrom
alcora/run_5g3t195j3m56223k6w26/fix/fix
Dec 2, 2026
Merged

james-elicx merged 7 commits into
mainfrom
alcora/run_5g3t195j3m56223k6w26/fix/fix

Conversation

@alcora-dev

@alcora-dev alcora-dev Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #5040

When a .env* file changes during vite dev, Vite restarts the server, and import.meta.env, NEXT_PUBLIC_* defines and server-side process.env should show the file's new value. That's what plain Vite and next dev do. Vinext kept the value it read at startup until the dev server was stopped and started again.

Root cause

On a restart, Vite runs the vinext:config hook again (packages/vinext/src/index.ts), and it calls loadDotenv() a second time. loadDotenv() (packages/vinext/src/config/dotenv.ts) skips every key already in process.env, so it can't apply the files' variables-set-before-the-load rule. It also skips the values it wrote itself on startup (from the module-load early pass, the config hook or the legacy vinext dev proxy in cli.ts), so the old value stays. Vite's loadEnv then prefers process.env over the file, so import.meta.env.VITE_* keeps the old value too.

@next/env 16.2.7 avoids this: loadEnvConfig snapshots process.env on its first call, and on every reload calls replaceProcessEnv(initialEnv) before reading the files again. That way values from an earlier load never block the new ones.

Fix

  • loadDotenv() now records the values it writes into the real process.env. A new unloadDotenv() removes the ones that still hold the value that was loaded.
  • The config hook unloads all of them when it runs again in a dev server (serve, not preview) after an earlier config-hook load in the same process, then loads the current envDir. That's what a restart is. It covers values from the early pass, the legacy vinext dev proxy and the previous run. It also covers a restart that changes envDir, sets it to false, or changes root.
  • When the first config hook finds that the early pass read a different directory than the resolved envDir, it now drops the early values with unloadDotenv() instead of deleting them directly. The tracker then forgets them, so a value app code assigns later isn't taken for a dotenv value and deleted on a restart.
  • Dotenv is process-wide, as with @next/env's single snapshot. When several dev servers run in one Node process, they share one set of dotenv values, and a restart of any of them replaces it with its own envDir's. The maintainers chose this over per-project ownership tracking.

Deliberately unchanged:

  • The first config-hook pass at startup. The early pass's values stay as they are, as tests/client-global-define.test.ts expects.
  • vite build, preview and vinext start, which load once.
  • Variables set before vinext loaded, and values app code changed at runtime. @next/env restores its whole snapshot instead, which would also discard other plugins' and Vite's own process.env writes. Here, only what loadDotenv wrote is removed.
  • A loaded key that app code deleted at runtime is loaded again from the file on a restart, as @next/env does when it restores its snapshot and reloads.

Behaviour

Scenario (vite dev, after a .env.development change and restart) Next.js 16.2.7 (next dev) Before After
A changed value (VITE_*, NEXT_PUBLIC_*, server process.env) New value Old value New value
A key removed from the file Unset Old value stays Unset
A key also set in the shell before start Shell value Shell value Shell value
A loaded key app code reassigned at runtime Reset to the file's value Runtime value Runtime value (kept, see above)
A loaded key app code deleted at runtime Loaded from the file again Stays deleted Loaded from the file again
envDir changed in vite.config (restart) — (no envDir in Next.js) Old envDir's values shadow the new ones New envDir's values only
envDir changed to false (restart) — Old values stay Removed
Another dev server in the same process, when one restarts One process-wide env Keeps its values Shares the restarting server's values (process-wide)
vite build / vinext start (single load) — Unchanged Unchanged

The Next.js column comes from the loadEnvConfig, replaceProcessEnv and processEnv source in node_modules/@next/env 16.2.7. I didn't run next dev.

Tests

  • tests/dotenv-dev-restart.test.ts (new, integration project) and fixture tests/fixtures/dotenv-dev-restart:
    • Starts a dev server with VITE_DEMO_LABEL=first in .env.development, changes the file to second, calls server.restart(), then checks server.config.env, process.env and the rendered page.
    • Starts with .env.development in the root, restarts with envDir: "other-env" (set on server.config.inlineConfig, which Vite's restart reuses), then with envDir: false. Checks that the old envDir's values are gone and the new one's are served.
    • Both fail on the base with expected 'first' to be 'second'. The tests write .env.development and other-env/ at runtime because .env.* is gitignored, and remove them afterwards.
  • tests/dotenv.test.ts: a new unloadDotenv case. It checks that a reload drops a key removed from the file, and that a value set before the load or changed at runtime is kept. On the base it fails with unloadDotenv is not a function.
  • tests/client-global-define.test.ts: the existing "replaces the CLI's early root .env values with a configured envDir's" case now goes on to assign a dropped early key at runtime, run the config hook again as a dev restart, and check that the assignment stays. Without the change it fails with expected undefined to be 'from-root'.
  • The fixture's importer is added to pnpm-lock.yaml, and the test is added to the unit exclude and integration include in vite.config.ts.

Validation

  • vp test run tests/dotenv-dev-restart.test.ts: both cases fail with the base source (expected 'first' to be 'second') and pass with the fix.
  • vp test run tests/dotenv.test.ts: the unloadDotenv case fails with the base source (unloadDotenv is not a function) and passes with the fix.
  • vp test run tests/client-global-define.test.ts: the extended early-pass case fails without the early-pass change (expected undefined to be 'from-root') and passes with it.
  • vp test run tests/dotenv-dev-restart.test.ts tests/dotenv.test.ts tests/client-global-define.test.ts: 49 passed.
  • vp check: no format, lint or type errors.
  • vp install: lockfile unchanged apart from the new importer.

Performance

The new work only runs in the Vite config hook: a pass over the recorded keys on a dev-server restart. Nothing changes per request or at startup.

Known limitations

  • Several dev servers in one Node process share one set of dotenv values (see Fix).
  • If a restart fails after vinext's config hook (a later plugin's hook throws), Vite keeps the old server running, but process.env already holds the edited files' values while that server's import.meta.env and defines keep the old ones. Server-side reads see the new values, as in next dev. Next.js reloads process.env in place (loadEnvConfig with forceReload: true in setup-dev-bundler.js) before it updates its defines, and doesn't roll the reload back. Vite has no public hook that says whether a restart succeeded.
  • On a restart, Vite re-evaluates vite.config.* before the config hook runs, so code in the config file that reads process.env still sees the previous values for that one evaluation. The early pass that serves config evaluation runs only once per process, at module load.

@pkg-pr-new

pkg-pr-new Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@vinext/cloudflare

npm i https://pkg.pr.new/@vinext/cloudflare@5041

create-vinext-app

npm i https://pkg.pr.new/create-vinext-app@5041

@vinext/types

npm i https://pkg.pr.new/@vinext/types@5041

vinext

npm i https://pkg.pr.new/vinext@5041

@cloudflare/workers-response-store

npm i https://pkg.pr.new/@cloudflare/workers-response-store@5041

commit: 5d4f228

@github-actions

github-actions Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Performance benchmarks

Compared 5d4f228 against base ba17aac using alternating same-runner rounds. Next.js was unchanged and skipped.

0 improved · 0 regressed · 7 within ±1.5%

Scenario Framework Baseline Current Change
Client bundle size (gzip) vinext 157.7 KB 157.7 KB ⚫ 0.0%
Client entry size (gzip) vinext 145.9 KB 145.9 KB ⚫ 0.0%
Dev server cold start vinext 2.95 s 2.98 s ⚫ +1.1%
Dev server cold start (large Pages Router app) vinext 25.18 s 25.13 s ⚫ -0.2%
Production build time vinext 3.95 s 3.96 s ⚫ +0.1%
RSC entry closure size (gzip) vinext 155.5 KB 155.5 KB ⚫ -0.0%
Server bundle size (gzip) vinext 268.5 KB 268.5 KB ⚫ -0.0%

View detailed results and traces

🟢 improvement · 🔴 regression · ⚫ change below 1.5% · paired base/head

@github-actions

github-actions Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor
Example Preview Production Original
app-router-cloudflare preview production
pages-router-cloudflare preview production
app-router-playground preview production original
realworld-api-rest preview production
nextra-docs-template preview production
benchmarks preview production
hackernews preview production original
response-store-demo preview production
workers-cache preview production
kv preview production
static-assets-cache preview production
static-assets-pages preview production
static-assets-pages-i18n preview production
static-export preview production
web preview production

@alcora-dev

alcora-dev Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

/bigbonk review for issues
Please review exact head fdd2715f485238254dd9b15e4280f11adb4775be without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

Comment thread packages/vinext/src/index.ts Resolved
Comment thread packages/vinext/src/config/dotenv.ts Outdated
for (const [root, loaded] of processEnvLoads) {
if (!matchesRoot(root)) continue;
for (const [key, value] of loaded) {
if (process.env[key] === value) Reflect.deleteProperty(process.env, key);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Treat deletion as a runtime mutation too. After .env loads KEY=file, app code can run delete process.env.KEY; on restart this comparison is false, the tracking entry is discarded, and the following loadDotenv() restores KEY=file. That violates the helper rule that a value changed since loading stays and differs from the reassignment case tested below. Retain a tombstone or blocked key for deleted tracked values so reload does not restore it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Declined: this would diverge from Next.js. @next/env (16.2.7, loadEnvConfig → replaceProcessEnv(initialEnv) then processEnv) restores its startup snapshot, which doesn't have the key, and reads the files again, so a key that app code deleted comes back from .env on reload. The PR does the same. Keeping a reassigned value is the one deliberate difference, so other plugins' and Vite's process.env writes survive. I added a row for the deleted-key case to the PR's behaviour table.

@ask-bonk

ask-bonk Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Review: 2 findings.

Posted 2 inline comments. Targeted dotenv tests pass; no files were modified.

github run

@alcora-dev

alcora-dev Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

/bigbonk review for issues
Please review exact head f0da79b497b44a77a3d8c637a5d9426cac380a9d without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

Comment thread packages/vinext/src/index.ts Outdated
}
const preserveSymlinks = config.resolve?.preserveSymlinks;
const resolvedEnvDir = envDir ? resolveProjectDir(envDir, preserveSymlinks) : undefined;
if (configHookEnvDirs.has(root)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Track the previous config lifecycle independently of the newly resolved root. If a restart changes config.root (or changes preserveSymlinks so the same root resolves to a different identity), this lookup misses the old entry, so the old root’s dotenv values remain in process.env and shadow the new root’s files. This is reproducible by changing server.config.inlineConfig.root from a project whose .env contains VALUE=from-a to one containing VALUE=from-b: after restart(), the resolved root is B but process.env.VALUE is still from-a.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Declined, listed under Known limitations. From the config hook, a restart that changes root (or preserveSymlinks) looks exactly like a second dev server for another project in the same process, and that server's values must not be dropped (the isolation asked for in the other thread). Vite exposes no public way to link the new config to the server it replaces, and old values staying is what happened before this PR.

Comment thread packages/vinext/src/config/dotenv.ts Resolved
@ask-bonk

ask-bonk Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Since last review: 2 resolved, 0 still open, 2 new.

Posted 2 inline findings. All 49 targeted tests pass; worktree unchanged.

github run

@alcora-dev

alcora-dev Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

/bigbonk review for issues
Please review exact head 1623edf584f692976e0a716fff12946696b8dd57 without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

Comment thread packages/vinext/src/index.ts Resolved
@ask-bonk

ask-bonk Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Since last review: 2 resolved, 0 still open, 1 new.

Posted 1 inline finding. All 38 targeted tests pass; worktree unchanged.

github run

@alcora-dev

alcora-dev Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

/bigbonk review for issues
Please review exact head 4ab039f40aa790d5e5193caecffc39eeb0ccc1a4 without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

Comment thread packages/vinext/src/index.ts Resolved
Comment thread packages/vinext/src/index.ts Outdated
// open server still uses that directory.
let previousEnvDir = configHookEnvDirs.get(root)?.envDir;
for (const [otherRoot, other] of configHookEnvDirs) {
if (otherRoot !== root && other.envDir === previousEnvDir) previousEnvDir = undefined;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Protect overlapping keys used by active servers even when their envDirs differ. If roots A and B use separate directories that both define KEY=shared, A writes the global value and B's loadDotenv() skips it. When A switches to envDir: false, this exact-directory check does not recognize B as an owner, and unloadDotenv() deletes process.env.KEY while B remains open. I reproduced that result with two listening servers. Ownership needs to account for loaded keys (or otherwise restore active roots), not only equal directory paths.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Declined, per the maintainers' decision (618e4ec4): dotenv is now process-wide, like @next/env. Servers in one process share one set of dotenv values, and a restart of any of them replaces that set with its own envDir's. Per-key ownership across live servers isn't tracked. This is listed under Known limitations in the PR.

Comment thread packages/vinext/src/index.ts Resolved
@ask-bonk

ask-bonk Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Since last review: 1 resolved, 0 still open, 3 new.

Posted 3 inline findings. All 39 targeted tests pass; worktree unchanged.

github run

@alcora-dev

alcora-dev Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

/bigbonk review for issues
Please review exact head 618e4ec4b4c25b07a9bb04be6a8e808d95b4fb1f without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

  • Following the maintainers' decision, dotenv reloading is now process-wide, like @next/env's single snapshot (618e4ec4). On a dev-server restart vinext removes every value it loaded from dotenv files and loads the restarting server's envDir. The per-root ownership map, owner tokens and closeServer hook are gone, and several dev servers in one process now share one set of dotenv values (listed under Known limitations). As a side effect, a restart that changes root now works too.

// pass's and the CLI's), or it would shadow the new values as if set
// before vinext loaded. Dotenv is process-global: other dev servers
// in this process share what this one loads.
unloadDotenv();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Preserve the previous dotenv state until the replacement server has configured successfully. Vite builds the replacement inside a try/catch and, if any later config hook throws, logs server restart failed and keeps the old server running (node_modules/vite/dist/vite/node/chunks/node.js:30521-30535). By this line, however, vinext has already removed the old values and loaded the edited file. A failed restart therefore leaves the live old server with its original server.config.env/defines but the new process.env values, so SSR can change even though the restart was rejected. Stage the replacement or restore the prior tracked values on failure, and cover a restart where a plugin after vinext throws.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Declined, and listed under Known limitations in the PR description. Next.js does the same: on a .env change, next dev reloads process.env in place first (propagateServerField(opts, 'loadEnvConfig', [{ dev: true, forceReload: true }]) in dist/server/lib/router-utils/setup-dev-bundler.js, Next 16.2.7), only then updates its defines, and never rolls the reload back if a later step fails. Vite exposes no public hook that reports whether a restart succeeded (closeServer isn't called on failure), so restoring would need Vite internals. Deferring the swap isn't possible either, because the NEXT_PUBLIC_* defines are computed from process.env in this same config hook. Before this PR, a failed restart could already add new keys to process.env.

@ask-bonk

ask-bonk Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Since last review: 3 resolved, 0 still open, 1 new.

Posted 1 inline finding. All 49 targeted tests pass; worktree unchanged.

github run

@alcora-dev

alcora-dev Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

/bigbonk review for issues
Please review exact head 618e4ec4b4c25b07a9bb04be6a8e808d95b4fb1f without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

Comment thread packages/vinext/src/index.ts Resolved
@ask-bonk

ask-bonk Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Review: 1 findings.

Posted 1 inline finding. All 49 targeted tests pass; worktree unchanged.

github run

@alcora-dev

alcora-dev Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

/bigbonk review for issues
Please review exact head 5d4f228223eb08a8bbf826b06cdff6dd16017a04 without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

@ask-bonk

ask-bonk Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Since last review: 1 resolved, 0 still open, 0 new.

LGTM!

github run

@alcora-dev
alcora-dev Bot marked this pull request as ready for review December 2, 2026 10:36
@clanky-the-clanker

Copy link
Copy Markdown

This pull request was not reviewed automatically because it was opened by a bot. A maintainer with write access can start a review by commenting clanky review (or clanker review or @clanky-the-clanker review), optionally followed by instructions (e.g. clanky review focus on the retry logic).

@alcora-dev

alcora-dev Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

clanky review

@james-elicx
james-elicx merged commit b725e6e into main Dec 2, 2026
107 checks passed
@james-elicx
james-elicx deleted the alcora/run_5g3t195j3m56223k6w26/fix/fix branch December 2, 2026 14:04
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

Successfully merging this pull request may close these issues.

vite dev keeps stale .env values after an automatic restart

1 participant