npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@ibnushahraa/dotenv-guard

v1.4.0

Published

Secure & validate your .env files with encryption and schema validation

Readme

@ibnushahraa/dotenv-guard

npm version npm downloads Bundle Size license CI coverage Known Vulnerabilities Security

🔐 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 .env secrets 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() (no await)
  • 🌍 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 .env values (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 mode is specified, it loads multiple files in this priority order:
    1. .env (base configuration)
    2. .env.local (local overrides, gitignored)
    3. .env.[mode] (e.g., .env.production)
    4. .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=production

3. 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 init

Options:

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

  1. 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
  2. User Home Directory (default for development)

    ~/.dotenv-guard/master.key
    • Auto-generated on first use
    • Persists across projects
    • Secure file permissions (0600)
  3. 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
  4. 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-here

AWS 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 test

All 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


Best Practices

  • ✅ Store encrypted .env in git (with selective encryption via env.enc.json)
  • ✅ Keep env.schema.json in git for validation
  • ✅ Use .env.local for local overrides (gitignored)
  • ✅ Never commit plaintext secrets
  • ✅ Use @ibnushahraa/vite-plugin-dotenv-guard for Vite projects
  • ✅ Use npx dotenv-guard decrypt to convert encrypted → plaintext (if needed)

📄 License

MIT © 2025