Full answer
Real services get settings from several places. A clear order avoids surprises. A common order, from lowest to highest priority:
- Built-in defaults in code (safe values for development).
- A config file (config.json or YAML) for non-secret structured settings.
- Environment variables (deployment settings and secrets).
- Command-line flags (one-off overrides, such as --port 4000).
Implementation points:
- util.parseArgs({ args, options: { port: { type: 'string', short: 'p' }, verbose: { type: 'boolean' } }, strict: true }) returns { values, positionals }. In strict mode, unknown flags throw, which catches typos. It supports short flags, string and boolean types, multiple values and defaults.
- Map each environment variable to a config key in a table (APP_PORT to port). A mapping table is easier to review than scattered process.env reads.
- Convert and validate types after merging, not before.
- Keep the source of every value ('default', 'file', 'env', 'cli'). When a value is wrong, the message says where it came from.
- Deep-freeze the final object so code cannot change it at run time.
- Redact secrets in output: a list of key names (password, token, secret, key) replaced by '[redacted]'. Do it in one function that all logging of config uses.
- Never put secrets in command-line flags: process listings and shell history show them. Prefer environment variables, mounted secret files or a secret manager.
Reload on change is optional and risky. Many services restart on a config change instead, which keeps the state simple.
const { parseArgs } = require('node:util');
const defaults = { port: 3000, logLevel: 'info', dbPassword: undefined };
const fileConfig = { logLevel: 'warn' }; // pretend this came from config.json
const env = { APP_PORT: '8080', APP_DB_PASSWORD: 'p@ssw0rd!' }; // pretend process.env
const argv = ['--log-level', 'debug', '-v', 'extra-file.txt'];
function deepFreeze(object) {
for (const value of Object.values(object)) if (value && typeof value === 'object') deepFreeze(value);
return Object.freeze(object);
}
function buildConfig({ defaults, fileConfig, env, argv }) {
const { values, positionals } = parseArgs({
args: argv,
options: {
port: { type: 'string', short: 'p' },
'log-level': { type: 'string' },
verbose: { type: 'boolean', short: 'v' },
},
allowPositionals: true,
strict: true, // unknown flags throw
});
const value = {};
const source = {};
const apply = (name, v, from) => { if (v !== undefined) { value[name] = v; source[name] = from; } };
for (const [name, v] of Object.entries(defaults)) apply(name, v, 'default');
for (const [name, v] of Object.entries(fileConfig)) apply(name, v, 'file');
apply('port', env.APP_PORT && Number(env.APP_PORT), 'env');
apply('logLevel', env.APP_LOG_LEVEL, 'env');
apply('dbPassword', env.APP_DB_PASSWORD, 'env');
apply('port', values.port && Number(values.port), 'cli');
apply('logLevel', values['log-level'], 'cli');
apply('verbose', values.verbose, 'cli');
value.files = positionals;
return { config: deepFreeze(value), source };
}
const SECRET_KEYS = /password|secret|token|key/i;
const redact = (config) => Object.fromEntries(Object.entries(config).map(([k, v]) => [k, SECRET_KEYS.test(k) ? '[redacted]' : v]));
const { config, source } = buildConfig({ defaults, fileConfig, env, argv });
console.log('final config (secrets hidden):', redact(config));
console.log('where each value came from:', source);
console.log('config is frozen:', Object.isFrozen(config));
try {
buildConfig({ defaults, fileConfig, env, argv: ['--prot', '1'] }); // a typo (error on purpose)
} catch (err) {
console.log('unknown flag rejected:', err.code);
}The sources are simulated with plain objects so the output is the same everywhere. The misspelled flag at the end fails on purpose. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): final config (secrets hidden): { port: 8080, logLevel: 'debug', dbPassword: '[redacted]', verbose: true, files: [ 'extra-file.txt' ] } where each value came from: { port: 'env', logLevel: 'cli', dbPassword: 'env', verbose: 'cli' } config is frozen: true unknown flag rejected: ERR_PARSE_ARGS_UNKNOWN_OPTION
Key points
- Fixed precedence: default, file, environment, command line.
- util.parseArgs handles flags with no dependency.
- Track the source of each value.
- Freeze the config and redact secrets in output.
- Do not pass secrets as command-line arguments.
Common mistakes
- Passing passwords with a command-line flag.
- Applying precedence inconsistently in different parts of the app.
- Printing the config for debugging with secrets inside.
- Allowing unknown flags silently, so typos pass.
Follow-ups
- How would you hot-reload config safely?
- How do you manage secrets in Kubernetes?
- How do CLI libraries like commander compare to parseArgs?
Tips
- State the precedence order first.
- Mention provenance (source tracking) as a debugging aid.
- Say why secrets do not belong in argv.