Skip to content

Commit 98473e4

Browse files
stephen776Steve Jacobs
andauthored
use zod to parse environment variables (#342)
Co-authored-by: Steve Jacobs <[email protected]>
1 parent d07af92 commit 98473e4

File tree

1 file changed

+23
-19
lines changed

1 file changed

+23
-19
lines changed

app/utils/env.server.ts

Lines changed: 23 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,34 @@
1-
import { invariant } from './misc.ts'
2-
3-
const requiredServerEnvs = [
4-
'NODE_ENV',
5-
'DATABASE_PATH',
6-
'DATABASE_URL',
7-
'SESSION_SECRET',
8-
'INTERNAL_COMMAND_TOKEN',
9-
'CACHE_DATABASE_PATH',
10-
// If you plan to use Resend, uncomment this line
11-
// 'RESEND_API_KEY',
1+
import { z } from 'zod'
2+
3+
const schema = z.object({
4+
NODE_ENV: z.enum(['production', 'development', 'test'] as const),
5+
DATABASE_PATH: z.string(),
6+
DATABASE_URL: z.string(),
7+
SESSION_SECRET: z.string(),
8+
INTERNAL_COMMAND_TOKEN: z.string(),
9+
CACHE_DATABASE_PATH: z.string(),
1210
// If you plan on using Sentry, uncomment this line
13-
// 'SENTRY_DSN',
14-
] as const
11+
// SENTRY_DSN: z.string(),
12+
// If you plan to use Resend, uncomment this line
13+
// RESEND_API_KEY: z.string(),
14+
})
1515

1616
declare global {
1717
namespace NodeJS {
18-
interface ProcessEnv
19-
extends Record<(typeof requiredServerEnvs)[number], string> {}
18+
interface ProcessEnv extends z.infer<typeof schema> {}
2019
}
2120
}
2221

2322
export function init() {
24-
for (const env of requiredServerEnvs) {
25-
invariant(process.env[env], `${env} is required`)
23+
const parsed = schema.safeParse(process.env)
24+
25+
if (parsed.success === false) {
26+
console.error(
27+
'❌ Invalid environment variables:',
28+
parsed.error.flatten().fieldErrors,
29+
)
30+
31+
throw new Error('Invalid envirmonment variables')
2632
}
2733
}
2834

@@ -36,8 +42,6 @@ export function init() {
3642
* @returns all public ENV variables
3743
*/
3844
export function getEnv() {
39-
invariant(process.env.NODE_ENV, 'NODE_ENV should be defined')
40-
4145
return {
4246
MODE: process.env.NODE_ENV,
4347
SENTRY_DSN: process.env.SENTRY_DSN,

0 commit comments

Comments
 (0)