env-validator-guard
v2.0.0
Published
Validate environment variables at app startup
Downloads
238
Maintainers
Readme
env-validator-guard
Validate environment variables at app startup so your app doesn't crash later.
Installation
npm install env-validator-guardQuick Start
v1 API (simple)
import { validateEnv } from "env-validator-guard";
const env = validateEnv({
PORT: { type: "number", required: true },
API_KEY: { type: "string", required: true },
DEBUG: { type: "boolean", default: false }
});v2 Builder API (Zod-like)
import { EnvGuard } from "env-validator-guard";
const env = new EnvGuard()
.dotenv() // auto-load .env
.var("PORT", { type: "number", required: true })
.var("API_KEY", { type: "string", required: true })
.var("DEBUG", { type: "boolean", default: false })
.var("NODE_ENV", {
type: "enum",
values: ["development", "production", "test"],
message: { type: "NODE_ENV must be dev, prod, or test" }
})
.var("EMAIL", {
type: "string",
required: true,
validate: (v) => v.includes("@") ? undefined : "Invalid email format",
message: { validate: "EMAIL must contain @" }
})
.parse();CLI Usage
Create env-guard.json in your project root:
{
"PORT": { "type": "number", "required": true },
"API_KEY": { "type": "string", "required": true }
}Then run:
npx env-validator-guard check
npx env-validator-guard check -f=.env.production
npx env-validator-guard check -s='{"PORT":{"type":"number","required":true}}'API
EnvGuard (Builder)
| Method | Description |
|--------|-------------|
| .dotenv(path?) | Auto-load .env file |
| .var(key, rules) | Define a variable schema |
| .parse() | Validate and return env object |
Rules
| Option | Type | Description |
|--------|------|-------------|
| type | "string" | "number" | "boolean" | "enum" | Expected type |
| required | boolean | Throws if missing |
| default | any | Fallback if not set |
| values | string[] | Allowed values (for enum type) |
| validate | (value) => string \| undefined | Custom validation function |
| message | { required?, type?, validate? } | Custom error messages |
validateEnv(schema, options?) (Legacy)
Same as v1, with optional { dotenv: true } to auto-load .env.
TypeScript
Full type support included:
import { EnvGuard, EnvRule } from "env-validator-guard";License
ISC
