env-guardian-cli
v1.0.1
Published
Validate, document, and type-check your environment variables
Maintainers
Readme
env-guardian-cli
Validate, document, and type-check your environment variables.
Stop runtime crashes from missing env vars. Stop guessing what variables your app needs. Get TypeScript autocomplete for process.env.
Why env-guardian-cli?
| Problem | Solution |
| --------------------------------------- | --------------------------------- |
| Missing env vars cause runtime crashes | Validates at build/start time |
| No documentation for required variables | Schema file acts as documentation |
| No type safety for process.env | Generates TypeScript types |
| .env.example gets out of sync | Auto-generates from schema |
| Team members have broken environments | CI checks catch issues early |
Quick Start
# Install
npm install env-guardian-cli
# Initialize schema (infers from existing .env)
npx env-guardian-cli init
# Validate your environment
npx env-guardian-cli validate
# Generate TypeScript types
npx env-guardian-cli generateCommands
env-guardian-cli init
Creates a new env.schema.json file. If you have an existing .env, it will infer variable types automatically.
npx env-guardian-cli init # Create env.schema.json
npx env-guardian-cli init --format js # Create env.schema.js instead
npx env-guardian-cli init --no-infer # Don't infer from .env
npx env-guardian-cli init --force # Overwrite existing schemaenv-guardian-cli validate
Validates your .env file against the schema.
npx env-guardian-cli validate # Validate .env
npx env-guardian-cli validate -e .env.local # Validate specific file
npx env-guardian-cli validate --strict # Warn about vars not in schema
npx env-guardian-cli validate --ci # Exit with code 1 on failure
npx env-guardian-cli validate --process-env # Also check process.envOutput example:
✓ DATABASE_URL valid (url)
✓ PORT default (Using default value: 3000)
✗ NODE_ENV missing (Required variable is missing)
✗ API_KEY invalid (Invalid uuid format)
Validation failed: 2 error(s)env-guardian-cli generate
Generates TypeScript type declarations from your schema.
npx env-guardian-cli generate # Output to env.d.ts
npx env-guardian-cli generate -o src/env.d.ts
npx env-guardian-cli generate --no-namespace # Skip ProcessEnv augmentationGenerated output:
// Auto-generated by env-guardian-cli. Do not edit.
declare global {
namespace NodeJS {
interface ProcessEnv {
/** Database connection string */
DATABASE_URL: string;
/** Server port */
PORT?: string;
NODE_ENV: 'development' | 'production' | 'test';
}
}
}
export interface Env {
DATABASE_URL: string;
PORT?: number;
NODE_ENV: 'development' | 'production' | 'test';
}env-guardian-cli sync
Generates .env.example from your schema with comments and default values.
npx env-guardian-cli sync # Output to .env.example
npx env-guardian-cli sync -o .env.template
npx env-guardian-cli sync --no-comments # Skip commentsOutput:
# Database connection string
DATABASE_URL=
# Server port
# Optional
PORT=3000
# Allowed values: development, production, test
NODE_ENV=env-guardian-cli check
Quick validation for CI/pre-commit hooks. Exits with code 0 (valid) or 1 (invalid).
npx env-guardian-cli check # Quick check
npx env-guardian-cli check --quiet # No output
npx env-guardian-cli check --process-env # Check process.envSchema Reference
Create env.schema.json in your project root:
{
"$schema": "https://env-guardian-cli.dev/schema.json",
"variables": {
"DATABASE_URL": {
"type": "string",
"format": "url",
"required": true,
"description": "PostgreSQL connection string"
},
"PORT": {
"type": "number",
"default": 3000,
"required": false,
"description": "Server port"
},
"NODE_ENV": {
"type": "string",
"enum": ["development", "production", "test"],
"required": true
},
"ENABLE_CACHE": {
"type": "boolean",
"default": false
},
"API_KEY": {
"type": "string",
"minLength": 20,
"pattern": "^sk-[a-zA-Z0-9]+$"
}
}
}Variable Options
| Option | Type | Description |
| ------------------------- | ----------------------------------- | -------------------------------------------------- |
| type | "string" \| "number" \| "boolean" | Variable type (required) |
| required | boolean | Whether the variable is required (default: true) |
| default | string \| number \| boolean | Default value if not provided |
| description | string | Human-readable description |
| enum | string[] | Allowed values |
| format | string | Format validation (see below) |
| pattern | string | Custom regex pattern |
| min / max | number | Range for numbers |
| minLength / maxLength | number | Length limits for strings |
Built-in Formats
String formats:
url- Valid URL (http/https)email- Valid email addressuuid- UUID v4 formatjson- Valid JSON stringbase64- Base64 encoded stringhex- Hexadecimal stringalphanumeric- Letters and numbers only
Number formats:
port- Valid port number (1-65535)positive- Positive numberinteger- Integer (no decimals)percentage- Number between 0-100
Programmatic API
Use env-guardian-cli in your code:
import { validateEnv, guardEnv } from 'env-guardian-cli';
// Option 1: Validate and handle errors yourself
const result = validateEnv();
if (!result.valid) {
console.error('Invalid environment:', result.errors);
process.exit(1);
}
console.log(result.parsed.PORT); // typed!
// Option 2: Guard function (throws on invalid)
const env = guardEnv();
// Throws if invalid, returns typed env if valid
console.log(env.DATABASE_URL);Advanced Usage
import { loadSchema, validate, generateTypeScript, loadEnvFile } from 'env-guardian-cli';
// Load schema
const schemaResult = loadSchema('./env.schema.json');
if (!schemaResult.success) {
throw new Error(schemaResult.error);
}
// Load env file
const envResult = loadEnvFile('.env.production');
// Validate
const result = validate(schemaResult.schema!, envResult.env);
// Generate types
const types = generateTypeScript(schemaResult.schema!);CI Integration
GitHub Actions
name: Validate Environment
on: [push, pull_request]
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
- run: npm ci
- run: npx env-guardian-cli check --quiet
env:
NODE_ENV: production
DATABASE_URL: ${{ secrets.DATABASE_URL }}
# ... other env varsPre-commit Hook
Add to .husky/pre-commit or similar:
#!/bin/sh
npx env-guardian-cli check --quiet || exit 1Or use lint-staged:
{
"lint-staged": {
".env*": "env-guardian-cli check --quiet"
}
}Recipes
Validate at App Startup
// src/env.ts
import { guardEnv } from 'env-guardian-cli';
export const env = guardEnv<{
DATABASE_URL: string;
PORT: number;
NODE_ENV: 'development' | 'production' | 'test';
}>();
// src/index.ts
import { env } from './env';
console.log(`Starting on port ${env.PORT}`);Generate Types in Build
{
"scripts": {
"prebuild": "env-guardian-cli generate -o src/env.d.ts",
"build": "tsc"
}
}Different Schemas per Environment
# Development
env-guardian-cli validate -s env.schema.dev.json -e .env.development
# Production
env-guardian-cli validate -s env.schema.prod.json -e .env.productionContributing
Contributions are welcome! Please read our contributing guide first.
# Clone and install
git clone https://github.com/yourusername/env-guardian-cli.git
cd env-guardian-cli
npm install
# Run tests
npm test
# Build
npm run build
# Run CLI locally
npm run local -- validateMade with ❤️ for developer experience
