Last active
March 10, 2023 19:34
-
-
Save kiliman/466656fc6a7c1873ce7ed457c29f57ca to your computer and use it in GitHub Desktop.
Use zod to parse/validate environment variables
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { z } from 'zod'; | |
import { getParams } from './params'; | |
const envSchema = z.object({ | |
NODE_ENV: z.string(), | |
DATABASE_URL: z.string().url(), | |
SESSION_SECRET: z.string(), | |
AUTH_SECRET: z.string(), | |
ENABLE_REGISTRATION: z.boolean().default(false), | |
SMTP_HOST: z.string(), | |
SMTP_PORT: z.number(), | |
SMTP_USERNAME: z.string(), | |
SMTP_PASSWORD: z.string(), | |
}); | |
export type EnvVars = z.infer<typeof envSchema>; | |
declare global { | |
var __env__: EnvVars; | |
} | |
let env: EnvVars; | |
if (process.env.NODE_ENV === 'production') { | |
env = initEnvVars(); | |
} else { | |
if (!global.__env__) { | |
global.__env__ = initEnvVars(); | |
} | |
env = global.__env__; | |
} | |
function initEnvVars(): EnvVars { | |
// use params helper to validate and PARSE the env vars | |
// @ts-ignore-expect-error | |
const [errors, data] = getParams( | |
process.env as Record<string, string>, | |
envSchema, | |
); | |
if (errors) { | |
throw new Error(JSON.stringify(errors)); | |
} | |
return data; | |
} | |
export function getEnvVars(): EnvVars { | |
return env; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment