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.
Code
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:
zodis 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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.