TypeScript

Environment Variable Validator

admin by @admin ADMIN
1h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Validate process.env at boot-time and exit fast if anything's missing. The returned object is typed so the rest of the code reads `env.DATABASE_URL` instead of `process.env.DATABASE_URL!`.
TypeScript
Raw
type EnvSchema = Record<string, { default?: string; required?: boolean }>;

export function loadEnv<S extends EnvSchema>(schema: S): { [K in keyof S]: string } {
  const out = {} as { [K in keyof S]: string };
  const missing: string[] = [];

  for (const key in schema) {
    const v = process.env[key] ?? schema[key]!.default;
    if (v === undefined) {
      if (schema[key]!.required ?? true) missing.push(key);
    } else {
      out[key] = v;
    }
  }
  if (missing.length) {
    console.error('Missing required env vars:', missing.join(', '));
    process.exit(1);
  }
  return out;
}

export const env = loadEnv({
  DATABASE_URL:   {},
  STRIPE_SECRET:  {},
  PORT:           { default: '3000' },
  DEBUG:          { default: 'false', required: false },
});
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.