🦺 Type-safe environment variables

if (process.env.VARIABLE_NAME != null) {
  // Do things here
}

I hate conditionally checking for variables like this.


Below is a snippet I basically use in every new project so I can have type-safe environment variables.

import { z } from "zod";

const envSchema = z.object({
  // Pocketbase
  PB_TYPEGEN_URL: z.string(),
  PB_TYPEGEN_EMAIL: z.string().email(),
  PB_TYPEGEN_PASSWORD: z.string(),
});

const env = envSchema.safeParse(process.env);
if (!env.success) {
  console.error(
    "❌ Invalid environment variables:",
    JSON.stringify(env.error.format(), null, 4),
  );
  process.exit(1);
}

export const envs = env.data;