@dotenvage/node
v0.3.2
Published
Node.js bindings for dotenvage - Dotenv with age encryption
Downloads
1,260
Maintainers
Readme
@dotenvage/node
Node.js bindings for dotenvage - Dotenv with age encryption.
Features
- 🔒 Encrypt secrets in
.envfiles - Safely commit encrypted secrets to version control - 📦 Native performance - Built with NAPI-RS for fast Rust performance
- 🔄 Auto-detection - Automatically identifies which keys should be encrypted
- 🌳 File layering - Multiple
.env*files with automatic precedence - 💻 CLI support - Includes
dotenvagecommand-line tool - 📝 TypeScript support - Full TypeScript definitions included
Installation
npm install @dotenvage/nodeQuick Start
Basic Usage (Like dotenv)
import * as dotenvage from "@dotenvage/node";
// Load encrypted .env files into process.env
const loader = dotenvage.JsEnvLoaderNew();
loader.load(); // Mutates process.env (like dotenv.config())
// Now access variables
const apiKey = process.env.API_KEY;
const dbUrl = process.env.DATABASE_URL;Get Variables as Object (Non-mutating)
import * as dotenvage from "@dotenvage/node";
const loader = dotenvage.JsEnvLoaderNew();
const env = loader.getAllVariables(); // Returns Record<string, string>
// Use without modifying process.env
console.log(env.API_KEY);
console.log(env.DATABASE_URL);Encrypt and Decrypt Values
import * as dotenvage from "@dotenvage/node";
// Generate a new key pair
const manager = dotenvage.JsSecretManagerGenerate();
const publicKey = manager.publicKeyString(); // Share this public key
// Encrypt a secret
const secret = "sk_live_abc123";
const encrypted = manager.encryptValue(secret);
// Returns: "ENC[AGE:b64:...]"
// Decrypt it back
const decrypted = manager.decryptValue(encrypted);
console.log(decrypted === secret); // trueAPI Reference
JsEnvLoader
Loads and decrypts .env files.
JsEnvLoaderNew(): JsEnvLoader
Creates a new loader with a default SecretManager.
const loader = dotenvage.JsEnvLoaderNew();load(): void
Loads .env files from the current directory into process.env.
loader.load(); // Sets variables in process.envloadFromDir(dir: string): void
Loads .env files from a specific directory.
loader.loadFromDir("./config");getAllVariableNames(): string[]
Gets all variable names from all loaded .env files (without loading
into environment).
const names = loader.getAllVariableNames();
console.log(names); // ["API_KEY", "DATABASE_URL", ...]getAllVariables(): Record<string, string>
Gets all environment variables as an object (decrypted). Note: This loads variables into the process environment first.
const env = loader.getAllVariables();
console.log(env.API_KEY);resolveEnvPaths(dir: string): string[]
Computes the ordered list of env file paths that would be loaded.
const paths = loader.resolveEnvPaths(".");
console.log(paths); // [".env", ".env.local", ...]JsSecretManager
Manages encryption and decryption of secrets.
JsSecretManagerGenerate(): JsSecretManager
Generates a new random encryption key pair.
const manager = dotenvage.JsSecretManagerGenerate();JsSecretManagerNew(): JsSecretManager
Creates a SecretManager by loading the key from standard locations:
DOTENVAGE_AGE_KEYenvironment variableAGE_KEYenvironment variableEKG_AGE_KEYenvironment variable- Key file at
~/.local/state/dotenvage/dotenvage.key
const manager = dotenvage.JsSecretManagerNew();publicKeyString(): string
Gets the public key as a string (starts with age1).
const publicKey = manager.publicKeyString();encryptValue(plaintext: string): string
Encrypts a plaintext value.
const encrypted = manager.encryptValue("secret");decryptValue(value: string): string
Decrypts a value if it's encrypted; otherwise returns it unchanged.
const decrypted = manager.decryptValue(encrypted);isEncrypted(value: string): boolean
Checks if a value is in a recognized encrypted format.
const isEncrypted = manager.isEncrypted("ENC[AGE:b64:...]");Utility Functions
shouldEncrypt(key: string): boolean
Checks if a key name should be encrypted based on auto-detection patterns.
dotenvage.shouldEncrypt("API_KEY"); // true
dotenvage.shouldEncrypt("PORT"); // falseCLI Usage
The package includes a dotenvage CLI command:
npx dotenvage list
npx dotenvage get API_KEY
npx dotenvage dump --exportSee the main dotenvage README for full CLI documentation.
Next.js Integration
For Next.js applications, use the dedicated integration utilities:
// In next.config.mjs
import { loadEnv } from "@dotenvage/node/nextjs";
loadEnv();Or use the pre-initialization loader to ensure environment variables are available for Edge Runtime (middleware):
{
"scripts": {
"dev": "node -r @dotenvage/node/nextjs/preinit node_modules/.bin/next dev"
}
}See nextjs/README.md for complete Next.js
integration documentation.
TypeScript Examples
See the examples/ directory for TypeScript examples:
load-env.ts- Loading environment variablesencrypt-decrypt.ts- Encryption and decryptionapp-config.ts- Type-safe application configurationauto-encrypt.ts- Auto-detection patternsnextjs-config.ts- Basic Next.js usage example
File Layering
dotenvage supports automatic file layering with precedence:
.env- Base configuration.env.<ENV>- Environment-specific (e.g.,.env.production).env.<ENV>.<OS>- OS-specific (e.g.,.env.production.linux).env.<ENV>.<OS>.<ARCH>- Architecture-specific.env.<ENV>.<OS>.<ARCH>.<USER>- User-specific overrides.env.<ENV>.<OS>.<ARCH>.<USER>.<VARIANT>- Variant-specific (e.g.,.env.production.linux.amd64.alice.docker)
Files are loaded in specificity order - more specific files override
less specific ones. Dimension values can also be discovered from
loaded files (e.g., NODE_ENV=production in .env causes
.env.production to load).
Key Management
Setting the Encryption Key
Set one of these environment variables:
export DOTENVAGE_AGE_KEY="AGE-SECRET-KEY-1..."
export AGE_KEY="AGE-SECRET-KEY-1..."
export EKG_AGE_KEY="AGE-SECRET-KEY-1..."Generating a Key
const manager = dotenvage.JsSecretManagerGenerate();
const publicKey = manager.publicKeyString();
console.log(`Public key: ${publicKey}`);
console.log(`Set: export DOTENVAGE_AGE_KEY="<private-key>"`);Or use the CLI:
npx dotenvage keygenComparison with dotenv
| Feature | dotenv | @dotenvage/node |
| -------------------- | ------ | --------------- |
| Load .env files | ✅ | ✅ |
| Mutate process.env | ✅ | ✅ |
| Encrypt secrets | ❌ | ✅ |
| Commit to git safely | ❌ | ✅ |
| File layering | ❌ | ✅ |
| Auto-detection | ❌ | ✅ |
| Native performance | ❌ | ✅ (Rust) |
Requirements
- Node.js >= 18.0.0
- Valid age encryption key (set via environment variable or key file)
Building from Source
From the npm/ directory:
cd npm
npm install
npm run buildOr from the project root:
npm run npm:install
npm run npm:buildLicense
MIT - See LICENSE
