process.env 를 스키마로 parse 하면 빠진 값은 시작할 때 ZodError 로 터지고1, 결과에는 선언한 키만 남는다2.
import z from 'zod'
const envSchema = z.object({
REACT_APP_FEATURE_VAC_ASK: z.string(),
REACT_APP_FEATURE_RECORDS: z.string(),
NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
})
const windowSchema = z.object({
SOMETHING_COOL: z.string()
})
export const ENV = envSchema.parse(process.env)
export const WINDOW = windowSchema.parse(window)
- Using Zod to safely read env variables by sergiodxa
- GitHub - lostfictions/znv: Type-safe environment parsing and validation for Node.js with Zod schemas
- https://twitter.com/mattpocockuk/status/1615110808219918352?s=20
Footnotes
-
Basic usage | Zod: “When validation fails, the
.parse()method will throw aZodErrorinstance with granular information about the validation issues.” ↩ -
Defining schemas | Zod: “By default, unrecognized keys are stripped from the parsed result” ↩