-
Notifications
You must be signed in to change notification settings - Fork 7
/
env.mjs
218 lines (203 loc) · 7.7 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
import { z } from 'zod'
// Coerces a string to true if it's "true", false if "false".
const coerceBoolean = z
.string()
// only allow "true" or "false" or empty string
.refine((s) => s === 'true' || s === 'false' || s === '')
// transform to boolean
.transform((s) => s === 'true')
// make sure tranform worked
.pipe(z.boolean())
/**
* Specify your client-side environment variables schema here. This way you can ensure the app isn't
* built with invalid env vars. To expose them to the client, prefix them with `NEXT_PUBLIC_`.
*/
const client = z.object({
NEXT_PUBLIC_ENABLE_STORAGE: coerceBoolean.default('false'),
NEXT_PUBLIC_ENABLE_SGID: coerceBoolean.default('false'),
NEXT_PUBLIC_APP_URL: z.string().url().optional(),
NEXT_PUBLIC_APP_NAME: z.string().default('Starter Kit'),
NEXT_PUBLIC_APP_VERSION: z.string().default('0.0.0'),
})
/** Feature flags */
const baseR2Schema = z.object({
R2_ACCESS_KEY_ID: z.string().optional(),
R2_ACCOUNT_ID: z.string().optional(),
R2_SECRET_ACCESS_KEY: z.string().optional(),
R2_PUBLIC_HOSTNAME: z.string().optional(),
R2_BUCKET_NAME: z.string().optional(),
R2_AVATARS_DIRECTORY: z.string().optional(),
R2_IMAGES_DIRECTORY: z.string().optional(),
})
const r2ServerSchema = z.discriminatedUnion('NEXT_PUBLIC_ENABLE_STORAGE', [
baseR2Schema.extend({
NEXT_PUBLIC_ENABLE_STORAGE: z.literal(true),
// Add required keys if flag is enabled.
R2_ACCESS_KEY_ID: z.string().min(1),
R2_ACCOUNT_ID: z.string().min(1),
R2_SECRET_ACCESS_KEY: z.string().min(1),
R2_PUBLIC_HOSTNAME: z.string().min(1),
}),
baseR2Schema.extend({
NEXT_PUBLIC_ENABLE_STORAGE: z.literal(false),
}),
])
const baseSgidSchema = z.object({
SGID_CLIENT_ID: z.string().optional(),
SGID_CLIENT_SECRET: z.string().optional(),
// Remember to set SGID redirect URI in SGID dev portal.
SGID_REDIRECT_URI: z.union([z.string().url(), z.string()]).optional(),
SGID_PRIVATE_KEY: z.string().optional(),
})
const sgidServerSchema = z.discriminatedUnion('NEXT_PUBLIC_ENABLE_SGID', [
baseSgidSchema.extend({
NEXT_PUBLIC_ENABLE_SGID: z.literal(true),
// Add required keys if flag is enabled.
SGID_CLIENT_ID: z.string().min(1),
SGID_CLIENT_SECRET: z.string().min(1),
SGID_PRIVATE_KEY: z.string().min(1),
SGID_REDIRECT_URI: z.string().url(),
}),
baseSgidSchema.extend({
NEXT_PUBLIC_ENABLE_SGID: z.literal(false),
}),
])
/**
* 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']),
OTP_EXPIRY: z.coerce.number().positive().optional().default(600),
POSTMAN_API_KEY: z.string().optional(),
SENDGRID_API_KEY: z.string().optional(),
SENDGRID_FROM_ADDRESS: z.union([
z.string().email().optional(),
z.string().length(0),
]),
SESSION_SECRET: z.string().min(32),
})
// Add on schemas as needed that requires conditional validation.
.merge(baseR2Schema)
.merge(baseSgidSchema)
.merge(client)
// Add on refinements as needed for conditional environment variables
// .superRefine((val, ctx) => ...)
.superRefine((val, ctx) => {
const parse = r2ServerSchema.safeParse(val)
if (!parse.success) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['NEXT_PUBLIC_ENABLE_STORAGE'],
message: 'R2 environment variables are missing',
})
parse.error.issues.forEach((issue) => {
ctx.addIssue(issue)
})
}
})
.superRefine((val, ctx) => {
const parse = sgidServerSchema.safeParse(val)
if (!parse.success) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['NEXT_PUBLIC_ENABLE_SGID'],
message: 'SGID environment variables are missing',
})
parse.error.issues.forEach((issue) => {
ctx.addIssue(issue)
})
}
})
.refine((val) => !(val.SENDGRID_API_KEY && !val.SENDGRID_FROM_ADDRESS), {
message: 'SENDGRID_FROM_ADDRESS is required when SENDGRID_API_KEY is set',
path: ['SENDGRID_FROM_ADDRESS'],
})
/**
* 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.
* Intellisense should work due to inference.
*
* @type {Record<keyof z.infer<typeof server> | keyof z.infer<typeof client>, string | undefined>}
*/
const processEnv = {
// Server-side env vars
NODE_ENV: process.env.NODE_ENV,
DATABASE_URL: process.env.DATABASE_URL,
OTP_EXPIRY: process.env.OTP_EXPIRY,
POSTMAN_API_KEY: process.env.POSTMAN_API_KEY,
SENDGRID_API_KEY: process.env.SENDGRID_API_KEY,
SENDGRID_FROM_ADDRESS: process.env.SENDGRID_FROM_ADDRESS,
SESSION_SECRET: process.env.SESSION_SECRET,
R2_ACCESS_KEY_ID: process.env.R2_ACCESS_KEY_ID,
R2_ACCOUNT_ID: process.env.R2_ACCOUNT_ID,
R2_BUCKET_NAME: process.env.R2_BUCKET_NAME,
R2_AVATARS_DIRECTORY: process.env.R2_AVATARS_DIRECTORY,
R2_IMAGES_DIRECTORY: process.env.R2_IMAGES_DIRECTORY,
R2_PUBLIC_HOSTNAME: process.env.R2_PUBLIC_HOSTNAME,
R2_SECRET_ACCESS_KEY: process.env.R2_SECRET_ACCESS_KEY,
SGID_CLIENT_ID: process.env.SGID_CLIENT_ID,
SGID_CLIENT_SECRET: process.env.SGID_CLIENT_SECRET,
SGID_PRIVATE_KEY: process.env.SGID_PRIVATE_KEY,
SGID_REDIRECT_URI: process.env.SGID_REDIRECT_URI,
// Client-side env vars
NEXT_PUBLIC_APP_NAME: process.env.NEXT_PUBLIC_APP_NAME,
NEXT_PUBLIC_APP_VERSION:
process.env.NEXT_PUBLIC_APP_VERSION ??
process.env.NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA,
NEXT_PUBLIC_ENABLE_STORAGE: process.env.NEXT_PUBLIC_ENABLE_STORAGE,
NEXT_PUBLIC_ENABLE_SGID: process.env.NEXT_PUBLIC_ENABLE_SGID,
NEXT_PUBLIC_APP_URL: process.env.NEXT_PUBLIC_APP_URL,
}
// Don't touch the part below
// --------------------------
/** @typedef {z.input<typeof server>} MergedInput */
/** @typedef {z.infer<typeof server>} MergedOutput */
/** @typedef {z.SafeParseReturnType<MergedInput, MergedOutput>} MergedSafeParseReturn */
// @ts-expect-error Types are wonky from refinement
let env = /** @type {MergedOutput} */ (process.env)
if (!!process.env.SKIP_ENV_VALIDATION == false) {
const isServer = typeof window === 'undefined'
const parsed = /** @type {MergedSafeParseReturn} */ (
isServer
? server.safeParse(processEnv) // on server we can validate all env vars
: client.safeParse(processEnv) // on client we can only validate the ones that are exposed
)
if (parsed.success === false) {
console.error(
'❌ Invalid environment variables:',
parsed.error.flatten().fieldErrors,
)
throw new Error('Invalid environment variables')
}
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 && !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`,
)
return target[/** @type {keyof typeof target} */ (prop)]
},
})
} else if (process.env.STORYBOOK) {
const parsed = client
.partial()
.safeParse(JSON.parse(process.env.STORYBOOK_ENVIRONMENT ?? '{}'))
if (parsed.success === false) {
console.error(
'❌ Invalid environment variables:',
parsed.error.flatten().fieldErrors,
)
throw new Error('Invalid environment variables')
}
// @ts-expect-error Injection of environment variables is optional
env = parsed.data
}
export { env }