Dotenv Validator CLI
A Node CLI that loads a .env file, checks it against a declared schema of required keys and types, and exits non-zero with a report on failure.
Project
node-dotenv-validate
Entry point: env-validate.mjs
Install
node --versionRun
node env-validate.mjs .env config.schema.jsonTest
node --test env.test.mjsExpected output
Prints OK and exits 0 when every required key is present and typed correctly, or lists the offending keys and exits 1.Dependencies
- node >=20
What it does
Parses simple KEY=value lines, then validates each declared key for presence and type (string, number, boolean, url). Missing or mistyped values are collected and reported together so you can fix them in one pass.
import { readFileSync } from 'node:fs';
const parseEnv = (text) => Object.fromEntries(text.split(/\r?\n/)
.map((l) => l.replace(/^\s*#.*$/, '').trim()).filter(Boolean)
.map((l) => { const i = l.indexOf('='); return [l.slice(0, i).trim(), l.slice(i + 1).trim()]; }));
const TYPES = {
string: (v) => typeof v === 'string',
number: (v) => v !== '' && !Number.isNaN(Number(v)),
boolean: (v) => v === 'true' || v === 'false',
url: (v) => { try { new URL(v); return true; } catch { return false; } },
};
const [envFile, schemaFile] = process.argv.slice(2);
const env = parseEnv(readFileSync(envFile, 'utf8'));
const schema = JSON.parse(readFileSync(schemaFile, 'utf8'));
const errors = [];
for (const [key, type] of Object.entries(schema)) {
if (env[key] === undefined) errors.push('missing: ' + key);
else if (!TYPES[type](env[key])) errors.push('invalid ' + type + ': ' + key);
}
if (errors.length) { console.error(errors.join('\n')); process.exit(1); }
console.log('OK: ' + Object.keys(schema).length + ' keys valid');
Run and verify
node env-validate.mjs .env config.schema.json
Run the test command to check the implementation: node --test env.test.mjs.
Expected Output
For a valid environment the validator reports success and exits 0:
OK: 4 keys valid
Limitations
Parses only simple KEY=value lines without quotes or interpolation, which covers most .env files but not shell-style quoting or variable references.