typescriptbeginner
Environment Variable Validator
Validates required environment variables at startup and returns a typed config object or throws with missing keys.
typescriptPress ⌘/Ctrl + Shift + C to copy
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.
typescriptbeginner
Environment Variable Validation
Validate required environment variables at build time with type-safe access and descriptive errors.
Best for: App startup checks
#environment#validation
typescriptbeginner
Type-Safe Configuration Loader
Load and validate configuration from environment variables with type coercion and required field checks.
Best for: Application configuration management
#nodejs#config
typescriptintermediate
Request Validation Schema Builder
Build a lightweight request validation layer with type inference for API endpoints.
Best for: API request body validation
#nodejs#validation
typescriptintermediate
Schema Validation with Zod-like Patterns
Build a minimal schema validation library inspired by Zod using TypeScript type inference.
Best for: API request validation
#nodejs#validation