0Pricing
TypeScript Academy · Lesson

Schema-Validated Config

Validate config at startup with a schema.

Schema-Validated Config is a free TypeScript Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the TypeScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Validate Config at Startup

Manual parsing helpers work, but a schema declares the entire shape and rules in one place and validates all of it at startup, failing fast before the app serves traffic.

What Fail-Fast Means

Failing fast means the process exits immediately with a clear message when configuration is wrong, rather than crashing later in an obscure code path during a request.

A Schema with Zod

Libraries like zod let you describe config declaratively. Each field states its type and constraints; validation produces a fully typed object.

import { z } from "zod";
const EnvSchema = z.object({
  PORT: z.coerce.number().int().positive(),
  NODE_ENV: z.enum(["development", "production"]),
  DATABASE_URL: z.string().url(),
});

Coercion Built In

Schemas can coerce strings into the right types. z.coerce.number() turns "8081" into 8081, so raw env strings become real numbers safely.

// "8081" -> 8081 via z.coerce.number()

Parsing and Failing Fast

Calling parse validates everything. If anything is invalid, zod throws a detailed error you can log and exit on, stopping startup immediately.

function loadConfig() {
  const result = EnvSchema.safeParse(process.env);
  if (!result.success) {
    console.error(result.error.format());
    process.exit(1);
  }
  return result.data;
}

Inferring the Type

A huge benefit: the validated type is derived from the schema with z.infer. The schema is the single source of truth for both runtime checks and compile-time types.

type Env = z.infer<typeof EnvSchema>;
// { PORT: number; NODE_ENV: "development" | "production"; DATABASE_URL: string }

Descriptive Errors

Schema validators report exactly which field failed and why, e.g. "PORT: expected positive number". Clear messages make misconfiguration trivial to diagnose.

// e.g. { PORT: { _errors: ["Expected number, received nan"] } }

Optional and Default Fields

Schemas express optionality and defaults directly, removing hand-written fallback logic and keeping all the rules in one declaration.

const Schema = z.object({
  LOG_LEVEL: z.enum(["info", "debug"]).default("info"),
  TIMEOUT_MS: z.coerce.number().optional(),
});

Validate Once, Use Everywhere

Run validation a single time at boot and export the resulting typed object. Downstream code trusts that config is present and well-formed.

export const config = loadConfig();

Beyond Env: Files and Args

The same schema can validate config from a JSON file or merged sources, not just process.env. The validation step is independent of where values originate.

Why Schemas Beat Ad-Hoc Checks

A schema unifies validation and typing, produces consistent rich errors, supports coercion and defaults, and fails fast, replacing scattered manual if checks with one declaration.

Quick Check

Quick check on this lesson.

Recap

A config schema (e.g. zod) declares types, constraints, coercion, and defaults in one place, validates at startup to fail fast with descriptive errors, and lets you z.infer the typed config from that single source of truth.

Frequently asked questions

Is the “Schema-Validated Config” lesson free?

Yes — the full text of “Schema-Validated Config” is free to read here on the web, and the TypeScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the TypeScript Academy course, upgrade to CoddyKit PRO.

What will I learn in “Schema-Validated Config”?

Validate config at startup with a schema. You practise TypeScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start TypeScript Academy?

No prior experience is required. TypeScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Schema-Validated Config” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this TypeScript Academy lesson?

Yes. Every TypeScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Typing Environment Variables
  2. Schema-Validated Config
  3. Config Layering and Defaults
  4. Secrets and Type Safety
← Back to TypeScript Academy