@simpleworkjs/conf
v1.2.0
Published
Lightweight, flexible configuration management for Node.js applications with multi-environment support
Maintainers
Readme
@simpleworkjs/conf
Configuration management for the SimpleWorkJS framework.
Table of Contents
- Installation
- Quick Start
- Configuration Structure
- How It Works
- API Reference
- Examples
- Best Practices
- Development
Installation
npm install --save @simpleworkjs/confQuick Start
Create a conf directory in your project root (at the same level as node_modules):
your-project/
├── node_modules/
├── conf/
│ ├── base.js # Required - base configuration
│ ├── development.js # Optional - development environment config
│ ├── production.js # Optional - production environment config
│ └── secrets.js # Optional - sensitive data (add to .gitignore!)
└── package.jsonConfiguration files can be either JSON or JavaScript files exporting an object.
Example conf/base.js:
module.exports = {
app: {
name: 'My Application',
port: 3000
},
database: {
host: 'localhost',
name: 'myapp'
}
};Example conf/production.js:
module.exports = {
app: {
port: 8080
},
database: {
host: 'prod-db.example.com'
}
};Example conf/secrets.js:
module.exports = {
database: {
password: 'super-secret-password',
username: 'dbuser'
},
apiKeys: {
stripe: 'sk_live_...'
}
};Usage in your application:
const conf = require('@simpleworkjs/conf');
console.log(conf.app.name); // 'My Application'
console.log(conf.database.host); // 'localhost' in development, 'prod-db.example.com' in production
console.log(conf.database.password); // 'super-secret-password' (from secrets.js)
console.log(conf.environment); // 'development' or 'production'Important: Add secrets.js to your .gitignore file to prevent committing sensitive data.
Configuration Structure
Directory Layout
The conf directory should be at the root of your project:
base.js- Required - Contains shared configuration used across all environments<environment>.js- Optional - Environment-specific overrides (e.g.,development.js,production.js,staging.js)secrets.js- Optional - Sensitive data that should not be committed to version control. Use theCONF_SECRETSenvironment variable to point to a secrets file outside theconfdirectory (for example,/etc/appName.js).
Load Order
Configuration files are loaded and merged in the following order:
- base.js - Loaded first (required)
- .js - Loaded second, overrides base settings
- secrets.js (or the file pointed to by
CONF_SECRETS) - Loaded third, overrides all previous settings app_*env vars - Applied last, overrides everything (highest precedence)
Each subsequent layer deeply merges with the previous configuration, allowing you to override specific values while keeping others intact. Environment variables win over all files. This matches the twelve-factor convention that env vars are the highest-precedence config layer.
Environment Variable Overrides (app_*)
Any environment variable whose name starts with app_ is applied as a config
override with the highest precedence. The remainder of the name is split on
double-underscore (__) into a nested path into the config object:
| Env var | Sets | Type |
|---------|------|------|
| app_database__host=env-db | conf.database.host | string |
| app_app__port=9090 | conf.app.port | number (JSON.parse) |
| app_features__enableCache=false | conf.features.enableCache | boolean (JSON.parse) |
| app_oauth__jwtSecret=secret | conf.oauth.jwtSecret | string |
| app_oauth__token_lifetime__access_token=3600 | conf.oauth.token_lifetime.access_token | number |
Values are coerced via JSON.parse when the value is valid JSON (so numbers,
booleans, null, and JSON objects/arrays become real types), and kept as the
raw string otherwise (URLs, passwords, free-form text). Use double-underscore
__ instead of single _ so that keys containing underscores (like
token_lifetime) are kept intact rather than split further.
# Override a few values without touching any config file
app_database__host=prod-db.example.com \
app_database__password=super-secret \
app_app__port=8080 \
node app.jsEnv vars with empty path segments (leading/trailing/repeated __, or just
app_) are ignored.
How It Works
The package uses a multi-tiered configuration strategy inspired by Django's settings system:
- Shared Configuration - Common settings go in
base.js - Environment-Specific - Environment overrides go in
development.js,production.js, etc. - Secrets - Sensitive data goes in
secrets.js(add to.gitignore) - Environment Variables - Any
app_*env var overrides everything above (highest precedence)
The environment is determined by the NODE_ENV environment variable (defaults to development).
Note on failures: This library treats a broken or missing required configuration as a fatal startup error. If
base.jscannot be loaded (missing file, syntax error, or runtime error), or if an unrecoverable error occurs while resolving or loading it, the library will callprocess.exit(1). Optional files (<environment>.jsandsecrets.js) only log a warning and continue with an empty object when they are missing.
Example Scenario
Consider this configuration:
base.js:
{
app: { name: 'MyApp', port: 3000 },
api: { url: 'https://api.example.com', timeout: 5000 }
}production.js:
{
app: { port: 8080 },
api: { timeout: 10000 }
}secrets.js:
{
api: { token: 'secret-api-key' }
}Result in production:
{
app: { name: 'MyApp', port: 8080 }, // port from production.js
api: {
url: 'https://api.example.com', // from base.js
timeout: 10000, // from production.js
token: 'secret-api-key' // from secrets.js
},
environment: 'production' // auto-added
}API Reference
Environment Variables
NODE_ENV- Sets the environment (default:development)CONF_DIR- Override the configuration directory path (default:./conf)CONF_SECRETS- Override the path to the secrets file (default:<CONF_DIR>/secrets.js). Relative paths are resolved fromprocess.cwd().app_*- Any env var prefixed withapp_overrides the merged config at the highest precedence. The rest of the name is split on__into a nested path, and the value isJSON.parse-coerced when possible (see Environment Variable Overrides).
Configuration Object
The exported configuration object includes all merged settings plus:
environment- The current environment name (fromNODE_ENV)
Examples
Using with Express
const conf = require('@simpleworkjs/conf');
const express = require('express');
const app = express();
app.listen(conf.app.port, () => {
console.log(`Server running on port ${conf.app.port}`);
});Different Environments
# Development (default)
npm start
# Production
NODE_ENV=production npm start
# Custom environment
NODE_ENV=staging npm start # Loads conf/staging.jsCustom Config Directory
CONF_DIR=/path/to/config node app.jsCustom Secrets File
Point to a secrets file outside the default conf/ directory, for example when secrets are stored in /etc/:
CONF_SECRETS=/etc/appName.js node app.jsRelative paths are resolved from process.cwd().
Best Practices
- Always commit
base.jsand environment-specific files to version control - Never commit
secrets.js- add it to.gitignore - Never commit
CONF_SECRETSfiles that contain real values - Use environment files for environment-specific URLs, ports, and settings
- Use secrets.js or CONF_SECRETS for API keys, passwords, tokens, and other sensitive data
- Keep base.js minimal - only include truly shared configuration
- Document your config - add comments explaining what each setting does
Development
Running Tests
# Install dependencies
npm install
# Run tests
npm test
# Run tests in watch mode
npm run test:watch
# Run tests with coverage
npm run test:coverageContributing
- Fork the repository
- Create a feature branch:
git checkout -b feature/my-feature - Make your changes and add tests
- Run tests to ensure they pass:
npm test - Commit your changes:
git commit -m 'Add my feature' - Push to the branch:
git push origin feature/my-feature - Submit a pull request
Testing
The test suite uses Mocha and Chai and includes:
- Basic configuration loading
- Environment-based configuration
- Secrets file handling
- Deep merge behavior
- Error handling
- Environment variable support
Tests run on multiple Node.js versions (16, 18, 20, 22) and operating systems (Ubuntu, Windows, macOS) via GitHub Actions.
License
MIT © simpleworkjs
