npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

env-guardian-cli

v1.0.1

Published

Validate, document, and type-check your environment variables

Readme

env-guardian-cli

npm version

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 generate

Commands

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 schema

env-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.env

Output 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 augmentation

Generated 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 comments

Output:

# 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.env

Schema 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 address
  • uuid - UUID v4 format
  • json - Valid JSON string
  • base64 - Base64 encoded string
  • hex - Hexadecimal string
  • alphanumeric - Letters and numbers only

Number formats:

  • port - Valid port number (1-65535)
  • positive - Positive number
  • integer - 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 vars

Pre-commit Hook

Add to .husky/pre-commit or similar:

#!/bin/sh
npx env-guardian-cli check --quiet || exit 1

Or 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.production

Contributing

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 -- validate

Made with ❤️ for developer experience