The config loader lets you specify environment values using JSON/YAML or JS/TS config files, then overlay them deterministically with privacy and source precedence.
Behavior: In the shipped CLI (plugin-first host) and the generator path, the loader/overlay pipeline is always active and is a no-op when no config files are present.
When enabled, the loader discovers up to three configs in the following order:
package.json above the importMetaUrl the host passes to createCli (for the shipped getdotenv CLI, get-dotenv's own package). Skipped when it is the project root.
Notes:
JSON/YAML (data only, always-on; no-op when no files are present):
env, defaultEnv, defaultEnvKey, paths, pathsDelimiter, pathsDelimiterPattern, dotenvToken, privateToken.vars, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, outputPath. A vars string is split into pairs at the delimiter and each pair at its first assignor, so A=1 B=x=y sets B to x=y.loadProcess, dynamicPath.excludeAll, excludeDynamic, excludeEnv, excludeGlobal, excludePrivate, excludePublic.shell, capture.log, debug, trace, strict.redact, redactPatterns.warnEntropy, entropyThreshold, entropyMinLength, entropyWhitelist.dynamic (use the top-level dynamic of a JS/TS config) and logger.JS/TS (data + dynamic):
(vars: Record<string, string | undefined>, env?: string) => string | undefined.TS support:
import of a package name that resolves to an ES module of that package (linked and workspace packages included) stays an import, resolved from the config file's directory, so a config shares the package instances the rest of the project uses. exports and main resolve as Node resolves them. Everything else is bundled as before: relative imports (also in a config shipped inside node_modules), tsconfig path aliases, TypeScript and JSON files, CommonJS packages (which may require() Node built-ins) and require() calls. A require() that can only be resolved at run time (a computed name, an optional dependency) resolves from the config file's directory. A package installed under an npm alias ("zod3": "npm:zod@^3") is bundled too, so the config gets its own copy of it.--debug (or set GETDOTENV_DEBUG=1) for the full stack traces.defineGetDotenvConfig() type has exactly the loader's keys, so a top-level root option is a type error.Root options resolve from one stack, higher wins: CLI flags, then the parent options bag (process.env.getDotenvCliOptions, in a nested run), then config rootOptionDefaults (project local, project public, packaged), then createCli({ rootOptionDefaults }), then the built-in defaults. createCli defaults are not Commander option defaults, so config and the parent bag override them.
Each ON/OFF family (-p/-P loadProcess, -l/-L log, --debug/--debug-off, --redact/--redact-off, --entropy-warn/--entropy-warn-off warnEntropy, and the five exclusions -z/-Z, -n/-N, -g/-G, -r/-R, -u/-U) resolves the same way:
rootOptionDefaults (or a built-in default, such as loadProcess: true and warnEntropy: true) turns it on;For the exclusions, an individual flag (-r, -R, …) beats -a/--exclude-all and -A/--exclude-all-off, which beat the defaults. In the defaults, rootOptionDefaults.excludeAll: true (in config or createCli) turns on all five exclusions, and an individual default such as excludePrivate: false beats it.
Config privacy derives from the filename suffix:
The loader overlays config-provided values onto the “base” file-derived dotenv values using these axes (higher wins):
The overlay flow:
null, deletes it).When no explicit -e flag is provided, get-dotenv resolves the target environment in three tiers:
-e flag — highest priority, used as-is.defaultEnvKey lookup — a global-only pre-pass loads dotenv files (excluding env-scoped files) and looks up the variable named by defaultEnvKey (default: DEFAULT_ENV). If found, its value becomes the resolved environment.defaultEnv — the fallback from config if neither of the above produces a value.Example: if .env.local contains DEFAULT_ENV=bali and your config sets defaultEnv: 'dev', the resolved environment is bali (tier 2 wins over tier 3).
By the time plugins run, bag.env is always the fully resolved environment — plugins never need to handle defaulting themselves.
There are three distinct expansion stages:
--env, --output-path, --dotenv-token, --private-token, --dynamic-path, --paths) are dotenv-expanded once against process.env via an option parser; they do not see { ...ctx.dotenv }. --vars is not one of them: its values are expanded once, in the vars layer, so -v 'P=\$5' sets P to $5.vars/envVars and explicit vars (--vars, programmatic vars) are expanded progressively during composition, each against process.env overlaid with the values composed so far (composed values win); later keys can reference earlier ones. A referenced value is substituted verbatim, as composed, and never expanded again: with .env P=\$5, config vars: { Q: '$P' } gives Q=$5. While a key is being expanded, a reference to it sees the value composed before it, else counts as unset.afterResolve, the host deep-interpolates each plugin’s config slice (string leaves only) once against { ...ctx.dotenv, ...process.env } (process.env wins).Notes:
getDotenv() (programmatic API) expands outputPath against the composed variables (it can reference other dotenv keys). In the CLI, argv-provided values (like --output-path) are expanded against process.env at parse time, but values coming from rootOptionDefaults are not automatically expanded.You can validate the final composed environment via config:
Behavior:
Examples:
# getdotenv.config.yaml
requiredKeys:
- APP_SETTING
- ENV_SETTING
// getdotenv.config.ts
import { z } from 'zod';
export default {
schema: z.object({
APP_SETTING: z.string().min(1),
ENV_SETTING: z.string().optional(),
}),
};
Vars and extendGetDotenvConfigdefineGetDotenvConfig has two overloads:
cfg.schema is a Zod object schema, the
Vars bag seen by dynamic functions is inferred from the schema's
input type (z.input<typeof schema>) — no Vars type parameter needed.
The schema's input must be string-valued (ProcessEnv-compatible: every
property string | undefined); a schema that coerces from a non-string
input (for example, a bare z.coerce.number() leaf, whose input is
unknown) is a type error. Use z.coerce.number<string>() to
validate a numeric value with string input.defineGetDotenvConfig<Vars, Env>(), an explicit Vars type
parameter (with or without a schema, including a non-Zod validator that
merely exposes safeParse), keeps compiling unchanged.// getdotenv.config.ts
import { z } from 'zod';
import { defineGetDotenvConfig } from '@karmaniverous/get-dotenv';
export default defineGetDotenvConfig({
schema: z.object({
APP_SETTING: z.string(),
ENV_SETTING: z.string().optional(),
}),
dynamic: {
// `vars` is typed from `schema` above: { APP_SETTING: string; ENV_SETTING?: string }
GREETING: (vars) => `Hello ${vars.APP_SETTING}`,
},
});
extendGetDotenvConfig(base, overrides?)Exported from the package root. Composes a new typed config from a base
and an optional overrides slice; neither argument is mutated. Useful
for a shared base config (for example, exported by an internal package for
every service in an org) extended per-project.
// shared-base/getdotenv.config.ts
import { z } from 'zod';
import { defineGetDotenvConfig } from '@karmaniverous/get-dotenv';
export const baseConfig = defineGetDotenvConfig({
schema: z.object({ SERVICE_NAME: z.string() }),
vars: { SERVICE_NAME: 'unnamed' },
dynamic: {
GREETING: (vars) => `Hello from ${vars.SERVICE_NAME}`,
},
});
// getdotenv.config.ts
import { z } from 'zod';
import { extendGetDotenvConfig } from '@karmaniverous/get-dotenv';
import { baseConfig } from 'shared-base/getdotenv.config';
export default extendGetDotenvConfig(baseConfig, {
schema: z.object({ REGION: z.string() }),
requiredKeys: ['REGION'],
dynamic: {
// Sees both SERVICE_NAME (base) and REGION (this override), with no
// `Vars` annotation: `Vars` is the merged schema's input.
TAG: (vars) => `${vars.SERVICE_NAME}-${vars.REGION}`,
},
});
Merge semantics, by key:
| Key | Merge |
|---|---|
schema |
The base Zod object schema extended with the override's fields; the override wins on a clashing key (z.input<Merged> has the override's type for that field). Requires Zod object schemas (z.object(...)) when both sides declare a schema — the call throws at runtime otherwise. Either side alone (or neither) passes through unchanged. |
dynamic |
Object spread: an overridden key keeps the base key's position, so values that depend on it are still computed after it (dynamic evaluation runs in key-insertion order); new keys come after all base keys. |
requiredKeys |
Union, base order first, de-duplicated. |
plugins, rootOptionDefaults, rootOptionVisibility, scripts, vars, envVars (plain objects) |
Deep merge, override wins (the same semantics as the library's internal defaultsDeep). |
| Other arrays and scalars | Override replaces (for example, rootOptionDefaults.redactPatterns is replaced wholesale, not concatenated). |
extendGetDotenvConfig(base) with no overrides returns a new, structurally
equivalent config.
validateEnvAgainstSources now validates the final composed env against the
schema of every config layer that has one (packaged, project public,
project local) instead of stopping at the first one found, and requiredKeys
are unioned across the layers that use them. A config set that uses a single
layer is unaffected. Previously, a project schema silently shadowed a
packaged layer's schema; if your packaged layer's schema relied on that
shadowing, review it before upgrading.
Plugin configuration is discovered under plugins.<mount-path> in the same packaged/project public/local files. The mount path is the chain of effective namespaces from the root (a .use(plugin, { ns }) override replaces the plugin's own ns), e.g. aws/whoami or deploy-api. The host merges slices by precedence (packaged → project/public → project/local) and deep‑interpolates string leaves once against { ...ctx.dotenv, ...process.env } (process.env wins for plugin slices). Plugins read their own validated slice via the instance‑bound helper plugin.readConfig(cli).
Location and shape:
{
"plugins": {
"batch": {
"rootPath": "./packages"
},
"aws/dynamodb": {
"create": { "version": "v1" }
},
"my-plugin": {
"scripts": {
"build": { "cmd": "npm run build", "shell": "/bin/bash" }
},
"shell": false
}
}
}
Precedence and timing:
For compile‑time DX, overlayEnv preserves the key set:
import { overlayEnv } from '@karmaniverous/get-dotenv/env/overlay';
const base = { A: 'a' };
const out = overlayEnv({
base,
env: 'dev',
configs: {},
programmaticVars: { B: 'b' },
});
// out is typed as { A?: string } & { B?: string } at compile time
Presentation‑only diagnostics help audit values without altering runtime behavior:
secret, token, pass/password, api_key/api-key/apikey and key, case-insensitively, as a whole word or as an underscore- or dash-delimited segment of the key: API_SECRET, DB_PASSWORD and GITHUB_TOKEN are masked; SECRETARY and MONKEY are not. Custom patterns (--redact-pattern <pattern...>, rootOptionDefaults.redactPatterns, or redactPatterns in getDotenv options) add to the built-in patterns. A RegExp pattern is used without its g and y flags, so it matches every key.--entropy-min-length characters (default 16) exceed --entropy-threshold bits/char (default 3.8). Both flags take numbers (a non-number is a usage error), and their help labels show the effective defaults.getDotenv({ log: true }).^GIT_, ^npm_, ^CI$, SHLVL) always applies: patterns from --entropy-whitelist, rootOptionDefaults.entropyWhitelist or entropyWhitelist in getDotenv options add to it.You can define a scripts table in config. Script strings are resolved by the cmd and batch commands. Only the table's own keys are script names: a command named after an inherited object property (toString, constructor) runs as typed. If you want a named script to inherit the root shell behavior, use the string form; the object form { cmd, shell } uses shell as the effective shell for that entry (and when omitted, the script currently runs with shell-off rather than inheriting the root shell):
{
"scripts": {
"bash-only": { "cmd": "echo $SHELL && echo OK", "shell": "/bin/bash" },
"plain": { "cmd": "node -v", "shell": false }
}
}
Then:
getdotenv cmd bash-only
getdotenv cmd plain
One script is built in: git-status runs git status -s -u -b (the ## <branch> line, then short status with untracked files) with shell: true, the OS default shell (PowerShell on Windows, /bin/bash elsewhere). Its command uses no shell operators, so it works under PowerShell 5.1, which has no &&. When you write a script for that default shell on Windows, do the same. Config scripts are merged with it.
For help‑time visibility of root flags (e.g., hiding --capture or an entire family like --shell/--shell-off), set rootOptionVisibility in JSON/YAML/JS/TS config. Precedence matches root defaults: createCli < packaged/public < project/public < project/local; a higher layer’s true shows a flag a lower layer hid. Every root flag has a key, including env, outputPath, defaultEnvKey, debug and excludeAll. The merged visibility applies to every help rendering: a hidden flag leaves root help and the inherited <alias> options (anywhere) section of every subcommand's help, qualified name included (see Qualified options).