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

node-ai-env

v0.1.0

Published

Fast, modern, beautiful environment variable validation library for Node.js and Bun

Readme


Features

  • ✨ Type Validation — Validate env vars against 14+ types (string, number, boolean, url, email, port, uuid, and more)
  • 🎨 Beautiful CLI — Colorful output with icons and clear error messages
  • 🔍 Doctor Analysis — Detect missing, unused, duplicate, and invalid variables
  • 📝 Auto-generate — Create .env.example from your schema
  • 👀 Watch Mode — Automatically re-validate when .env changes
  • 💡 Smart Suggestions — "Did you mean?" when variable names are wrong
  • 🚀 Zero Config — Works out of the box with no configuration
  • ⚡ Fast & Lightweight — Minimal dependencies, tree-shakeable ESM
  • 📦 TypeScript — 100% TypeScript with strict types and JSDoc everywhere

Installation

npm install node-ai-env
bun add node-ai-env
pnpm add node-ai-env
yarn add node-ai-env

Quick Start

1. Define a schema

import { validateEnv } from "node-ai-env";

const schema = {
  PORT: "port",
  HOST: "string",
  DATABASE_URL: "url",
  DEBUG: "boolean",
  NODE_ENV: {
    type: "enum",
    values: ["development", "production", "test"],
  },
};

2. Validate your environment

const report = validateEnv(schema);

if (report.failed > 0) {
  console.error("Environment validation failed!");
  for (const result of report.results) {
    if (!result.valid) {
      console.error(`✖ ${result.key}: ${result.error}`);
    }
  }
} else {
  console.log(`✓ All ${report.passed} variables valid`);
}

3. Or use the CLI

# Validate .env file
node-ai-env validate '{ "PORT": "number", "HOST": "string" }'

# Generate .env.example
node-ai-env generate '{ "PORT": { "type": "port", "description": "Server port" } }'

# Run doctor analysis
node-ai-env doctor

# Watch for changes
node-ai-env watch '{ "PORT": "number" }'

CLI

Commands

| Command | Description | |---------|-------------| | validate | Validate .env file against a schema | | generate | Generate .env.example from a schema | | doctor | Analyze .env file for issues | | check | Strict validation (alias for validate --strict) | | init | Initialize node-ai-env in your project | | watch | Watch .env for changes and re-validate | | help | Display help information |

Usage

node-ai-env validate [schema] [options]
node-ai-env generate [schema] [options]
node-ai-env doctor [schema] [options]
node-ai-env check [schema] [options]
node-ai-env init [options]
node-ai-env watch [schema] [options]

Options

| Option | Description | |--------|-------------| | -f, --file <path> | Path to .env file (default: .env) | | -o, --output <path> | Output file path (default: .env.example) | | --strict | Exit on first validation error | | --no-examples | Don't include example values in generated file | | --verbose | Enable verbose output |

Examples

# Validate with inline JSON schema
node-ai-env validate '{ "PORT": "number", "HOST": "string" }'

# Validate with schema file
node-ai-env validate ./schema.json

# Validate with config file (node-ai-env.config.ts)
node-ai-env validate

# Generate .env.example
node-ai-env generate '{ "PORT": { "type": "port", "description": "Server port" } }'

# Run doctor analysis
node-ai-env doctor

# Strict check (exit code 1 on failure)
node-ai-env check '{ "PORT": "number" }'

# Watch mode
node-ai-env watch '{ "PORT": "number" }'

# Initialize project
node-ai-env init

API

validateEnv(schema, envVars?)

Validate environment variables against a schema.

import { validateEnv } from "node-ai-env";

const report = validateEnv({
  PORT: "number",
  HOST: "string",
  DATABASE_URL: "url",
});

console.log(report.passed);  // number of passed validations
console.log(report.failed);  // number of failed validations

generateExample(schema, options?)

Generate the content of a .env.example file.

import { generateExample } from "node-ai-env";

const content = generateExample({
  PORT: { type: "port", description: "Server port" },
  HOST: { type: "string", default: "localhost" },
});

console.log(content);

doctor(envFilePath?, schema?)

Analyze a .env file for issues.

import { doctor } from "node-ai-env";

const report = doctor(".env", {
  PORT: "number",
  HOST: "string",
});

console.log(report.diagnostics);
// [
//   { level: "error", key: "PORT", message: "Missing required variable" },
//   { level: "warning", key: "API_KEY", message: "Not defined in schema" },
// ]

writeExampleFile(schema, options?)

Write a .env.example file to disk.

import { writeExampleFile } from "node-ai-env";

const path = writeExampleFile({
  PORT: "number",
  HOST: "string",
}, { output: ".env.example" });

console.log(`Generated ${path}`);

parseEnvFile(filePath?)

Parse a .env file into structured entries.

import { parseEnvFile } from "node-ai-env";

const parsed = parseEnvFile(".env");
for (const entry of parsed.entries) {
  console.log(`${entry.key}=${entry.value} (line ${entry.line})`);
}

Supported Types

| Type | Description | Example | |------|-------------|---------| | string | Any string value | hello | | number | Numeric value | 3000 | | boolean | true/false, 1/0, yes/no | true | | url | Valid URL | https://example.com | | email | Valid email address | [email protected] | | json | Valid JSON string | {"key":"value"} | | array | Comma-separated list | a,b,c | | enum | One of allowed values | development | | port | Port number 1-65535 | 3000 | | uuid | UUID v4 | 550e8400-... | | date | Valid date string | 2024-01-15 | | regex | Regular expression | ^[a-z]+$ | | filepath | File path | /path/to/file | | directory | Directory path | /path/to/dir |

Schema

Shorthand syntax

const schema = {
  PORT: "number",
  HOST: "string",
  DEBUG: "boolean",
};

Full syntax

const schema = {
  PORT: {
    type: "port",
    required: true,
    description: "The port the server runs on",
  },
  HOST: {
    type: "string",
    default: "localhost",
    description: "The hostname to bind to",
  },
  NODE_ENV: {
    type: "enum",
    values: ["development", "production", "test"],
    description: "The Node.js environment",
  },
  API_KEY: {
    type: "string",
    required: true,
    description: "The API key for external service",
    validate: (value: string) =>
      value.startsWith("sk-") || "Must start with 'sk-'",
  },
};

Schema options

| Option | Type | Default | Description | |--------|------|---------|-------------| | type | EnvType | (required) | The expected type | | required | boolean | true | Whether the variable is required | | default | string | — | Default value if not set | | description | string | — | Human-readable description | | values | string[] | — | Allowed values (for enum type) | | pattern | RegExp | — | Regex pattern (for regex type) | | validate | function | — | Custom validation function |

Configuration

Config file

Create node-ai-env.config.ts in your project root:

import type { AiEnvConfig } from "node-ai-env";

const config: AiEnvConfig = {
  schema: {
    PORT: {
      type: "port",
      description: "The port the server runs on",
    },
    NODE_ENV: {
      type: "enum",
      values: ["development", "production", "test"],
      description: "The Node.js environment",
    },
    DATABASE_URL: {
      type: "url",
      description: "The database connection string",
    },
  },
};

export default config;

Then run commands without arguments:

node-ai-env validate
node-ai-env doctor

Performance

  • Zero runtime dependencies for core functionality
  • Fast startup — Minimal module loading
  • Tree-shakeable — Import only what you need
  • Efficient parsing — Single-pass .env parser
  • Small bundle — Optimized for size

FAQ

Why node-ai-env?

Most env validation libraries are either too heavy, poorly maintained, or have a poor developer experience. node-ai-env is designed to be fast, beautiful, and beginner-friendly while still being powerful enough for production use.

Can I use it without TypeScript?

Yes! node-ai-env works great with plain JavaScript. The schema can be a plain object, and all API functions work without type annotations.

Does it work with Bun?

Yes! node-ai-env is fully compatible with Bun. The CLI and API work identically to Node.js.

How do I use it with frameworks?

You can use node-ai-env at your application entry point to validate environment variables before your framework boots:

import { validateEnv } from "node-ai-env";
import { schema } from "./env-schema";

const report = validateEnv(schema);
if (report.failed > 0) {
  console.error("Invalid environment variables!");
  process.exit(1);
}

// Start your app

Does it support .env.local, .env.production, etc.?

Yes! You can specify any .env file path:

validateEnv(schema, loadEnvVars(".env.production"));

Contributing

Contributions are welcome! Please read our contributing guidelines first.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

MIT © Hansa Dewmina / Dew Coders Team