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.
Code
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
zodas 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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.