Skip to content

</> Dev Zone

Dev Zone

For builders: practical code, commands and step-by-step guides. Every snippet marked “Tested” was run before publishing.

env.ts Tested
import { z } from "zod";

const EnvSchema = z.object({
  DATABASE_URL: z.url(),
  NODE_ENV: z.enum(["development", "test", "production"]).default("development"),
  PORT: z.coerce.number().int().positive().default(3000),
});

export function loadEnv(source: Record<string, string | undefined> = process.env) {
  const result = EnvSchema.safeParse(source);
  if (!result.success) {
    const problems = result.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`);
    throw new Error(`Invalid environment variables:\n${problems.join("\n")}`);
  }
  return result.data;
}

Static preview — code is not executed on our servers.

Web Development

  • Zod logo
    Intermediate

    Validate Environment Variables with Zod

    Fail fast with a clear message when configuration is missing or malformed — instead of a mysterious crash in production.

    15 min 2 steps Next.js