Load environment variables from a .env file with safety checks against an example file.
npm install env-safer.env file against an example file, check for missing or empty variables, and use it both as a library and a CLI tool.
.env.example are present in your .env
.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.
bash
npm install env-safer
`
Or globally for CLI usage:
`bash
npm install -g env-safer
`
---
Usage
$3
`js
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;
}
}
`
$3
After installing globally or as a project dependency, you can use the CLI:
`bash
env-safer --env .env --example .env.example --check-empty --strict
`
#### CLI Options
- -e, --env : Path to your .env file (default: .env)
- -x, --example : 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
`json
"scripts": {
"check-env": "env-safer --env .env --example .env.example --check-empty"
}
`
Then run:
`bash
npm run check-env
`
---
API
$3
- 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, throws EnvValidationError if invalid (default: false)
Returns:
`js
{
valid: boolean,
missing: string[],
empty: string[],
env: object // parsed env variables
}
`
Throws EnvValidationError` in strict mode if there are missing or empty variables.