Paweł Piech

Parsing environment variables with Zod

Environment variables are strings, and they can be missing. process.env.PORT is a string or undefined, and nothing stops me from passing it where a number belongs. The mistake shows up later, in another file, on a machine that is not mine.

Now I parse the environment once, at startup, with a Zod schema. The service reads one typed object, and a wrong value stops it from starting.

The problem

const port = process.env.PORT; // string | undefined
const password = process.env.POSTGRES_PASSWORD;

Every read is untyped, and every file that needs a value repeats the conversion. A missing variable does not fail where it is read. A missing PORT gives a server on a random port. A missing POSTGRES_PASSWORD gives a connection error on the first request, long after boot. I then compare the deployment config, the env file, and the README by hand.

One schema

import { z } from "zod";

const EnvSchema = z.object({
  PORT: z.coerce.number().int().default(3000),
  POSTGRES_USER: z.string().min(1),
  POSTGRES_PASSWORD: z.string().min(1),
  POSTGRES_DB: z.string().min(1),
  OPENAI_API_KEY: z.string().startsWith("sk-"),
  ANTHROPIC_API_KEY: z.string().startsWith("sk-ant-"),
  OPENROUTER_API_KEY: z.string().startsWith("sk-or-"),
});

Coerce does the string to number change once, next to the rule. A default marks a variable as optional. A field with no default is required, so the schema is the list of values the service cannot start without.

The key prefixes catch a value that is not a key at all, like a placeholder left in a copied .env file, and they name the provider next to the variable.

Start or fail

const parsed = EnvSchema.safeParse(process.env);

if (!parsed.success) {
  console.error(z.prettifyError(parsed.error));
  process.exit(1);
}

export const env = parsed.data;

A wrong variable stops the service before it listens, and the message names the variable and the rule. I fix the config and restart, instead of reading a stack trace from a request that failed ten seconds after boot. In a test I let the error throw, so the failure lands in the test output.

When not to use it

A twenty line script with one variable gets a check at the top. Parsing also does not hide a secret: the value is still in the environment, so I do not log the parsed object.

That is the whole trick. One file, one schema, one check before the server starts. A runtime surprise becomes a startup error that names the variable.