Repository navigation
fix(env): reload changed .env values when vite dev restarts - #5041
Conversation
@vinext/cloudflare
create-vinext-app
@vinext/types
vinext
@cloudflare/workers-response-store
commit: |
Performance benchmarksCompared 0 improved · 0 regressed · 7 within ±1.5%
View detailed results and traces 🟢 improvement · 🔴 regression · ⚫ change below 1.5% · paired base/head |
|
|
/bigbonk review for issues |
| 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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
Review: 2 findings. Posted 2 inline comments. Targeted dotenv tests pass; no files were modified. |
|
/bigbonk review for issues |
| } | ||
| const preserveSymlinks = config.resolve?.preserveSymlinks; | ||
| const resolvedEnvDir = envDir ? resolveProjectDir(envDir, preserveSymlinks) : undefined; | ||
| if (configHookEnvDirs.has(root)) { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
Since last review: 2 resolved, 0 still open, 2 new. Posted 2 inline findings. All 49 targeted tests pass; worktree unchanged. |
|
/bigbonk review for issues |
|
Since last review: 2 resolved, 0 still open, 1 new. Posted 1 inline finding. All 38 targeted tests pass; worktree unchanged. |
|
/bigbonk review for issues |
| // 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; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
Since last review: 1 resolved, 0 still open, 3 new. Posted 3 inline findings. All 39 targeted tests pass; worktree unchanged. |
|
/bigbonk review for issues
|
| // 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(); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
Since last review: 3 resolved, 0 still open, 1 new. Posted 1 inline finding. All 49 targeted tests pass; worktree unchanged. |
|
/bigbonk review for issues |
|
Review: 1 findings. Posted 1 inline finding. All 49 targeted tests pass; worktree unchanged. |
|
/bigbonk review for issues |
|
Since last review: 1 resolved, 0 still open, 0 new. LGTM! |
|
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 |
Fixes #5040
When a
.env*file changes duringvite dev, Vite restarts the server, andimport.meta.env,NEXT_PUBLIC_*defines and server-sideprocess.envshould show the file's new value. That's what plain Vite andnext devdo. 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:confighook again (packages/vinext/src/index.ts), and it callsloadDotenv()a second time.loadDotenv()(packages/vinext/src/config/dotenv.ts) skips every key already inprocess.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 legacyvinext devproxy incli.ts), so the old value stays. Vite'sloadEnvthen prefersprocess.envover the file, soimport.meta.env.VITE_*keeps the old value too.@next/env16.2.7 avoids this:loadEnvConfigsnapshotsprocess.envon its first call, and on every reload callsreplaceProcessEnv(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 realprocess.env. A newunloadDotenv()removes the ones that still hold the value that was loaded.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 legacyvinext devproxy and the previous run. It also covers a restart that changesenvDir, sets it tofalse, or changesroot.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.@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:
tests/client-global-define.test.tsexpects.vite build, preview andvinext start, which load once.@next/envrestores its whole snapshot instead, which would also discard other plugins' and Vite's ownprocess.envwrites. Here, only whatloadDotenvwrote is removed.@next/envdoes when it restores its snapshot and reloads.Behaviour
vite dev, after a.env.developmentchange and restart)next dev)VITE_*,NEXT_PUBLIC_*, serverprocess.env)envDirchanged invite.config(restart)envDirin Next.js)envDirchanged tofalse(restart)vite build/vinext start(single load)The Next.js column comes from the
loadEnvConfig,replaceProcessEnvandprocessEnvsource innode_modules/@next/env16.2.7. I didn't runnext dev.Tests
tests/dotenv-dev-restart.test.ts(new, integration project) and fixturetests/fixtures/dotenv-dev-restart:VITE_DEMO_LABEL=firstin.env.development, changes the file tosecond, callsserver.restart(), then checksserver.config.env,process.envand the rendered page..env.developmentin the root, restarts withenvDir: "other-env"(set onserver.config.inlineConfig, which Vite's restart reuses), then withenvDir: false. Checks that the old envDir's values are gone and the new one's are served.expected 'first' to be 'second'. The tests write.env.developmentandother-env/at runtime because.env.*is gitignored, and remove them afterwards.tests/dotenv.test.ts: a newunloadDotenvcase. 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 withunloadDotenv 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 withexpected undefined to be 'from-root'.pnpm-lock.yaml, and the test is added to theunitexclude andintegrationinclude invite.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: theunloadDotenvcase 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
process.envalready holds the edited files' values while that server'simport.meta.envand defines keep the old ones. Server-side reads see the new values, as innext dev. Next.js reloadsprocess.envin place (loadEnvConfigwithforceReload: trueinsetup-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.vite.config.*before the config hook runs, so code in the config file that readsprocess.envstill sees the previous values for that one evaluation. The early pass that serves config evaluation runs only once per process, at module load.