node-ai-env
v0.1.0
Published
Fast, modern, beautiful environment variable validation library for Node.js and Bun
Maintainers
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.examplefrom your schema - 👀 Watch Mode — Automatically re-validate when
.envchanges - 💡 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-envbun add node-ai-envpnpm add node-ai-envyarn add node-ai-envQuick 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 initAPI
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 validationsgenerateExample(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 doctorPerformance
- 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 appDoes 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.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
MIT © Hansa Dewmina / Dew Coders Team
