env-safer
v1.0.0
Published
Load environment variables from a .env file with safety checks against an example file.
Maintainers
Readme
env-safer
A safer way to load and validate your environment variables in Node.js projects. Compare your .env file against an example file, check for missing or empty variables, and use it both as a library and a CLI tool.
Features
- Ensures all variables in
.env.exampleare present in your.env - Optionally checks for empty variables
- Strict mode: throws on missing/empty variables
- Loads .env variables using dotenv
- Works as a Node.js library or CLI
How it works
When you use env-safer, your .env file is loaded using the dotenv package. This means all variables defined in your .env will be available globally in your Node.js process, just like with dotenv. The library then compares these variables to your .env.example to check for missing or empty values.
Installation
npm install env-saferOr globally for CLI usage:
npm install -g env-saferUsage
As a Node.js Library
import { loadSafeEnv, EnvValidationError } from "env-safer";
try {
const result = loadSafeEnv({
envPath: ".env", // optional, default: '.env'
envExamplePath: ".env.example", // optional, default: '.env.example'
checkEmpty: true, // optional, default: false
strict: true, // optional, default: false
});
// result: { valid, missing, empty, env }
console.log(result);
} catch (err) {
if (err instanceof EnvValidationError) {
console.error("Environment validation failed:", err.message);
} else {
throw err;
}
}As a CLI
After installing globally or as a project dependency, you can use the CLI:
env-safer --env .env --example .env.example --check-empty --strictCLI Options
-e, --env <path>: Path to your .env file (default: .env)-x, --example <path>: Path to your .env.example file (default: .env.example)-c, --check-empty: Warn if variables exist but are empty-s, --strict: Fail if there are empty or missing variables-h, --help: Show help message
Example: Add to your package.json scripts
"scripts": {
"check-env": "env-safer --env .env --example .env.example --check-empty"
}Then run:
npm run check-envAPI
loadSafeEnv(options)
envPath(string): Path to your .env file (default:.env)envExamplePath(string): Path to your .env.example file (default:.env.example)checkEmpty(boolean): If true, checks for empty variables (default:false)strict(boolean): If true, throwsEnvValidationErrorif invalid (default:false)
Returns:
{
valid: boolean,
missing: string[],
empty: string[],
env: object // parsed env variables
}Throws EnvValidationError in strict mode if there are missing or empty variables.
