typescriptintermediate

Environment Variable Validation with Zod

Validate environment variables at build time using Zod to catch misconfigurations early.

typescript
// lib/env.ts
import { z } from 'zod';

const envSchema = z.object({
  // Server-only
  DATABASE_URL: z.string().url(),
  API_SECRET_KEY: z.string().min(32),
  JWT_SECRET: z.string().min(16),
  SMTP_HOST: z.string().optional(),
  SMTP_PORT: z.coerce.number().default(587),

  // Public (client-safe)
  NEXT_PUBLIC_SITE_URL: z.string().url(),
  NEXT_PUBLIC_GA_ID: z.string().startsWith('G-').optional(),
  NEXT_PUBLIC_ADSENSE_CLIENT: z.string().startsWith('ca-pub-').optional(),
});

type Env = z.infer<typeof envSchema>;

function validateEnv(): Env {
  const result = envSchema.safeParse(process.env);

  if (!result.success) {
    console.error('Environment variable validation failed:');
    for (const [key, errors] of Object.entries(
      result.error.flatten().fieldErrors
    )) {
      console.error(`  ${key}: ${errors?.join(', ')}`);
    }
    throw new Error('Invalid environment variables');
  }

  return result.data;
}

export const env = validateEnv();

// Usage:
// import { env } from '@/lib/env';
// const dbUrl = env.DATABASE_URL; // Type-safe, validated

Use Cases

  • build-time validation
  • type-safe config
  • preventing deployment errors

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.