@nodezor/env-guard
v0.0.1
Published
Zero-dependency type-safe startup environment variable validation guard
Maintainers
Readme
@nodezor/env-guard
Fail-fast, type-safe environment variable validation with automatic type inference and readable startup error tables.
The Problem
Applications frequently crash in production or expose security risks due to missing, unvalidated, or type-mismatched environment variables. Standard dotenv loaders load all values as unvalidated strings, causing silent runtime bugs, improper fallbacks, or security flaws when critical keys (like DATABASE_URL or API_PORT) are missing or malformed during deployment.
Features
- 🔒 Auto-Inferred Types: Types TypeScript primitive return objects directly from schema rules.
- ⚡ Zero External Dependencies: Powered entirely by native JS primitives and
process.env. - 🚨 Fail-Fast Startup: Prints clear, formatted
console.tableerror reports listing all failing key/value rules before crashing early. - 🛠️ Rich Rule Primitive Types: Validates
string,number,boolean, andurlformats with custom predicate validator support. - 📦 Dual ESM & CommonJS: Full support for bundlers, Node.js ESM (
.js), and CJS (.cjs).
Installation
# pnpm
pnpm add @nodezor/env-guard
# npm
npm install @nodezor/env-guard
# yarn
yarn add @nodezor/env-guardQuick Start / Usage Example
import { createEnvGuard } from '@nodezor/env-guard';
// Define schema rules
export const env = createEnvGuard({
PORT: { type: 'number', required: true },
HOST: { type: 'string', fallback: 'localhost' },
ENABLE_CACHE: { type: 'boolean', required: true },
DATABASE_URL: { type: 'url', required: true, description: 'PostgreSQL connection URI' },
MAX_CONNECTIONS: {
type: 'number',
fallback: 10,
validator: (val) => val >= 1 || 'MAX_CONNECTIONS must be at least 1',
},
});
// Auto-inferred return type:
// env.PORT -> number
// env.HOST -> string
// env.ENABLE_CACHE -> boolean
// env.DATABASE_URL -> string
// env.MAX_CONNECTIONS -> numberFormatted Startup Failure Report
If environment validation fails, @nodezor/env-guard logs a clear startup diagnostic table before throwing an EnvGuardError:
================================================================
🚨 ENV-GUARD VALIDATION FAILURE
Missing or malformed environment variables detected at startup.
================================================================
┌─────────┬────────────────┬────────────────┬───────────────┬───────────────────────────────────────────┬───────────────────────────┐
│ (index) │ ENV Variable │ Current Value │ Expected Type │ Reason │ Description │
├─────────┼────────────────┼────────────────┼───────────────┼───────────────────────────────────────────┼───────────────────────────┤
│ 0 │ 'PORT' │ '"not-a-num"' │ 'NUMBER' │ 'Expected valid number, received "..."' │ '-' │
│ 1 │ 'DATABASE_URL' │ <MISSING> │ 'URL' │ 'Missing required environment variable.' │ 'PostgreSQL connection' │
└─────────┴────────────────┴────────────────┴───────────────┴───────────────────────────────────────────┴───────────────────────────┘API Reference
createEnvGuard<S extends EnvSchema>(schema: S, options?: EnvGuardOptions): InferEnv<S>
Validates input environment variables against a schema and returns a frozen, typed configuration object.
Schema Rule Definition (EnvRule)
interface BaseRule<T> {
type: 'string' | 'number' | 'boolean' | 'url';
description?: string;
validator?: (value: ParsedType) => boolean | string;
}
interface RequiredRule<T> extends BaseRule<T> {
required: true;
fallback?: ParsedType;
}
interface FallbackRule<T> extends BaseRule<T> {
fallback: ParsedType;
required?: boolean;
}
interface OptionalRule<T> extends BaseRule<T> {
required?: false;
fallback?: undefined;
}Options (EnvGuardOptions)
| Option | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| env | Record<string, string \| undefined> | process.env | Source dictionary of environment variables |
| exitOnFailure | boolean | true (non-test) | Invokes process.exit(1) when validation fails |
| reporter | (errors: ValidationError[]) => void | undefined | Custom callback for handling validation errors |
License
MIT © PRX2112
