-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenv.ts
More file actions
77 lines (62 loc) · 2.29 KB
/
env.ts
File metadata and controls
77 lines (62 loc) · 2.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// src/env.ts
import { z } from 'zod';
/** Server-only env (no NEXT_PUBLIC_ here) */
const server = z.object({
POSTGRES_CONNECTION_STRING: z.string(),
VERIFIER_API_URL: z.string().url(),
ISSUER_API_URL: z.string().url(),
KEYSTORE_FILE: z.string(),
KEYSTORE_PASS: z.string(),
KEYSTORE_ALIAS: z.string(),
});
/** Client-exposed env (must be prefixed with NEXT_PUBLIC_) */
const client = z.object({
NEXT_PUBLIC_APP_NAME: z.string(),
NEXT_PUBLIC_APP_URI: z.string().url(),
});
/** Build a single shape that contains both */
const merged = server.merge(client);
/** Collect runtime env from process.env */
const runtimeEnv: Record<keyof z.infer<typeof merged>, string | undefined> = {
POSTGRES_CONNECTION_STRING: process.env.POSTGRES_CONNECTION_STRING,
VERIFIER_API_URL: process.env.VERIFIER_API_URL,
ISSUER_API_URL: process.env.ISSUER_API_URL,
KEYSTORE_FILE: process.env.KEYSTORE_FILE,
KEYSTORE_PASS: process.env.KEYSTORE_PASS,
KEYSTORE_ALIAS: process.env.KEYSTORE_ALIAS,
NEXT_PUBLIC_APP_NAME: process.env.NEXT_PUBLIC_APP_NAME,
NEXT_PUBLIC_APP_URI: process.env.NEXT_PUBLIC_APP_URI,
};
const isServer = typeof window === 'undefined';
/** Validate lazily to avoid requiring env vars at build time */
let validated = false;
let data: z.infer<typeof merged>;
function validate() {
if (validated) return;
const parsed = isServer ? merged.safeParse(runtimeEnv) : client.safeParse(runtimeEnv);
if (!parsed.success) {
// Show precise errors in dev
console.error('❌ Invalid environment variables:', parsed.error.flatten().fieldErrors);
throw new Error('Invalid environment variables');
}
data = parsed.data as z.infer<typeof merged>;
validated = true;
}
/** Strongly-typed env with a guard: client cannot access server vars */
type Merged = z.infer<typeof merged>;
export const env = new Proxy({} as Merged, {
get(_target, prop: string) {
// Validate on first access (runtime)
validate();
// Disallow server vars on the client
if (!isServer && !prop.startsWith('NEXT_PUBLIC_')) {
throw new Error(
process.env.NODE_ENV === 'production'
? '❌ Attempted to access a server-side environment variable on the client'
: `❌ Attempted to access server-side environment variable '${prop}' on the client`,
);
}
// @ts-expect-error — index signature via Proxy
return data[prop];
},
});