env-inspector
v1.0.0
Published
Type-safe .env validation for Node.js applications with development-time warnings
Maintainers
Readme
env-inspector
Type-safe environment variable validation for Node.js applications with development-time warnings.
Features
- 🔍 Type-safe validation - Validate and transform environment variables with TypeScript support
- 🛡️ Required/Optional flags - Mark variables as required or provide defaults
- ⚠️ Development warnings - Get helpful warnings during development
- 🎯 Custom validators - Add custom validation logic
- 📝 Auto-documentation - Generate documentation for your environment schema
- 🔧 Flexible configuration - Customize behavior with various options
- 📁 Clean Architecture - Well-organized, maintainable codebase
Installation
npm install env-inspectorQuick Start
import { env } from 'env-inspector';
// Define your environment schema
const config = env()
.define({
PORT: {
type: 'number',
required: true,
default: 3000,
description: 'Server port number'
},
NODE_ENV: {
required: true,
validator: (value) => ['development', 'production', 'test'].includes(value)
},
DATABASE_URL: {
required: true,
description: 'PostgreSQL connection string'
},
DEBUG: {
type: 'boolean',
default: false
},
ALLOWED_ORIGINS: {
type: 'array',
default: ['http://localhost:3000']
}
})
.validate();
// Use your validated config
console.log(`Server starting on port ${config.PORT}`);
console.log(`Environment: ${config.NODE_ENV}`);
console.log(`Debug mode: ${config.DEBUG}`);Architecture
The package is organized with clean separation of concerns:
src/
├── core/
│ └── env-inspector.ts # Main EnvInspector class
├── types/
│ └── index.ts # TypeScript interfaces and types
├── utils/
│ ├── env-loader.ts # Environment file loading
│ ├── type-transformer.ts # Type transformation utilities
│ ├── validator.ts # Validation logic
│ └── doc-generator.ts # Documentation generation
├── factories/
│ └── index.ts # Convenience factory functions
└── index.ts # Main entry pointAPI Reference
EnvInspector
Constructor Options
interface EnvInspectorOptions {
envPath?: string; // Path to .env file (default: '.env')
silent?: boolean; // Suppress warnings (default: false)
throwOnMissing?: boolean; // Throw on missing required vars (default: false)
prefix?: string; // Prefix for environment variables
}Variable Configuration
interface EnvVarConfig {
required?: boolean; // Is this variable required?
default?: any; // Default value if missing
type?: 'string' | 'number' | 'boolean' | 'array'; // Type transformation
validator?: (value: string) => boolean; // Custom validation function
description?: string; // Documentation description
transform?: (value: string) => any; // Custom transformation function
}Methods
define(schema: EnvSchema): EnvInspector
Define the environment variable schema.
validate(): Record<string, any>
Validate all defined environment variables and return the validated config.
get<T>(key: string): T | undefined
Get a specific validated environment variable.
getAll(): Record<string, any>
Get all validated environment variables.
generateDocs(): string
Generate markdown documentation for the environment schema.
Examples
Basic Usage
import { EnvInspector } from 'env-inspector';
const inspector = new EnvInspector();
const config = inspector
.define({
API_KEY: { required: true },
PORT: { type: 'number', default: 3000 }
})
.validate();With Custom Validation
const config = env()
.define({
EMAIL: {
required: true,
validator: (value) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value),
description: 'Valid email address'
},
URL: {
required: true,
validator: (value) => {
try {
new URL(value);
return true;
} catch {
return false;
}
}
}
})
.validate();Generate Documentation
const inspector = env()
.define({
DATABASE_URL: {
required: true,
description: 'PostgreSQL connection string'
},
REDIS_URL: {
required: false,
default: 'redis://localhost:6379',
description: 'Redis connection string for caching'
}
});
// Generate markdown documentation
console.log(inspector.generateDocs());Error Handling
// Throw on missing required variables
const config = env({ throwOnMissing: true })
.define({
SECRET_KEY: { required: true }
})
.validate(); // Will throw if SECRET_KEY is missing
// Or handle errors gracefully
const config = env({ silent: true })
.define({
SECRET_KEY: { required: true }
})
.validate(); // Will log errors but not throwDevelopment
# Install dependencies
npm install
# Build the project
npm run build
# Run tests
npm test
License
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
