forked from TanStack/tanstack.com
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenv.ts
More file actions
43 lines (38 loc) · 1.29 KB
/
Copy pathenv.ts
File metadata and controls
43 lines (38 loc) · 1.29 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
import { z } from 'zod'
// Define server-only schema
const serverEnvSchema = z.object({
GITHUB_AUTH_TOKEN: z.string().default('USE_A_REAL_KEY_IN_PRODUCTION'),
AIRTABLE_API_KEY: z.string().optional(),
})
// Define client schema
const viteEnvSchema = z.object({
VITE_CLERK_PUBLISHABLE_KEY: z.string().optional(),
})
// Validate and parse environment variables
const parsedServerEnv = import.meta.env.SSR
? serverEnvSchema.parse(process.env)
: {}
const parsedClientEnv = viteEnvSchema.parse(import.meta.env)
type ParsedServerEnv = z.infer<typeof serverEnvSchema>
type ParsedClientEnv = z.infer<typeof viteEnvSchema>
type ParsedEnv = ParsedServerEnv & ParsedClientEnv
// Merge parsed environments, with server env hidden from client
export const env = new Proxy(
import.meta.env.SSR
? { ...parsedClientEnv, ...parsedServerEnv }
: parsedClientEnv,
{
get(target, prop) {
if (prop in parsedServerEnv && typeof window !== 'undefined') {
throw new Error(
`Access to server-only environment variable '${String(
prop
)}' from client code is not allowed.`
)
}
return prop in parsedServerEnv
? parsedServerEnv[prop as keyof typeof parsedServerEnv]
: target[prop as keyof typeof parsedClientEnv]
},
}
) as ParsedEnv