Zod Environment Variables Startup Validation

Parse and validate process.env at boot with a Zod schema so missing or malformed configuration fails fast before any request is served.

JavascriptNodeConfig Management

Code

javascriptsnippet
23 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(),
  JWT_SECRET: z.string().min(32),
  LOG_LEVEL: z.enum(['debug', 'info', 'warn', 'error']).default('info'),
});

function loadEnv() {
  const parsed = EnvSchema.safeParse(process.env);
  if (!parsed.success) {
    for (const issue of parsed.error.issues) {
      console.error('invalid env:', issue.path.join('.'), '-', issue.message);
    }
    process.exit(1);
  }
  return parsed.data;
}

export const env = loadEnv();
console.log('listening on port', env.PORT, 'in', env.NODE_ENV);

Inside the snippet

Zod Environment Variables Startup Validation keeps everything in the function loadEnv.

for (const issue of parsed.error.issues) is the loop that carries the per-item work. Everything borrowed from zod is visible in one line: z.

Watch out for

  • Requires zod as a package; the snippet will not run without it.

Putting it to use

The primary signature is export const env =

The demo output is labeled (invalid env:, listening on port), so every printed line maps back to its originating operation.

Import env from the file and call it — the rest of the code is implementation detail.

Core lines

const parsed = EnvSchema.safeParse(process.env);
export const env = loadEnv();
process.exit(1);

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
Yes: `zod` must be present in the project or the import fails at load time.