Validate Environment Variables With Zod

Parse process environment variables through a schema at startup, failing fast with a clear message when a required setting is missing or malformed.

TypescriptConfig Management

Code

typescriptsnippet
21 lines
import { z } from "zod";

const EnvSchema = z.object({
  NODE_ENV: z.enum(["development", "test", "production"]).default("development"),
  PORT: z.coerce.number().int().min(1).max(65535).default(3000),
  DATABASE_URL: z.string().url(),
  LOG_LEVEL: z.enum(["debug", "info", "warn", "error"]).default("info"),
});

export type Env = z.infer<typeof EnvSchema>;

export function loadEnv(source: NodeJS.ProcessEnv = process.env): Env {
  const parsed = EnvSchema.safeParse(source);
  if (!parsed.success) {
    const detail = parsed.error.issues
      .map((issue) => issue.path.join(".") + ": " + issue.message)
      .join("; ");
    throw new Error("invalid environment config -> " + detail);
  }
  return parsed.data;
}

Inside the code

Beyond the EnvSchema definition, the runnable logic is loadEnv alone.

From zod it pulls z — the imports name exactly which library surface the snippet touches. Failure is loud: Error aborts the current operation instead of degrading it.

Watch out for

  • Plan for an install step: zod is a real dependency, resolved by the package manager.

Applying it

Its main signature reads export function loadEnv(source: NodeJS.ProcessEnv = process.env)

The surface worth importing is loadEnv; the helpers around it are private to the snippet.

Statements that matter

throw new Error("invalid environment config -> " + detail);
.map((issue) => issue.path.join(".") + ": " + issue.message)
.join("; ");

Interactive Tools for This Topic

FAQ

Is there a failure path for bad input?
The code refuses to continue: `Error` is thrown while the state is still recoverable.
Does this require external packages?
Yes — `zod`. Add it to your project before running the snippet.