Environment Variable Validator
Validates required environment variables at startup and returns a typed config object or throws with missing keys.
type EnvSchema = Record<string, { required?: boolean; default?: string }>;
export function validateEnv<T extends EnvSchema>(schema: T): {
[K in keyof T]: string;
} {
const result: Record<string, string> = {};
const missing: string[] = [];
for (const [key, opts] of Object.entries(schema)) {
const value = process.env[key] ?? opts.default;
if (!value && opts.required !== false) {
missing.push(key);
} else {
result[key] = value ?? '';
}
}
if (missing.length > 0) {
throw new Error(
`Missing required environment variables: ${missing.join(', ')}`
);
}
return result as { [K in keyof T]: string };
}
// Usage:
// const env = validateEnv({
// DATABASE_URL: { required: true },
// PORT: { default: '3000' },
// NODE_ENV: { default: 'development' },
// });Use Cases
- App startup validation
- Typed configuration objects
- 12-factor app compliance
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
Environment Variable Validation
Validate required environment variables at build time with type-safe access and descriptive errors.
Type-Safe Settings with Pydantic
Load and validate environment variables into a typed settings object using pydantic-settings with defaults.
Redis Cache Get/Set Helper
Type-safe Redis cache wrapper with automatic JSON serialization, TTL support, and cache-aside pattern.
Express Zod Request Validation
Validate Express request body, params, and query with Zod schemas via reusable middleware.