Validate the environment at startup
Read process.env once at startup with coercion and defaults, fail with every missing or malformed variable listed at once, and hand the rest of the program a typed, frozen config.
The environment is text. Read it once, coerce what needs coercing, and stop with every problem at once rather than the first.
import { boolean, enumOf, number, object, optional, parse, string } from 'truefit';
import { httpUrl } from 'truefit/formats';
const Env = object({
DATABASE_URL: string({ format: httpUrl }),
PORT: optional(number({ int: true, min: 1, max: 65535, coerce: true }), { default: 3000 }),
LOG_LEVEL: optional(enumOf(['debug', 'info', 'warn', 'error']), { default: 'info' }),
DRY_RUN: optional(boolean({ coerce: true }), { default: false }),
});
const result = parse(Env, process.env);
if (!result.ok) {
for (const issue of result.issues) console.error(`${issue.path.slice(1)}: ${issue.message}`);
process.exit(1);
}
const { DATABASE_URL, PORT, LOG_LEVEL, DRY_RUN } = result.value;
console.log(Object.freeze({ DATABASE_URL, PORT, LOG_LEVEL, DRY_RUN }));{
DATABASE_URL: 'https://db.example',
PORT: 8080,
LOG_LEVEL: 'info',
DRY_RUN: false
}DATABASE_URL: expected a value, got undefined. fix: add "DATABASE_URL"
PORT: expected a number, got string "http". fix: send a finite number
LOG_LEVEL: expected one of "debug", "info", "warn", "error", got string "loud". fix: send one of themThe object keeps unknown keys by default, so the rest of process.env passes through untouched and
is left out of the config by the destructuring. issue.path.slice(1) turns /PORT into the
variable's name.
Coming from ajv
An ajv alternative that reads the JSON Schema you already have: fromJsonSchema turns a 2020-12, draft-07 or OpenAPI 3.0 document into a truefit schema with inferred-type builders beside it, graded against ajv's own verdicts on 2,385 pairs, with no eval by default.
Validate a request body
Validate a JSON request body in any Node server, strip keys the API does not know, answer 400 with every issue as JSON Pointer paths a client can map onto its form fields, and keep the handler typed.