How-To Guide

How to Implement CLI Config Precedence

Resolve configuration with an explicit precedence: flag over env over file over default, and show the source so a value is traceable.

On this page

  1. Introduction
  2. Define the precedence once
  3. Resolve every setting through the same rule
  4. Track the source for traceability
  5. Validate the resolved config once
  6. Test the precedence and the source
  7. Common pitfalls
  8. Conclusion

Introduction

A CLI reads configuration from many places: the command-line flags, the environment variables, a config file, and the defaults. Without an explicit order, a setting’s value depends on the code path, and the same command behaves differently in two runs. A defined precedence resolves every setting the same way, so a flag overrides the file, and the behavior is predictable. The common order is flag, then environment, then file, then default.

This tutorial covers defining the precedence, resolving every setting through it, tracking the source, and validating the resolved config. The examples use a resolver, and the design applies to any CLI or service that reads configuration from several sources.

Define the precedence once

Decide the order and write it down: commonly the flag first, because it is the most explicit, then the environment, then the config file, then the default. The order is a single policy, applied to every setting, so there is no per-setting surprise. The most explicit and the most recent intent wins, which is the flag.

The environment over the file because it is easier to set per run and per environment, such as in a container. The file over the default because it is an explicit setting. The default last, so a setting always has a value. Document the order, so a user knows that a flag overrides a file and why their change did not take effect.

# precedence, highest first
1. --port flag
2. PORT environment variable
3. port in the config file
4. the built-in default
# a setting always resolves by this order; the first found wins

Resolve every setting through the same rule

Each setting is resolved by walking the order and taking the first value found, so one function handles them all and the rule is not duplicated. A resolver takes the setting’s sources and returns the value and its source, and the CLI uses it for every setting. This makes the precedence uniform and the code short.

A default for every setting means the resolution always returns a value, so the CLI does not have to handle a missing setting at each use. The resolver, not the call sites, owns the precedence and the default, so a new setting is added by declaring it with its sources and its default. This keeps the precedence in one place and the call sites simple.

function resolve(setting, sources) {
  for (const s of sources) {                 // ordered: flag, env, file, default
    if (s.value !== undefined && s.value !== null) {
      return { value: s.value, source: s.name };
    }
  }
  return { value: setting.default, source: 'default' };
}

const port = resolve({ default: 3000 }, [
  { name: 'flag', value: flags.port },
  { name: 'env', value: process.env.PORT ? Number(process.env.PORT) : undefined },
  { name: 'file', value: config.port },
]);

Track the source for traceability

Record where each value came from, so a surprising value is traceable. A config command, or a verbose flag, prints each setting with its source: port=4000 (from flag), logLevel=debug (from env). This is how a user discovers that their file setting is overridden by an environment variable they forgot, without the CLI’s having to be guessed at by reading the code.

The source is also useful for debugging in production: a verbose startup log prints the resolved config with the sources, so a misconfiguration is visible rather than hidden. A setting that came from the default when the user expected the file is a common confusion, and the source removes it.

mycli --verbose
# config:
#   port=4000      (from flag)
#   logLevel=debug (from env LOG_LEVEL)
#   region=us-east (from file)
#   timeout=30     (from default)

Validate the resolved config once

Validate the final, resolved config, not each source in isolation, so the required keys and the formats are checked after the precedence has picked the values. A setting can be valid in the file and overridden by an invalid flag; the validation must see the flag’s value. Validate once at startup, so a misconfiguration fails fast and loudly.

The validation checks the resolved values: the required keys are present, the values have the right types, and the combinations are allowed. Fail with a message that names the setting and its source, so the user knows which source to correct. The validation at the resolved level is the counterpart of the precedence: the precedence picks, and the validation checks the pick.

const schema = z.object({
  port: z.number().int().min(1).max(65535),
  logLevel: z.enum(['debug', 'info', 'warn', 'error']),
  region: z.string().min(1),
});

const result = schema.safeParse(resolvedConfig);
if (!result.success) {
  for (const issue of result.error.issues) {
    console.error(issue.path.join('.') + ': ' + issue.message + ' (from ' + sources[issue.path[0]] + ')');
  }
  process.exit(2);
}

Test the precedence and the source

Test that a flag overrides the environment and the file, that the environment overrides the file, and that the file overrides the default, by setting all of them and asserting the resolved value. Test that the source is reported correctly for each, so the traceability works. Test that a missing required setting and an invalid value fail with a message naming the setting and the source.

# flag beats env beats file: assert the flag's value wins
mycli --port 4000        # with PORT=3000 and file port=5000 set
# assert the resolved port is 4000 and its source is "flag"

Common pitfalls

No explicit order so the result depends on the code path, a different order per setting, a missing default so a setting can be undefined, no source tracking so a surprising value cannot be traced, and validating each source instead of the resolved config are the recurring mistakes. One documented order, a single resolver, a default for every setting, source tracking, and a resolved-config validation address them.

Conclusion

A CLI resolves configuration with an explicit precedence, so a setting has one rule. Define the order flag over env over file over default, resolve every setting through one resolver, track the source for traceability, and validate the resolved config once. Self-check by setting a flag, an env, and a file value and asserting the flag wins, with the source reported. Then a configuration value is predictable and traceable.

Sources: The Twelve-Factor App: Config, GNU: Command-line options and precedence, Node.js: dotenv and config precedence.

FAQ

Why not merge the sources randomly?
Without an explicit order, the result depends on the code path, and the same setting can come from different sources in different runs. An explicit order makes every setting resolve the same way, so a flag always overrides the file, and the behavior is predictable and documentable.
Where do flags fit?
The command-line flag is the highest precedence, because it is the most explicit and the most recent intent of the person running the command. It overrides the environment and the file, so a one-off override is a flag, and a persistent setting is in the file.

Related Examples