defuss-env
v1.0.2
Published
Safe and convenient environment variable handling.
Maintainers
Readme
defuss-env
Secure environment variable loader and parser with TypeScript support
Load and parse .env files with strict validation and security features:
npx defuss-env # parse and print ./.env
npx defuss-env path/to/file # parse and print the given .env fileOr install globally or locally in a project:
npm install defuss-envimport { load, parse, getEnv, setEnv } from "defuss-env";
// Load from file (no injection by default)
const env = load(".env");
console.log(env.DATABASE_URL);
// Load and inject into process.env
load(".env", true /* inject */);
// Load with override of existing values
load(".env", true /* inject */, true /* override */);
// Parse content string directly
const parsed = parse(`
# Database configuration
DB_HOST=localhost
DB_PORT=5432
DATABASE_URL="postgresql://user:pass@localhost:5432/db"
`);
// In-memory environment management
setEnv("API_KEY", "secret-value");
const apiKey = getEnv("API_KEY", "fallback-value");
defuss-envis a secure, TypeScript-first environment variable loader that prioritizes safety and validation. Unlike other .env loaders, it enforces strict size limits, validates variable names, and provides an in-memory store for sensitive values that never touchprocess.env.
It supports standard .env syntax with comments, quoted values, and export statements, while providing protection against oversized files and values that could cause memory issues.
Features
- Security First: Hard caps on file size (256KB) and value length (64KB)
- Strict Validation: POSIX-compliant environment variable names only
- In-Memory Store: Secure storage for sensitive values separate from
process.env - TypeScript Ready: Full TypeScript support with proper type definitions
- Standard Syntax: Supports comments, quotes, escapes, and export statements
- No Process Mutation: Parse without modifying
process.envby default - CLI Tool: Built-in command-line interface for debugging and inspection
- Node.js Only: Server-side safety with explicit browser bundling prevention
Supported .env Syntax
# Comments are supported
export DATABASE_URL="postgresql://localhost:5432/mydb"
# Unquoted values (comments stripped)
API_HOST=api.example.com # production endpoint
# Single-quoted values (literal, no escaping)
SECRET_KEY='raw$tring#with!special@chars'
# Double-quoted values (with escape sequences)
MULTILINE="line1\nline2\ttabbed"
ESCAPED_QUOTES="He said \"Hello World\""
# Values with special characters
URL="https://example.com?param=value#fragment"
# Export prefix is optional
export NODE_ENV=production
DEBUG=trueAPI Reference
parse(content: string): EnvMap
Parse a .env file content string into a key/value map.
const env = parse(`
FOO=bar
QUOTED="value with spaces"
`);
// Returns: { FOO: "bar", QUOTED: "value with spaces" }load(filePath?, inject?, override?): EnvMap
Load and parse a .env file from disk.
filePath(string, default: ".env"): Path to the .env fileinject(boolean, default: false): Whether to inject intoprocess.envoverride(boolean, default: false): Whether to override existing values
// Parse only (safe)
const env = load(".env");
// Parse and inject new variables only
load(".env", true);
// Parse and inject, overriding existing variables
load(".env", true, true);getEnv(name: string, fallback?: string): string | undefined
Retrieve a variable from in-memory store, then process.env, then fallback.
const dbUrl = getEnv("DATABASE_URL", "sqlite://memory");setEnv(name: string, value: string): void
Set a variable in the in-memory store (does not modify process.env).
setEnv("API_TOKEN", "secret-token");
// API_TOKEN is now available via getEnv() but not in process.envisValidEnvKey(name: string): boolean
Check if a variable name follows POSIX conventions.
isValidEnvKey("VALID_NAME"); // true
isValidEnvKey("1INVALID"); // false
isValidEnvKey("also-invalid"); // falseSecurity Features
- File Size Limit: Refuses to read files larger than 256KB
- Value Length Limit: Throws error on values exceeding 64KB
- Name Validation: Only accepts POSIX-compliant variable names (
/^[A-Za-z_][A-Za-z0-9_]*$/) - No Process Mutation: Parse without side effects by default
- In-Memory Secrets: Store sensitive values without exposing them in
process.env - Node.js Only: Explicit server-side usage with browser bundling protection
CLI Tool
The included CLI tool helps debug and inspect .env files:
# Parse and display .env
npx defuss-env
# Parse specific file
npx defuss-env config/production.env
# Example output:
# Read 3 entries from .env:
# DATABASE_URL=postgresql://localhost:5432/mydb
# NODE_ENV=production
# PORT=3000Error Handling
defuss-env provides clear error messages for common issues:
// File too large
load("huge-file.env");
// Error: Refusing to read huge-file.env: size 300000 > 262144 bytes
// Value too long
parse("BIG_VALUE=" + "x".repeat(70000));
// Error: Value for BIG_VALUE exceeds maximum length of 65536 characters
// Invalid variable name
parse("1INVALID=value"); // Silently ignored (follows .env conventions)
// File not found
load("missing.env");
// Error: ENOENT: no such file or directory, open 'missing.env'Why defuss-env?
- Security: Built-in protection against oversized files and values
- Type Safety: Full TypeScript support with proper type definitions
- Separation of Concerns: In-memory store for secrets vs. environment variables
- Standard Compliance: Follows .env conventions while adding safety features
- Zero Dependencies: Lightweight with no external dependencies
- Server-First: Designed for Node.js with explicit browser protection
