Implement comprehensive validation for environment variables using a schema validation library (e.g., Zod). Include proper typing, conditional validation rules, and sensible defaults. This ensures configuration errors are caught early and prevents runtime issues.
Key practices:
Example:
const EnvSchema = z.object({
// Use appropriate types instead of string enums
DEBUG_MODE: z.coerce.boolean().default(false),
// Add conditional validation for dependent configs
S3_MEDIA_UPLOAD_SSE: z.enum(["AES256", "aws:kms"]).optional(),
S3_MEDIA_UPLOAD_KMS_KEY_ID: z.string().optional()
.refine((val, ctx) => {
if (ctx.parent.S3_MEDIA_UPLOAD_SSE === "aws:kms" && !val) {
return false;
}
return true;
}, "KMS key ID required when using aws:kms encryption"),
// Provide fallbacks for optional configs
SENTRY_RELEASE: z.string().optional()
.default(process.env.BUILD_ID ?? "unknown")
});
Enter the URL of a public GitHub repository