good-env


🚨 v7 requires Node version 18.20.4 or higher! 🚨
good-env
A more intuitive way to work with environment variables in Node.js applications.

Why good-env?
When building non-trivial applications, working with environment variables as raw strings can be limiting. good-env provides:
- Type conversion (strings to numbers, booleans, lists, etc.)
- Default values
- Existence checking
- Validation
- No production dependencies
Installation
npm install good-env --save
Usage
Basic Usage
Import the package:
const env = require('good-env');
Getting Values
Simple Values
env.get('HOST');
env.get('NOT_SET', 'default');
Type Conversion
env.getNumber('PORT');
env.num('PORT');
env.getBool('DEBUG');
env.bool('DEBUG');
env.getList('ALLOWED_ORIGINS');
env.list('ALLOWED_ORIGINS');
env.list('VALUES', { cast: 'number' });
URLs and IPs
env.getUrl('API_ENDPOINT');
env.url('API_ENDPOINT');
env.getIp('SERVER_IP', '127.0.0.1');
Multiple Variables
First Available Value
env.get(['PRIMARY_HOST', 'BACKUP_HOST', 'DEFAULT_HOST']);
env.get(['PRIMARY_HOST', 'BACKUP_HOST'], 'localhost');
Batch Operations
env.getAll(['SECRET', 'HOST', 'PORT']);
env.getAll({
API_KEY: null,
PORT: 3000,
DEBUG: false
});
Validation
Existence Checking
env.ok('HOST');
env.ok('HOST', 'PORT', 'API_KEY');
Assertions
env.assert(
'HOST',
{ PORT: { type: 'number' }},
{ REFRESH_INTERVAL: {
type: 'number',
ok: val => val >= 1000
}
}
);
AWS Credentials
const {
awsKeyId,
awsSecretAccessKey,
awsSessionToken,
awsRegion
} = env.getAWS();
const credentials = env.getAWS({ region: 'us-west-2' });
Important Behavior Notes
Boolean Existence vs Value
When checking for the existence of a boolean environment variable:
env.ok('A_BOOL_VAL');
env.getBool('A_BOOL_VAL');
URL Validation
getUrl() only supports 'http', 'https', 'redis', and 'postgresql' protocols
- Invalid URLs return
null instead of throwing errors
- Using
getUrl() ensures proper URL format
Examples
Complete Configuration Setup
const env = require('good-env');
env.assert(
'DATABASE_URL',
{ PORT: { type: 'number' }}
);
module.exports = {
port: env.num('PORT', 3000),
database: env.url('DATABASE_URL'),
debug: env.bool('DEBUG', false),
allowedOrigins: env.list('ALLOWED_ORIGINS', 'localhost'),
cache: {
enabled: env.bool('CACHE_ENABLED', true),
ttl: env.num('CACHE_TTL', 3600)
}
};
License
MIT