How to Validate Environment Variables at Startup
Check every environment variable when a Node.js app boots, with a schema that reports all problems at once, coerces types and stops before serving traffic.

A misconfigured app that starts anyway is worse than one that refuses to start. If DATABASE_URL is missing, the server may boot, pass its health check and fail on the first query, minutes after a deploy that looked green. If PORT is set to eighty, Number("eighty") is NaN and listen(NaN) behaves in ways nobody planned. Validating the environment when the process boots turns those slow, confusing failures into one clear message at the moment of the deploy. This post builds a validator in three steps: a hand-written check with no dependencies, the same check with a schema library, and the wiring that runs it before the app accepts traffic. The samples target Node.js 26 and use Zod 4 for the library version, documented at zod.dev.
What a startup check must do
A useful validator does four things, and the order matters.
Collect every problem. Stopping at the first missing variable makes a deploy a game of fixing one error and redeploying. Report all of them together.
Convert types. Turn
"8080"into a number and"true"into a boolean so the rest of the app never parses strings.Apply defaults. Fill in the values that have a safe fallback.
Run before anything else. Validate before opening a port, connecting to a database or starting workers, so a failure has no side effects to undo.
The previous post on configuration throws on the first bad value, which is enough for a few settings. Once an app has a dozen, collecting errors pays off.
A validator with no dependencies
Describe each variable as a small object: its name, how to parse it, and whether a default exists. Run every rule, gather the messages, and throw once.
const rules = {
NODE_ENV: { parse: (v) => v, default: "development", oneOf: ["development", "test", "production"] },
PORT: { parse: (v) => Number(v), default: 3000, check: Number.isInteger, hint: "an integer" },
DATABASE_URL: { parse: (v) => v, required: true, check: (v) => URL.canParse(v), hint: "a URL" },
CACHE_TTL: { parse: (v) => Number(v), default: 60, check: (v) => Number.isInteger(v) && v >= 0, hint: "a non-negative integer" },
};
export function validateEnv(source = process.env) {
const values = {};
const problems = [];
for (const [name, rule] of Object.entries(rules)) {
const raw = source[name];
if (raw === undefined || raw === "") {
if (rule.required) problems.push(`${name} is required`);
else values[name] = rule.default;
continue;
}
const parsed = rule.parse(raw);
if (rule.oneOf && !rule.oneOf.includes(parsed)) {
problems.push(`${name} must be one of ${rule.oneOf.join(", ")}, got "${raw}"`);
} else if (rule.check && !rule.check(parsed)) {
problems.push(`${name} must be ${rule.hint}, got "${raw}"`);
} else {
values[name] = parsed;
}
}
if (problems.length > 0) {
throw new Error(`Invalid environment:\n- ${problems.join("\n- ")}`);
}
return Object.freeze(values);
}The function takes the environment as an argument, defaulting to process.env. That makes it testable with a plain object and keeps the global out of the logic. URL.canParse() is a static method on the built-in URL class, available in current Node.js, that returns a boolean instead of throwing. Parsing happens before checking, so "eighty" becomes NaN, and Number.isInteger(NaN) is false.
Call it with a broken environment and read the report.
import { validateEnv } from "./validate-env.js";
try {
validateEnv({ NODE_ENV: "staging", PORT: "eighty", CACHE_TTL: "-5" });
} catch (error) {
console.log(error.message);
}Invalid environment:
- NODE_ENV must be one of development, test, production, got "staging"
- PORT must be an integer, got "eighty"
- DATABASE_URL is required
- CACHE_TTL must be a non-negative integer, got "-5"All four problems appear in one run, in the order the rules are declared. With a valid environment the same call returns the typed values.
import { validateEnv } from "./validate-env.js";
const env = validateEnv({
DATABASE_URL: "postgres://localhost/app",
PORT: "8080",
});
console.log(env);{
NODE_ENV: 'development',
PORT: 8080,
DATABASE_URL: 'postgres://localhost/app',
CACHE_TTL: 60
}NODE_ENV and CACHE_TTL came from their defaults, PORT is now a number, and the object is frozen.
The same check with a schema library
Hand-written rules are fine for a handful of variables. A schema library trades a dependency for less code, better messages and inferred TypeScript types. Zod parses an object against a schema, and safeParse returns a result instead of throwing, so you can format the failure yourself.
import { z } from "zod";
const schema = z.object({
NODE_ENV: z.enum(["development", "test", "production"]).default("development"),
PORT: z.coerce.number().int().default(3000),
DATABASE_URL: z.url(),
CACHE_TTL: z.coerce.number().int().nonnegative().default(60),
DEBUG: z.stringbool().default(false),
});
export function loadEnv(source = process.env) {
const result = schema.safeParse(source);
if (!result.success) {
const lines = result.error.issues.map(
(issue) => `${issue.path.join(".")}: ${issue.message}`,
);
throw new Error(`Invalid environment:\n- ${lines.join("\n- ")}`);
}
return Object.freeze(result.data);
}The pieces map onto the four jobs.
z.coerce.number()converts the string withNumber()before checking, so"8080"passes and"eighty"fails..default(3000)fills in a missing value.z.url()checks the value is a valid URL, and a variable with no default is required.z.stringbool()converts strings such as"true","false","1","0","yes"and"no"to a boolean, which avoids the trap where any non-empty string is truthy.safeParsereports every failing field, not just the first.
Run it with the same broken input.
import { loadEnv } from "./env-zod.js";
try {
loadEnv({ NODE_ENV: "staging", PORT: "eighty", CACHE_TTL: "-5" });
} catch (error) {
console.log(error.message);
}Invalid environment:
- NODE_ENV: Invalid option: expected one of "development"|"test"|"production"
- PORT: Invalid input: expected number, received NaN
- DATABASE_URL: Invalid input: expected string, received undefined
- CACHE_TTL: Too small: expected number to be >=0Wording of the messages belongs to the library and can change between versions, so do not assert on exact text in tests. Check the number of issues or the paths instead. A schema also gives you a type for free: in TypeScript, z.infer<typeof schema> is the type of the validated object, so env.PORT is a number everywhere it is used.
Run it before anything else
The check is only useful if nothing else happens first. Make the entry point validate, then import the rest of the app.
import { loadEnv } from "./env-zod.js";
const env = loadEnv();
const { createApp } = await import("./app.js");
const app = createApp(env);
app.listen(env.PORT, () => {
console.log(`listening on ${env.PORT} in ${env.NODE_ENV}`);
});Passing env into createApp instead of letting modules read process.env keeps the dependency explicit and makes the app testable with a fake environment. The dynamic import() guarantees app.js and everything it imports is not evaluated until validation has passed, which matters if any module connects to something at import time.
On a failure, the process should exit with a non-zero status, so the supervisor and the deploy pipeline see it. An uncaught error already does that, but a handler makes the output tidy.
try {
const env = loadEnv();
// start the app
} catch (error) {
console.error(error.message);
process.exit(1);
}With a systemd unit using Restart=on-failure, a bad value then produces a visible crash loop with the full message in the journal, not a half-working service.
Where the check lives in a larger project
In a service with several entry points, such as a web server, a worker and a migration script, the same variables are not needed everywhere. A worker does not need PORT, and a migration script does not need a session secret. Keep one schema per concern and compose them, so each entry point validates exactly what it uses and a missing web setting does not stop a one-off script.
A common arrangement is a small shared schema for the basics, NODE_ENV and LOG_LEVEL, and a schema per process that extends it. Each entry file loads the schema it needs on its first line. The benefit is that the error message tells an operator which process is missing which setting, and nobody has to define dummy values for variables a process never reads. The cost is a little duplication, which is worth it because a schema that demands every variable for every process is one people learn to satisfy with fake values, and a fake value defeats the point of validating.
It also helps to print which variables were found, with the names only, when the app starts in a development environment. Seeing the list of names, without values, makes a typo such as DATABSE_URL easy to spot, because the correct name is missing from the output and the misspelled one is not in the schema at all. Unknown variables in the environment are normal, since the operating system sets many, so never fail on extra names. Fail only on names your schema declares.
Validate secrets without printing them
The error text names variables and, in the examples above, echoes the bad value. Echoing is helpful for PORT and harmful for a password. Never include the raw value for settings that hold secrets. Name the variable and the rule instead, as SESSION_SECRET: must be at least 32 characters, and rely on length or format checks that do not reveal content.
const schema = z.object({
SESSION_SECRET: z.string().min(32),
});Test the validator
Because the function takes its input as a parameter, a test needs no global state.
import { test } from "node:test";
import assert from "node:assert/strict";
import { validateEnv } from "./validate-env.js";
test("reports every problem at once", () => {
assert.throws(() => validateEnv({ PORT: "x" }), (error) => {
return error.message.includes("PORT") && error.message.includes("DATABASE_URL");
});
});
test("applies defaults", () => {
const env = validateEnv({ DATABASE_URL: "postgres://localhost/app" });
assert.equal(env.PORT, 3000);
});ā reports every problem at once (1.1ms)
ā applies defaults (0.2ms)Timings will differ. A test of this kind is cheap and catches the case where someone adds a variable to the app and forgets to add it to the schema.
When this is too much
For a script that reads one variable, a schema library is overkill and a single if is the right size. The startup check earns its place in a long-running service with several settings and more than one person deploying it. Do not validate lazily, inside request handlers: by then the failure is already a user's problem.


