Skip to content
IntermediateNext.jsWeb Development

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 min2 stepsPublished

Zod logo
Photo: Zod project (MIT licence)

Prerequisites

  • Node.js 20+
  • A TypeScript project
  • npm install zod
  1. 1

    Describe your configuration

    Create env.ts. The schema documents every variable, its type and its default:

    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;
    }
  2. 2

    Load it once at startup

    TypeScript
    import { loadEnv } from "./env";
    
    const env = loadEnv();
    console.log(env.PORT); // typed as number

    With an invalid value, startup stops with a readable list such as DATABASE_URL: Invalid URL.

Troubleshooting

PORT is a string

Environment variables are always strings; `z.coerce.number()` converts them.

Check your understanding

Which variables can a Next.js app expose to the browser?