Skip to content

Commit 3007e64

Browse files
committed
refactor: use Vite loadEnv instead of manual .env parsing
Replace manual regex-based .env parsing and the unsafe define: { "process.env": process.env } (which leaked all env vars into the bundle) with Vite's built-in loadEnv scoped to CANISTER_* prefix. Also remove unused DFX_NETWORK define (no longer referenced after removing fetchRootKey).
1 parent 925e5e0 commit 3007e64

File tree

1 file changed

+12
-12
lines changed

1 file changed

+12
-12
lines changed

motoko/hello_world/frontend/vite.config.js

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
import { defineConfig } from "vite";
2-
import { readFileSync } from "fs";
1+
import { defineConfig, loadEnv } from "vite";
32
import { execSync } from "child_process";
43
import { icpBindgen } from "@icp-sdk/bindgen/plugins/vite";
54

@@ -59,15 +58,12 @@ function getDevServerConfig() {
5958
);
6059
}
6160

62-
export default defineConfig(({ command }) => {
63-
// Load .env file (generated by dfx) if it exists
64-
try {
65-
const envFile = readFileSync("../.env", "utf-8");
66-
for (const line of envFile.split("\n")) {
67-
const match = line.match(/^([A-Z_]+[A-Z0-9_]*)=(.+)$/);
68-
if (match) process.env[match[1]] = match[2].replace(/^['"]|['"]$/g, "");
69-
}
70-
} catch {}
61+
export default defineConfig(({ command, mode }) => {
62+
// dfx generates ../.env with CANISTER_ID_* vars on deploy. Bake them into the
63+
// bundle so actor.js can fall back to them when the ic_env cookie does not
64+
// contain canister IDs (dfx does not inject PUBLIC_CANISTER_ID:* env vars
65+
// into the asset canister, unlike icp-cli).
66+
const env = loadEnv(mode, "..", ["CANISTER_"]);
7167

7268
return {
7369
base: "./",
@@ -77,7 +73,11 @@ export default defineConfig(({ command }) => {
7773
outDir: "./src/bindings",
7874
}),
7975
],
80-
define: { "process.env": process.env },
76+
define: {
77+
"process.env.CANISTER_ID_BACKEND": JSON.stringify(
78+
env.CANISTER_ID_BACKEND
79+
),
80+
},
8181
optimizeDeps: {
8282
esbuildOptions: { define: { global: "globalThis" } },
8383
},

0 commit comments

Comments
 (0)