-
Notifications
You must be signed in to change notification settings - Fork 1
/
env.mjs
72 lines (64 loc) · 2.32 KB
/
env.mjs
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
//credit: https://create.t3.gg/
/* eslint-disable @typescript-eslint/ban-ts-comment */
import { z } from "zod";
/**
* Specify your server-side environment variables schema here.
* This way you can ensure the app isn't built with invalid env vars.
*/
const server = z.object({
DATABASE_URL: z.string().url(),
NODE_ENV: z.enum(["development", "test", "production"]),
SUPABASE_URL: z.string(),
SUPABASE_ANON_KEY: z.string(),
LEMON_KEY: z.string(),
LEMON_STORE_ID: z.string(),
LEMON_SIGN_SECRET: z.string(),
});
/**
* You can't destruct `process.env` as a regular object in the Next.js
* edge runtimes (e.g. middlewares) or client-side so we need to destruct manually.
* @type {Record<keyof z.infer<typeof server>>}
*/
const processEnv = {
DATABASE_URL: process.env.DATABASE_URL,
NODE_ENV: process.env.NODE_ENV,
SUPABASE_URL: process.env.SUPABASE_URL,
SUPABASE_ANON_KEY: process.env.SUPABASE_ANON_KEY,
LEMON_KEY: process.env.LEMON_KEY,
LEMON_STORE_ID: process.env.LEMON_STORE_ID,
LEMON_SIGN_SECRET: process.env.LEMON_SIGN_SECRET,
};
// Don't touch the part below
// --------------------------
/** @type z.infer<server>
* @ts-ignore - can't type this properly in jsdoc */
let env = process.env;
if (!!process.env.SKIP_ENV_VALIDATION == false) {
const isServer = typeof window === "undefined";
const parsed = server.safeParse(processEnv); // validate env vars
if (parsed.success === false) {
console.error(
"❌ Invalid environment variables:",
parsed.error.flatten().fieldErrors
);
throw new Error("Invalid environment variables");
}
/** @type z.infer<server>
* @ts-ignore - can't type this properly in jsdoc */
env = new Proxy(parsed.data, {
get(target, prop) {
if (typeof prop !== "string") return undefined;
// Throw a descriptive error if a server-side env var is accessed on the client
// Otherwise it would just be returning `undefined` and be annoying to debug
if (!isServer)
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-ignore - can't type this properly in jsdoc */
return target[prop];
},
});
}
export { env };