Skip to content

Commit

Permalink
fix(next): fix reload dot env (#657)
Browse files Browse the repository at this point in the history
  • Loading branch information
hi-ogawa authored Oct 5, 2024
1 parent 613a1da commit 0d2131c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
17 changes: 16 additions & 1 deletion packages/react-server-next/src/vite/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,11 +128,26 @@ function nextConfigPlugin(): Plugin {
};
},
configResolved(config) {
Object.assign(process.env, loadEnv(config.mode, config.envDir, ""));
updateEnv(() => loadEnv(config.mode, config.envDir, ""));
},
};
}

// workaround https://github.com/vitejs/vite/issues/17689
(globalThis as any).__next_vite_last_env__ ??= [];
declare let __next_vite_last_env__: string[];

function updateEnv(loadEnv: () => Record<string, string>) {
for (const key of __next_vite_last_env__) {
delete process.env[key];
}
const loadedEnv = loadEnv();
__next_vite_last_env__ = Object.keys(loadedEnv).filter(
(key) => !(key in process.env),
);
Object.assign(process.env, loadedEnv);
}

function nextJsxPlugin(): Plugin {
return {
name: nextJsxPlugin.name,
Expand Down
6 changes: 2 additions & 4 deletions packages/react-server/examples/next/e2e/basic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,8 +185,6 @@ test("dotenv", async ({ page }) => {
);

if (!process.env.E2E_PREVIEW) {
// TODO: dotenv reload not working
// https://github.com/vitejs/vite/issues/17689
const reloadPromise = page.waitForEvent("load");
using file = createEditor(".env");
file.edit((s) =>
Expand All @@ -196,10 +194,10 @@ test("dotenv", async ({ page }) => {
);
await reloadPromise;
await expect(page.getByTestId("process.env")).toContainText(
'{ "SECRET_ENV_TEST": "ok", "NEXT_PUBLIC_ENV_TEST": "ok", "VITE_ENV_TEST": "ok" }',
'{ "SECRET_ENV_TEST": "edit", "NEXT_PUBLIC_ENV_TEST": "ok", "VITE_ENV_TEST": "edit" }',
);
await expect(page.getByTestId("import.meta.env")).toContainText(
'{ "SECRET_ENV_TEST": null, "NEXT_PUBLIC_ENV_TEST": "ok", "VITE_ENV_TEST": "ok" }',
'{ "SECRET_ENV_TEST": null, "NEXT_PUBLIC_ENV_TEST": "ok", "VITE_ENV_TEST": "edit" }',
);
}
});

0 comments on commit 0d2131c

Please sign in to comment.