⚡ Automatic environment variable parsing with zero configuration and type inference
Following 12-Factor App principles - Store configuration in the environment without schemas, validators, or manual type conversion. Your object structure IS your schema.
- 💡 Why auto-envparse?
- 🎯 Features
- 📦 Installation
- 🚀 Quick Start
- 📖 Type Coercion & Advanced Types
- 📁 .env File Loading
- 🛠️ Custom Validation & Transforms
- 📚 Documentation
- 🎨 TypeScript Support
- 🤝 Contributing
- 📄 License
- 🔗 Links
Most environment variable libraries force you to write schemas and validators before you can parse anything:
// ❌ Other libraries: Define schema + types + validators
const schema = {
host: str({ default: 'localhost' }),
port: num({ default: 5432 }),
ssl: bool({ default: false })
};
const config = cleanEnv(process.env, schema);auto-envparse takes a different approach. If you already have a configuration object with defaults, that's all you need:
// ✅ auto-envparse: Your object IS the schema
import AEP from 'auto-envparse';
const config = {
host: 'localhost',
port: 5432,
ssl: false
};
AEP.parse(config, { prefix: 'DB' }); // Done!The type of each default value tells auto-envparse how to parse it. No schemas. No validators. No manual type conversion. Just works.
import AEP from 'auto-envparse';
class DatabaseConfig {
host = 'localhost';
port = 5432;
ssl = false;
}
// Environment: DB_HOST=example.com, DB_PORT=3306, DB_SSL=true
const config = AEP.parse(DatabaseConfig, { prefix: 'DB' });
// Returns a fully populated DatabaseConfig instancePerfect for existing codebases with class-based configuration.
- ✨ Zero Configuration - Object structure defines the schema
- 🎯 Type Inference - Automatic type detection from default values
- 🔄 Type Coercion - String env vars → correct types (string, number, boolean, array)
- 🐫 Smart Naming - Auto camelCase → SNAKE_CASE conversion
- 🏗️ Nested Objects - Full support with dot-notation (e.g.,
DB_POOL_MIN) - 📋 Nested Arrays - Arrays of objects with dot-notation (e.g.,
SERVERS_0_HOST) - 📁 .env File Loading - Load from .env files with configurable priority
- 🔀 Multi-Source Support - Merge variables from multiple sources (env, .env, .env.local)
- 🔀 Transform Functions - Custom value transformations with external libraries
- 🛠️ Custom Overrides - Add validation or custom parsing when needed
- 📦 Dual Package - ESM and CommonJS support
- 🎨 TypeScript - Full type safety included
- 🪶 Lightweight - Zero dependencies
npm install auto-envparseyarn add auto-envparseimport AEP from 'auto-envparse';
const config = {
apiUrl: 'http://localhost:3000',
timeout: 5000,
debug: false
};
// Environment variables: APP_API_URL, APP_TIMEOUT, APP_DEBUG
AEP.parse(config, { prefix: 'APP' });
console.log(config.timeout); // Automatically converted to numberShorter alias: Import as default for shorter code:
import AEP from 'auto-envparse';
AEP.parse(config, { prefix: 'APP' });Prefix is optional - omit it for global environment variables:
import AEP from 'auto-envparse';
const config = {
host: 'localhost',
port: 3000,
nodeEnv: 'development'
};
// Environment variables: HOST, PORT, NODE_ENV
AEP.parse(config);import AEP from 'auto-envparse';
const config = {
database: {
host: 'localhost',
port: 5432,
pool: {
min: 2,
max: 10
}
}
};
// Environment:
// APP_DATABASE_HOST=prod.com
// APP_DATABASE_PORT=5433
// APP_DATABASE_POOL_MIN=5
// APP_DATABASE_POOL_MAX=20
AEP.parse(config, { prefix: 'APP' });import AEP from 'auto-envparse';
class ServerConfig {
host = '0.0.0.0';
port = 3000;
getUrl(): string {
return `http://${this.host}:${this.port}`;
}
}
// Environment: SERVER_HOST=example.com, SERVER_PORT=8080
const config = AEP.parse(ServerConfig, { prefix: 'SERVER' });
console.log(config.getUrl()); // 'http://example.com:8080'auto-envparse automatically converts environment variables based on your default value types:
| Type | Example | Result |
|---|---|---|
string |
DB_HOST=prod.com |
'prod.com' |
number |
DB_PORT=3306 |
3306 |
boolean |
DB_SSL=true |
true (supports: true/false, 1/0, yes/no, on/off) |
object |
DB_POOL_MIN=5 |
Nested via dot-notation or JSON |
array |
SERVERS_0_HOST=x.com |
Arrays via dot-notation or JSON |
Arrays of Objects:
const config = { servers: [{ host: 'localhost', port: 8080 }] };
// SERVERS_0_HOST=s1.com, SERVERS_0_PORT=8080, SERVERS_1_HOST=s2.com, SERVERS_1_PORT=8081
AEP.parse(config, { prefix: 'APP' });See API.md for complete type coercion details and edge cases.
---------------|---------|--------|------|
| 'localhost' | 'prod.com' | 'prod.com' | string |
| 5432 | '3306' | 3306 | number |
| false | 'true' | true | boolean |
| ['a'] | '["x","y"]' | ['x', 'y'] | array |
Flexible boolean parsing (case-insensitive):
- Truthy:
'true','1','yes','on' - Falsy: Everything else
Arrays of objects support both JSON and dot-notation formats. Dot-notation takes priority:
Dot-Notation Format (Recommended):
const config = {
servers: [{
host: 'localhost',
port: 3000
}]
};
// Environment variables:
// APP_SERVERS_0_HOST=server1.com
// APP_SERVERS_0_PORT=8080
// APP_SERVERS_1_HOST=server2.com
// APP_SERVERS_1_PORT=8081
AEP.parse(config, { prefix: 'APP' });
// Result: servers = [
// { host: 'server1.com', port: 8080 },
// { host: 'server2.com', port: 8081 }
// ]JSON Format (Also supported):
// APP_SERVERS='[{"host":"server1.com","port":8080}]'
AEP.parse(config, { prefix: 'APP' });Features:
- ✅ Multilevel nesting:
APP_SERVICES_0_CONFIG_DATABASE_HOST=db.com - ✅ Sparse arrays: Indices
0, 2, 5→ compact array with 3 elements - ✅ Type coercion: String env vars → proper types in array elements
- ✅ Empty arrays skipped (require template element)
Load from .env files with configurable priority:
import AEP from 'auto-envparse';
const config = { host: 'localhost', port: 3000 };
// Default: loads from ['env', '.env']
AEP.parse(config, { prefix: 'APP' });
// Multi-source with priority (first wins):
AEP.parse(config, {
prefix: 'APP',
sources: ['env', '.env.local', '.env'] // process.env > .env.local > .env
});
// Custom parser (e.g., dotenv):
import { parse } from 'dotenv';
AEP.parse(config, {
prefix: 'APP',
sources: ['.env'],
envFileParser: parse
});The built-in parser supports KEY=value, comments, and quotes. For advanced features (multiline, variable expansion), use dotenv.parse. See API.md for details.
Add custom validation using overrides:
import AEP from 'auto-envparse';
const config = { port: 3000, env: 'dev' as 'dev' | 'staging' | 'prod' };
const overrides = new Map([
// Custom validation
['port', (obj, envVar) => {
const port = parseInt(process.env[envVar] || '');
if (port >= 1 && port <= 65535) obj.port = port;
else throw new Error(`Invalid port: ${port}`);
}],
// Enum validation (built-in helper)
['env', AEP.enumValidator('env', ['dev', 'staging', 'prod'])],
// Transform values (built-in helper)
['timeout', AEP.transform('timeout', (val) => Math.max(parseInt(val), 1000))]
]);
AEP.parse(config, { prefix: 'APP', overrides });Helpers available:
AEP.enumValidator(key, allowedValues)- Validate enum valuesAEP.transform(key, fn)- Transform values with custom logic
See API.md for complete override examples and helper documentation.
- API.md - Complete API reference with all methods and options
- CHANGELOG.md - Version history and migration guides
Full type safety with TypeScript:
import AEP from 'auto-envparse';
interface Config {
host: string;
port: number;
ssl: boolean;
}
const config: Config = {
host: 'localhost',
port: 5432,
ssl: false
};
AEP.parse(config, { prefix: 'DB' });
// All types are preserved and enforced
const host: string = config.host;
const port: number = config.port;
const ssl: boolean = config.ssl;auto-envparse supports both CommonJS and ESM:
// ESM (import) - Default export (recommended)
import AEP from 'auto-envparse';
AEP.parse(config, { prefix: 'DB' });
// ESM (import) - Named export
import { AutoEnvParse } from 'auto-envparse';
AutoEnvParse.parse(config, { prefix: 'DB' });
// CommonJS (require) - Default export
const AEP = require('auto-envparse').default;
AEP.parse(config, { prefix: 'DB' });
// CommonJS (require) - Named export
const { AutoEnvParse } = require('auto-envparse');
AutoEnvParse.parse(config, { prefix: 'DB' });Works seamlessly in both module systems!
Contributions are welcome! Please feel free to submit a Pull Request.
See GitHub Issues for open tasks and discussions.
MIT © Volodymyr Lavrynovych