-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathenv.mjs
More file actions
50 lines (43 loc) · 1.6 KB
/
env.mjs
File metadata and controls
50 lines (43 loc) · 1.6 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
// @ts-check
import { z } from "zod";
/**
* Specify your environment variables schema here.
* This way, you can ensure the app isn't built with invalid environment variables.
* By default, environment variables are only available in the Node.js environment, meaning they won't be exposed to the browser. In order to expose a variable to the browser you have to prefix the variable with NEXT_PUBLIC_.
* -> Don't use any Zod .transform() methods in the schema (will cause `implicitly has type 'any'` error) <-
*/
export const schema = z.object({
NODE_ENV: z.enum(["development", "test", "production"]),
});
/**
* Environment variable declarations based on the schema help structure your environment variables programmatically.
* @type {{ [k in keyof z.infer<typeof schema>]: z.infer<typeof schema>[k] | undefined }}
*/
export const env = {
NODE_ENV: process.env.NODE_ENV,
};
/**
* --------------------------------
* --------------------------------
* Next-ValidEnv Manual Implementation
* --------------------------------
* --------------------------------
*/
export const formatZodErrors = (
/** @type z.ZodFormattedError<Map<string, string>, string> */ errors
) =>
Object.entries(errors)
.map(([name, value]) => {
if (value && "_errors" in value)
return `${name}: ${value._errors.join(", ")}\n`;
return;
})
.filter(Boolean);
const safeParsedEnv = schema.safeParse(env);
if (!safeParsedEnv.success) {
console.error(
"❌ Invalid environment variables:\n",
...formatZodErrors(safeParsedEnv.error.format())
);
throw new Error("Invalid environment variables");
}