Skip to main content

Lesson 5 of 8

Environment Validation with Zod

TypeScript's `ProcessEnv` declaration merging adds compile-time types to `process.env`, but it cannot validate that the values actually exist at runtime. Zod validates env vars at startup - if `DATABASE_URL` is missing, the server refuses to start with a clear error rather than failing silently during a DB call at request time.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Runtime Env Validation - Zod Schema at Startup

Runtime Env Validation - Zod Schema at Startup
// src/config/env.ts
import { z }   from "zod";
import dotenv  from "dotenv";

// Load .env file BEFORE validation
dotenv.config();

// ── Zod schema for all env vars ────────────────────────────────
const EnvSchema = z.object({
  // Node
  NODE_ENV: z.enum(["development", "test", "production"]).default("development"),
  PORT:     z.string().regex(/^\d+$/).transform(Number).default("3000"),

  // Database
  DATABASE_URL: z.string().url("DATABASE_URL must be a valid URL"),

  // Auth
  JWT_SECRET:          z.string().min(32, "JWT_SECRET must be at least 32 chars"),
  JWT_EXPIRES_IN:      z.string().default("7d"),
  REFRESH_TOKEN_SECRET: z.string().min(32).optional(),

  // Redis (optional)
  REDIS_URL: z.string().url().optional(),

  // Email (required in production)
  SMTP_HOST: z.string().optional(),
  SMTP_PORT: z.string().regex(/^\d+$/).transform(Number).optional(),

  // CORS
  CORS_ORIGIN: z.string().default("http://localhost:3001"),
});

// ── Parse at module load - fail fast if invalid ───────────────
const parsed = EnvSchema.safeParse(process.env);

if (!parsed.success) {
  console.error("❌ Invalid environment configuration:");
  console.error(parsed.error.flatten().fieldErrors);
  process.exit(1);   // Hard stop - do not start the server
}

// ── Export strongly-typed config ──────────────────────────────
export const config = parsed.data;
export type Config  = typeof config;

// ── Usage in other modules ────────────────────────────────────
import { config } from "@/config/env";

// config.PORT     is number  (Zod transformed it)
// config.NODE_ENV is "development" | "test" | "production"
// config.DATABASE_URL is string (validated as URL)

const server = app.listen(config.PORT, () => {
  console.log(`✅ Server running on port ${config.PORT} [${config.NODE_ENV}]`);
});

// ── Production-only validation ────────────────────────────────
const ProductionEnvSchema = EnvSchema.extend({
  SMTP_HOST: z.string().min(1),   // required in prod
  SMTP_PORT: z.number(),          // required in prod
  REDIS_URL: z.string().url(),    // required in prod
});

if (config.NODE_ENV === "production") {
  const prodParsed = ProductionEnvSchema.safeParse(process.env);
  if (!prodParsed.success) {
    console.error("❌ Missing required production environment variables:");
    console.error(prodParsed.error.flatten().fieldErrors);
    process.exit(1);
  }
}

Common Mistakes

  • Importing config before `dotenv.config()` - module-level validation runs at import time. Always call `dotenv.config()` at the very top of your entry file before any other imports that depend on env vars.
  • Using `z.string()` for PORT - env vars are always strings. Use `.transform(Number)` to convert, and `.min(1).max(65535)` to validate the range.
  • Not calling `process.exit(1)` on invalid config - if env validation fails but you continue, you'll get cryptic DB connection errors at request time instead of a clear startup error. Hard-stop on invalid config.

Tip

Tip

Practice Environment Validation with Zod in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Environment Validation with Zod

Practice Task

Note

Practice Task - (1) Write a working example of Environment Validation with Zod from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Environment Validation with Zod is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.

Key Takeaways

  • TypeScript's `ProcessEnv` declaration merging adds compile-time types to `process.
  • Importing config before `dotenv.config()` - module-level validation runs at import time. Always call `dotenv.config()` at the very top of your entry file before any other imports that depend on env vars.
  • Using `z.string()` for PORT - env vars are always strings. Use `.transform(Number)` to convert, and `.min(1).max(65535)` to validate the range.
  • Not calling `process.exit(1)` on invalid config - if env validation fails but you continue, you'll get cryptic DB connection errors at request time instead of a clear startup error. Hard-stop on invalid config.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/8 done