Choose Theme

Type-Safe Environment Variables

· 1 min read · #TypeScript
--

Runtime validation and TypeScript types for environment variables. Catches missing env vars at startup instead of runtime.

env.ts
import { z } from 'zod';
const envSchema = z.object({
// Public vars (exposed to client)
PUBLIC_SUPABASE_URL: z.string().url(),
PUBLIC_SUPABASE_ANON_KEY: z.string().min(1),
PUBLIC_POSTHOG_KEY: z.string().optional(),
// Private vars (server-only)
SUPABASE_SERVICE_KEY: z.string().min(1),
RESEND_API_KEY: z.string().optional(),
DATABASE_URL: z.string().url(),
});
function validateEnv() {
const parsed = envSchema.safeParse(import.meta.env);
if (!parsed.success) {
console.error('❌ Invalid environment variables:');
console.error(parsed.error.flatten().fieldErrors);
throw new Error('Invalid environment variables');
}
return parsed.data;
}
// Export typed env object
export const env = validateEnv();
// Usage:
// import { env } from './env';
// const url = env.PUBLIC_SUPABASE_URL; // ✅ Typed!

Why this works:

  • Zod validates at runtime (catches missing vars on startup)
  • TypeScript infers types from schema
  • Single source of truth for environment variables
  • Fails fast if misconfigured

Related