-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathenv.server.ts
More file actions
61 lines (51 loc) · 1.76 KB
/
env.server.ts
File metadata and controls
61 lines (51 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { z } from "zod/v4"
const envSchema = z.object({
NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
APP_ENV: z.enum(["development", "staging", "production"]).default("development"),
})
type ServerEnv = z.infer<typeof envSchema>
let env: ServerEnv
/**
* Initializes and parses given environment variables using zod
* @returns Initialized env vars
*/
function initEnv() {
// biome-ignore lint/style/noProcessEnv: This should be the only place to use process.env directly
const envData = envSchema.safeParse(process.env)
if (!envData.success) {
// biome-ignore lint/suspicious/noConsole: We want this to be logged
console.error("❌ Invalid environment variables:", envData.error.flatten().fieldErrors)
throw new Error("Invalid environment variables")
}
env = envData.data
Object.freeze(env)
// Do not log the message when running tests
if (env.NODE_ENV !== "test") {
// biome-ignore lint/suspicious/noConsole: We want this to be logged
console.log("✅ Environment variables loaded successfully")
}
return env
}
export function getServerEnv() {
if (env) return env
return initEnv()
}
/**
* Helper function which returns a subset of the environment vars which are safe expose to the client.
* Dont expose any secrets or sensitive data here.
* Otherwise you would expose your server vars to the client if you returned them from here as this is
* directly sent in the root to the client and set on the window.env
* @returns Subset of the whole process.env to be passed to the client and used there
*/
export function getClientEnv() {
const serverEnv = getServerEnv()
return {
NODE_ENV: serverEnv.NODE_ENV,
}
}
type ClientEnvVars = ReturnType<typeof getClientEnv>
declare global {
interface Window {
env: ClientEnvVars
}
}