pretty-env
v1.0.1
Published
Validates and prettifies .env files with clear error messages. Warns on missing keys, typos, or insecure values. Drop-in replacement for dotenv.
Maintainers
Readme
🔥 pretty-env
Validates and prettifies .env files with zero config
Every JavaScript project uses .env files. dotenv loads them, but it doesn't validate anything. pretty-env solves this with:
✅ Validation — Catches typos, missing required keys, security issues
🔒 Security warnings — Detects weak credentials, sensitive unencrypted values
💚 Zero config — Works with one line: require('pretty-env').load()
🎨 Beautiful output — Clear error messages with line numbers
🛠️ CLI tool — Validate .env files from terminal
⚡ Drop-in replacement — Compatible with dotenv
Quick Start
Installation
npm install pretty-envUsage (One Line!)
const env = require('pretty-env').load();
console.log(env.parsed.DATABASE_URL); // ✅ Validated and loadedIn your .env file
# Database
DATABASE_URL=postgresql://user:pass@localhost/mydb
# Authentication
JWT_SECRET=your-secret-key-min-32-chars-is-better-for-security
API_KEY=sk_live_1234567890abcdef
# Settings
NODE_ENV=production
PORT=3000Features
1. Automatic Validation
const { load } = require('pretty-env');
// Validates format, required keys, security issues
const env = load({
required: ['DATABASE_URL', 'JWT_SECRET']
});
// ✅ Throws helpful error if keys missing:
// ❌ Failed to parse .env file (1 error)
// Validation errors:
// 1. Required key "DATABASE_URL" is missing2. Security Warnings
Detects common security issues:
# .env
DATABASE_PASSWORD=test # ⚠️ Weak value
API_KEY=abc # ⚠️ Too short
JWT_SECRET=password123 # 🔴 CRITICAL: Common weak passwordconst env = load({ warnings: true });
// Console output:
// ⚠️ Warnings (3)
// 1. 🔒 Security risk: "DATABASE_PASSWORD" appears sensitive but value is weak
// 2. 🔒 Security risk: "API_KEY" appears sensitive but value is weak
// 3. ⚠️ Insecure value detected in "JWT_SECRET"3. Strict Mode (Whitelist Keys)
const env = load({
strict: true,
allowed: ['DATABASE_URL', 'PORT', 'NODE_ENV']
});
// ❌ Throws if .env has any other keys4. CLI Tool
Validate from terminal:
# Validate current .env
$ npx pretty-env validate
# Validate specific file
$ npx pretty-env validate .env.production
# Compare two files
$ npx pretty-env compare .env.example .env
# Show help
$ npx pretty-env helpOutput example:
🔍 Validating .env...
────────────────────────
✅ Valid! Loaded 5 variables
📋 Variables:
DATABASE_URL = postgresql://localhost:5432/mydb
NODE_ENV = development
PORT = 3000
JWT_SECRET = (hidden for security)
DEBUG = true
⚠️ Warnings (2)
1. Empty value for key "LOG_LEVEL" [WARN]
2. 🔒 Security risk: "API_KEY" appears sensitive [SECURITY]
✨ All good to go!API Reference
load(options?)
Simple function to load and validate .env file. Returns { parsed, warnings, filePath }.
Parameters:
load({
path: '.env', // File path
required: ['DATABASE_URL'], // Required keys
allowed: null, // Whitelist keys (null = all allowed)
strict: true, // Throw on unknown keys + empty values
warnings: true, // Show security/convention warnings
trim: true, // Trim values
colorize: true, // Colorize output
merge: true // Merge into process.env
});Returns:
{
parsed: { DATABASE_URL: '...', PORT: '3000' }, // Validated env vars
warnings: [ // Array of warnings
{ line: 5, key: 'API_KEY', message: '...', severity: 'SECURITY' }
],
filePath: '/full/path/.env'
}PrettyEnv Class
For advanced usage:
const { PrettyEnv } = require('pretty-env');
const env = new PrettyEnv({
required: ['DATABASE_URL'],
strict: true,
warnings: true
});
// Load file
const result = env.load('.env');
// Get specific value with fallback
const dbUrl = env.get('DATABASE_URL', 'sqlite://db.sqlite');
// Get value from parsed env (not process.env)
console.log(env.env.PORT);
// Pretty print loaded variables
env.print();
// Get detailed report
console.log(env.report());Methods:
| Method | Description |
|--------|-------------|
| parse(content) | Parse raw .env content |
| load(filePath) | Load and validate file |
| get(key, default) | Get value with fallback |
| print() | Pretty print all variables |
| report() | Get detailed report |
| validateRequired() | Check required keys present |
| validateAllowed() | Check only allowed keys exist |
Error Handling
const { PrettyEnvError } = require('pretty-env');
try {
load({ required: ['DATABASE_URL'] });
} catch (error) {
if (error instanceof PrettyEnvError) {
console.error(error.toString());
// ❌ Failed to parse .env file (1 error)
// Validation errors:
// 1. Required key "DATABASE_URL" is missing
console.error(error.errors); // Array of detailed errors
}
}Common Patterns
Best Practice: Require + Validate at Startup
// config.js
const { load } = require('pretty-env');
const env = load({
path: process.env.ENV_FILE || '.env',
required: [
'DATABASE_URL',
'JWT_SECRET',
'NODE_ENV'
],
allowed: [
'DATABASE_URL', 'JWT_SECRET', 'NODE_ENV', 'PORT',
'LOG_LEVEL', 'DEBUG', 'API_KEY'
]
});
module.exports = env.parsed;Usage:
const config = require('./config');
app.get('/api/users', (req, res) => {
db.connect(config.DATABASE_URL);
});Development vs Production
# .env.example
DATABASE_URL=
JWT_SECRET=
NODE_ENV=# Compare files
pretty-env compare .env.example .env.productionDocker with require-env
FROM node:18
WORKDIR /app
COPY . .
# Will fail if .env is missing required keys
RUN npm run validate:env
CMD ["node", "server.js"]{
"scripts": {
"validate:env": "pretty-env validate .env"
}
}Comparison
| Feature | pretty-env | dotenv | dotenv-safe | joi-dotenv | |---------|-----------|--------|------------|-----------| | Load .env | ✅ | ✅ | ✅ | ✅ | | Validate format | ✅ | ❌ | ✅ | ✅ | | Required keys | ✅ | ❌ | ✅ | ✅ | | Security warnings | ✅ | ❌ | ❌ | ❌ | | CLI tool | ✅ | ❌ | ❌ | ❌ | | Compare files | ✅ | ❌ | ❌ | ❌ | | Zero config | ✅ | ✅ | ❌ | ❌ | | Size | ~3 KB | ~2 KB | ~2 KB | ~15 KB |
Examples
Example 1: Express.js App
// app.js
const express = require('express');
const { load } = require('pretty-env');
// FIRST: Load & validate env
const env = load({
required: ['DATABASE_URL', 'JWT_SECRET', 'PORT'],
warnings: true // Show security warnings during dev
});
const app = express();
app.get('/health', (req, res) => {
res.json({ status: 'ok', env: process.env.NODE_ENV });
});
app.listen(env.parsed.PORT, () => {
console.log(`Server running on port ${env.parsed.PORT}`);
});Example 2: Database Configuration
// db.js
const { PrettyEnv } = require('pretty-env');
const db = new PrettyEnv({
required: ['DATABASE_URL'],
allowed: ['DATABASE_URL', 'DATABASE_POOL_SIZE', 'DATABASE_LOGGING']
});
const config = db.load();
module.exports = {
connectionString: config.parsed.DATABASE_URL,
max: parseInt(config.parsed.DATABASE_POOL_SIZE || 10),
logging: config.parsed.DATABASE_LOGGING === 'true'
};Example 3: CI/CD Pipeline
#!/bin/bash
# deploy.sh
echo "📋 Validating .env..."
npx pretty-env validate .env.production
if [ $? -eq 0 ]; then
echo "✅ Env validation passed"
npm run build
npm run deploy
else
echo "❌ Env validation failed"
exit 1
fiTips & Tricks
Tip 1: Use in Immediate Mode
// No need to store in variable
require('pretty-env').load({
required: ['DATABASE_URL', 'API_KEY']
});
// ... now process.env is populated and validatedTip 2: Validate on CI/CD
{
"scripts": {
"validate": "pretty-env validate .env.example && pretty-env validate .env",
"ci": "npm run validate && npm test"
}
}Tip 3: Compare Before Deployment
# Make sure you're not deploying old config
npx pretty-env compare .env.example .env.production
# Fix any issues
npm run validate:envTip 4: Development vs CI Differences
load({
warnings: process.env.NODE_ENV === 'development', // Verbose in dev
strict: process.env.NODE_ENV === 'production' // Strict in prod
});Security
- Never commit
.env— Use.env.exampleinstead - Review warnings — Security warnings highlight risky patterns
- Use strong secrets — Minimum 32 characters for sensitive values
- Rotate regularly — Treat API keys like passwords
What pretty-env Does NOT Do
- 🚫 Does not encrypt values
- 🚫 Does not hide values in logs
- 🚫 Does not transmit data
For encryption, use tools like dotenv-vault alongside pretty-env!
FAQs
Q: Is pretty-env required for projects using dotenv?
A: No, but we recommend it for catching configuration errors early. Works great alongside dotenv!
Q: Does it support .env.local, .env.production, etc?
A: Yes! Pass the path: load({ path: '.env.production' })
Q: Can I use pretty-env in monorepos?
A: Yes! Each package can have its own config validation.
Q: Performance impact?
A: Negligible (~1-2ms per load). Safe to call at startup.
Q: TypeScript support?
A: Full JSDoc types. TypeScript support coming in v2.
Contributing
Contributions welcome!
git clone https://github.com/likhithsp/pretty-env.git
cd pretty-env
npm install
npm testLicense
MIT © 2026 Likhith SP
Made with ❤️ to catch .env bugs before production
