Skip to content

Commit b484bb5

Browse files
authored
Merge pull request #387 from captableinc/fix-runtime-env
fix: runtime env error message
2 parents c4451f8 + 5f11e1b commit b484bb5

File tree

1 file changed

+22
-3
lines changed

1 file changed

+22
-3
lines changed

src/env.js

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,18 @@
22
import { createEnv } from "@t3-oss/env-nextjs";
33
import { z } from "zod";
44

5+
const PUBLIC_ENV_KEY = "___ENV";
6+
7+
function isBrowser() {
8+
return typeof window !== "undefined";
9+
}
10+
511
const readRuntimePublicEnvVariable = (key) => {
6-
if (typeof window === "undefined") return process.env[key];
7-
return window.___ENV[key];
12+
if (isBrowser()) {
13+
return window?.[PUBLIC_ENV_KEY]?.[key];
14+
}
15+
16+
return process.env[key];
817
};
918

1019
export const env = createEnv({
@@ -60,7 +69,7 @@ export const env = createEnv({
6069
* You can't destruct `process.env` as a regular object in the Next.js edge runtimes (e.g.
6170
* middlewares) or client-side so we need to destruct manually.
6271
*/
63-
runtimeEnv: {
72+
experimental__runtimeEnv: {
6473
NODE_ENV: process.env.NODE_ENV,
6574
NEXT_PUBLIC_BASE_URL: readRuntimePublicEnvVariable("NEXT_PUBLIC_BASE_URL"),
6675
DATABASE_URL: process.env.DATABASE_URL,
@@ -98,4 +107,14 @@ export const env = createEnv({
98107
* `SOME_VAR=''` will throw an error.
99108
*/
100109
emptyStringAsUndefined: true,
110+
111+
onValidationError: (error) => {
112+
if (!isBrowser()) {
113+
console.error(
114+
"❌ Invalid environment variables:",
115+
error.flatten().fieldErrors,
116+
);
117+
throw new Error("Invalid environment variables");
118+
}
119+
},
101120
});

0 commit comments

Comments
 (0)