|
2 | 2 | import { createEnv } from "@t3-oss/env-nextjs";
|
3 | 3 | import { z } from "zod";
|
4 | 4 |
|
| 5 | +const PUBLIC_ENV_KEY = "___ENV"; |
| 6 | + |
| 7 | +function isBrowser() { |
| 8 | + return typeof window !== "undefined"; |
| 9 | +} |
| 10 | + |
5 | 11 | 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]; |
8 | 17 | };
|
9 | 18 |
|
10 | 19 | export const env = createEnv({
|
@@ -60,7 +69,7 @@ export const env = createEnv({
|
60 | 69 | * You can't destruct `process.env` as a regular object in the Next.js edge runtimes (e.g.
|
61 | 70 | * middlewares) or client-side so we need to destruct manually.
|
62 | 71 | */
|
63 |
| - runtimeEnv: { |
| 72 | + experimental__runtimeEnv: { |
64 | 73 | NODE_ENV: process.env.NODE_ENV,
|
65 | 74 | NEXT_PUBLIC_BASE_URL: readRuntimePublicEnvVariable("NEXT_PUBLIC_BASE_URL"),
|
66 | 75 | DATABASE_URL: process.env.DATABASE_URL,
|
@@ -98,4 +107,14 @@ export const env = createEnv({
|
98 | 107 | * `SOME_VAR=''` will throw an error.
|
99 | 108 | */
|
100 | 109 | 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 | + }, |
101 | 120 | });
|
0 commit comments