@ibnushahraa/dotenv-guard
v1.4.0
Published
Secure & validate your .env files with encryption and schema validation
Maintainers
Readme
@ibnushahraa/dotenv-guard
🔐 Secure & validate your .env files with encryption, schema validation, and CLI tools.
Think of it as dotenv on steroids — with guardrails for production-ready apps.
✨ Features
- 🔒 AES-256-GCM Encryption → keep
.envsecrets safe with authenticated encryption - 🗝 Auto-Generated Master Key → stored in
~/.dotenv-guard/master.key(no native dependencies) - ✅ Schema Validation → enforce required keys, regex patterns, enums
- ⚡ CLI Generator → auto-generate
.env.*(Node or Vite) - 🔄 Sync API → drop-in replacement for
dotenv.config()(noawait) - 🌍 Multi-Environment → auto-load
.env.[mode]based on NODE_ENV - 🛡️ Vite Security → safe template with proper VITE_ prefix usage
- 📦 Zero Native Dependencies → works with CommonJS & ESM
- 🔓 Quote Stripping → automatically strips quotes from
.envvalues (v1.4.0+)
Note: v1.3.0+ uses pure Node.js crypto (no keytar/native deps). Legacy keytar format still supported for migration.
📦 Installation
npm install @ibnushahraa/dotenv-guard🚀 Usage
1. Basic (like dotenv)
// CommonJS
require("@ibnushahraa/dotenv-guard").config();
// ESM
import { config } from "@ibnushahraa/dotenv-guard";
config();
console.log(process.env.DB_HOST);2. Multi-Environment Mode (Auto-load based on environment)
Load different .env files based on environment mode:
import { config } from "@ibnushahraa/dotenv-guard";
// Load based on environment variable
config({
mode: process.env.DOTENV_GUARD_MODE || 'development'
});
// Or based on hostname (for server-specific configs)
const os = require('os');
config({
mode: os.hostname() === 'ubuntu' ? 'production' : 'development'
});
// Or check HOSTNAME env var
config({
mode: process.env.HOSTNAME === 'production-server' ? 'production' : 'development'
});How it works:
- When
modeis specified, it loads multiple files in this priority order:.env(base configuration).env.local(local overrides, gitignored).env.[mode](e.g.,.env.production).env.[mode].local(e.g.,.env.production.local)
- Later files override earlier ones
- Only existing files are loaded
Example setup:
# .env - base config (committed to git)
DB_HOST=localhost
API_URL=http://localhost:3000
# .env.production - production config (committed to git)
DB_HOST=prod-db.example.com
API_URL=https://api.example.com
# .env.local - local development overrides (gitignored)
DB_PASSWORD=local-dev-password// In your app
config({ mode: process.env.DOTENV_GUARD_MODE || 'development' });Deployment:
# Docker/Kubernetes
ENV DOTENV_GUARD_MODE=production
# Or in your .env file on production server
DOTENV_GUARD_MODE=production3. With schema validation
Create env.schema.json:
{
"DB_HOST": { "required": true, "regex": "^[a-zA-Z0-9_.-]+$" },
"DB_PORT": { "required": true, "regex": "^[0-9]+$" },
"NODE_ENV": {
"required": true,
"enum": ["development", "production", "test"]
}
}Enable validator:
import { config } from "@ibnushahraa/dotenv-guard";
config({ validator: true });
// Or with mode
config({
mode: process.env.DOTENV_GUARD_MODE || 'development',
validator: true
});If invalid → app exits (process.exit(1)).
4. Vite Projects (Multi-Environment)
Option 1: Use the Vite Plugin (recommended)
npm install @ibnushahraa/vite-plugin-dotenv-guard// vite.config.js
import dotenvGuard from '@ibnushahraa/vite-plugin-dotenv-guard';
export default defineConfig({
plugins: [
dotenvGuard({
validator: true
})
]
});Option 2: Core Package (Not Recommended)
For Vite projects, use the vite-plugin instead (Option 1).
If you must use core package in vite.config.js:
// vite.config.js (NOT RECOMMENDED - use vite-plugin instead)
import { config } from "@ibnushahraa/dotenv-guard";
// Load specific env file
config({
path: '.env.development', // Manual file selection
enc: false, // Decrypt to plaintext
validator: true
});🖥 CLI Usage
npx dotenv-guard initOptions:
npx dotenv-guard init # choose template
npx dotenv-guard init custom # interactive key-value input
npx dotenv-guard init schema # generate env.schema.json from .env
npx dotenv-guard encrypt [file] # encrypt .env
npx dotenv-guard decrypt [file] # decrypt .env
npx dotenv-guard -v # show version- Auto-detects Node or Vite
- Creates
.env.development,.env.production, etc.
🔑 Master Key Storage
The encryption master key is stored with automatic fallback for production-ready deployment:
Storage Priority
Environment Variable (recommended for production)
export DOTENV_GUARD_MASTER_KEY=your-64-char-hex-key- Best for CI/CD, Docker, Kubernetes
- Works in serverless environments (AWS Lambda, etc.)
- No filesystem dependency
User Home Directory (default for development)
~/.dotenv-guard/master.key- Auto-generated on first use
- Persists across projects
- Secure file permissions (0600)
Project Directory (fallback for restricted environments)
./.dotenv-guard/master.key- Used when home directory is not writable
- Good for Docker containers without persistent home
- Remember to add to
.gitignore
Temp Directory (last resort)
/tmp/.dotenv-guard/master.key- For serverless/lambda environments
- Ephemeral, regenerated on each cold start
Production Deployment
Docker / Kubernetes:
ENV DOTENV_GUARD_MASTER_KEY=your-key-hereAWS Lambda:
aws lambda update-function-configuration \
--function-name my-function \
--environment Variables={DOTENV_GUARD_MASTER_KEY=your-key}Vercel / Netlify:
Add DOTENV_GUARD_MASTER_KEY in dashboard environment variables.
Key Generation
Generate a master key manually:
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"📚 API Reference
config(options)
Main function to load and validate environment variables.
const { config } = require('@ibnushahraa/dotenv-guard');
config({
path: '.env', // .env file path (default: '.env')
validator: false, // Enable schema validation (default: false)
schema: 'env.schema.json' // Schema file path (default: 'env.schema.json')
});
// After config(), all env vars are loaded to process.env
console.log(process.env.DB_HOST);Options:
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| path | string | '.env' | Path to .env file (single file mode) |
| mode | string | undefined | Environment mode for multi-file loading (e.g., 'development', 'production') |
| validator | boolean | false | Enable schema validation |
| schema | string | 'env.schema.json' | Schema file path |
Note: Encryption is always enabled. Plugin auto-decrypts encrypted values at runtime (read-only, no file modification).
Common use cases:
// Basic usage (auto-decrypt encrypted values)
config();
// With validation
config({ validator: true });
// Multi-environment mode (recommended)
config({
mode: process.env.DOTENV_GUARD_MODE || 'development'
});
// Multi-environment with validation
config({
mode: process.env.DOTENV_GUARD_MODE || 'development',
validator: true
});
// Hostname-based mode selection
const os = require('os');
config({
mode: os.hostname() === 'ubuntu' ? 'production' : 'development'
});
// Single file mode (legacy)
config({ path: '.env.production' });
// With custom schema
config({ validator: true, schema: 'config/env.schema.json' });🧪 Testing
npm testAll tests cover:
- ✅ Encryption/Decryption
- ✅ Multi-environment loading
- ✅ Schema validation
- ✅ CLI commands
- ✅ CommonJS & ESM imports
- ✅ Vite detection
💡 Why dotenv-guard?
| Feature | dotenv | dotenv-guard | |---------|--------|--------------| | Load .env files | ✅ | ✅ | | Encryption | ❌ | ✅ AES-256-GCM | | Schema validation | ❌ | ✅ Regex + Enum | | Multi-environment | ❌ | ✅ Auto-load | | CLI tools | ❌ | ✅ Full-featured | | Vite optimization | ❌ | ✅ Security-first | | Key storage | ❌ | ✅ Auto-generated (no native deps) | | Quote stripping | ❌ | ✅ Standard dotenv behavior |
Not a replacement for dotenv → a secure extension for production apps.
Migration Note: v1.3.0+ deprecated keytar in favor of pure Node.js crypto. Legacy keytar-encrypted files are still supported.
📁 Examples
Check out the example/ folder for working demos:
- Basic usage
- Schema validation
- Multi-environment setup
- Encryption/decryption
🌐 Ecosystem
- Vite Plugin: @ibnushahraa/vite-plugin-dotenv-guard
Best Practices
- ✅ Store encrypted
.envin git (with selective encryption viaenv.enc.json) - ✅ Keep
env.schema.jsonin git for validation - ✅ Use
.env.localfor local overrides (gitignored) - ✅ Never commit plaintext secrets
- ✅ Use
@ibnushahraa/vite-plugin-dotenv-guardfor Vite projects - ✅ Use
npx dotenv-guard decryptto convert encrypted → plaintext (if needed)
📄 License
MIT © 2025
