typescriptbeginner

Environment Variable Validator

Validates required environment variables at startup and returns a typed config object or throws with missing keys.

typescript
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.