Merge environment config with defaults
Merge environment variables over typed defaults in Node.js 24, converting strings to numbers and booleans and failing fast on bad values like PORT=abc.
const port = process.env.PORT || 3000 looks fine until PORT is set to an empty string or abc. Read each variable through a small converter and let the default decide the type.
const defaults = { port: 3000, debug: false, host: 'localhost', workers: 2 };
function fromEnv(env, base) {
const out = { ...base };
for (const [key, fallback] of Object.entries(base)) {
const raw = env[key.toUpperCase()];
if (raw === undefined || raw === '') continue;
if (typeof fallback === 'number') {
const n = Number(raw);
if (!Number.isFinite(n)) throw new Error(`${key.toUpperCase()} must be a number, got "${raw}"`);
out[key] = n;
} else if (typeof fallback === 'boolean') {
out[key] = ['1', 'true', 'yes'].includes(raw.toLowerCase());
} else {
out[key] = raw;
}
}
return Object.freeze(out);
}
console.log(fromEnv({ PORT: '8080', DEBUG: 'TRUE', WORKERS: '' }, defaults));
try {
fromEnv({ PORT: 'abc' }, defaults);
} catch (err) {
console.log(err.message);
}{ port: 8080, debug: true, host: 'localhost', workers: 2 }
PORT must be a number, got "abc"The type of each default drives the conversion, so PORT becomes a number and DEBUG a boolean, and every key you read has to be declared with a default first. An empty value counts as unset, which || handles but ?? does not, and Number('') would quietly give 0. A value that cannot convert stops startup with a clear message rather than surfacing later as NaN. See process.env.
Pass process.env in real code. Number accepts 0x1F and 1e3, so use parseInt with a pattern check if that is too lenient. Once you have nested settings or many required keys, a schema library such as Zod gives better messages than hand-rolled checks.