The .env cascade
Which .env files are loaded, in what order, and how the active Environment selects them.
The framework loads a small cascade of .env files once at boot, before
any config is read. The cascade follows dotenv-flow conventions:
most specific wins, real process env wins over every file, and tests stay
hermetic.
The cascade is parsed once per process into an in-crate map, and every
ConfigService reader consults it under
the real process environment. Nothing in the running app mutates std::env —
set_var is unsound against a concurrent read on another thread, so config
resolution stays side-effect-free by design.
The order
Section titled “The order”real env > .env.<environment>.local > .env.local > .env.<environment> > .envRead left-to-right as decreasing precedence: a key set in the real
process environment overrides every file; among files, .env.<env>.local
wins, .env loses. Set-if-absent semantics make the first writer win, so
loading “most specific first” implements the documented order without a
second pass.
| Layer | Committed? | Purpose |
|---|---|---|
| Real process env | n/a | Deployment overrides, secrets injected by the orchestrator |
.env.<env>.local | gitignored | Per-machine secrets for one environment (e.g. local prod creds) |
.env.local | gitignored | Per-machine secrets shared across environments |
.env.<env> | committed | Non-secret defaults for one environment |
.env | committed | Non-secret defaults shared across environments |
A value pinned in code (Module::for_root(cfg)) slots in between: below the
real process env, above every file — and it takes its whole namespace off the
files, so the boot names each key a file sets there that it no longer reads.
The reasoning and the full chain live with
the dual-path rule.
The convention: anything ending in .local is gitignored, everything
else is committed.
An app’s own files
Section titled “An app’s own files”A workspace starts every binary from its root, so the files above are shared:
every app reads them. What tells one app apart — its port, the audience it
requires, a signing key only the issuer may hold — goes in that app’s own
directory, beside its Cargo.toml (apps/<app>/ in the workspace
nestrs new scaffolds). Under a declared development or test profile,
its four files are read whole over the root’s, the order Nx gives a project’s
files over its workspace’s:
real env > apps/<app>/.env.<environment>.local > apps/<app>/.env.local > apps/<app>/.env.<environment> > apps/<app>/.env > .env.<environment>.local > .env.local > .env.<environment> > .envNESTRS_HTTP__PORT=3002NESTRS_AUTHN__AUDIENCE=http://localhost:3002So an app’s committed .env outranks the root’s .env.local: to change one
app’s key on your machine, write it in that app’s own .env.local. Its
.env.local stays unread under test, as the root’s does, and <PREFIX>_ENV
and NESTRS_ENV_PREFIX are refused in its files as in the root’s.
A deployed profile — staging, production, or none declared — reads the
root’s files alone. A deployment’s binary runs far from the directory it was
built in, so it names its own port and audience on the process, as
the demo’s chart does. The directory is the one
#[nest_rs::main] captures where it expands; the test harness reads the
package under test the same way, and nestrs doctor -p apps/<app> reports
what that app reads.
The root is the directory the process starts in, so a process started in
apps/auth/ reads that directory’s .env under every profile. A committed
credential therefore sits in .env.development and .env.test, which no
deployed profile reads from any directory: that is where the demo’s auth holds
its fixtures.
The active environment
Section titled “The active environment”The <environment> segment is the variant of Environment, read from
the reserved <PREFIX>_ENV variable. It sits outside the
<PREFIX>_<DOMAIN>__<KEY> scheme, as the kernel’s
console settings,
<PREFIX>_LOG_FORMAT and <PREFIX>_LOG_SOURCE_LOCATION, do — the three are
read before any config exists. <PREFIX>_ENV selects which .env
files to load, so it must come from the real process environment, not a
.env file. Writing it into one is a boot error naming the fix, the
same refusal NESTRS_ENV_PREFIX gets: the value arrives after the
cascade it names was already chosen, and it would arm development-only
affordances from a committed file. A file may only restate a value the
process actually carries.
pub enum Environment { Development, Test, Staging, Production,}<PREFIX>_ENV | Variant |
|---|---|
development / dev | Development |
test | Test |
staging / stage | Staging |
production / prod, unset, anything unrecognized | Production |
The default is Production. A process that declares nothing reads
.env.production, never .env.development, and arms no development
convenience: the OpenAPI documentation, GraphQL’s playground and
introspection and Server-Timing stay closed, no committed artifact is
rewritten, storage refuses plain HTTP, and the console writes JSON. No
profile names a database, a Redis or a store, nor the credentials to reach
them: the profile’s .env file does — nestrs new writes compose.yml’s
services into .env.development and .env.test — and a deployment names its
own. An app that reads any config — every app importing a module that owns
one — says so once at boot, at info on
nest_rs::config — no environment declared; running as production — and an
unrecognized value is said once on stderr, by the variable’s name.
nestrs run dev declares development on the process; a run outside it, an
IDE’s included, declares it the same way. Tests default to Test (the test
harness sets it before any builder runs).
Test mode is hermetic
Section titled “Test mode is hermetic”Under Environment::Test, the cascade skips .env.local. A
developer’s personal secrets (database URLs, OAuth client IDs, API
tokens) cannot leak into a test run. The committed .env.test still
loads — that’s where shared test defaults belong.
.env.test.local ← loaded (per-machine test overrides).env.local ← skipped under Test.env.test ← loaded.env ← loadedIf a test sets <PREFIX>_ENV to something else explicitly (CI asserting
prod behavior, for instance), the cascade follows that.
When the load happens
Section titled “When the load happens”Exactly once per process, before your main runs:
#[nest_rs::main]parses it and merges it intostd::env(set-if-absent, so the real environment still wins) before it builds the runtime, while the process still has one thread. Everythingmaindoes therefore sees the cascade, including the many consumers that only knowstd::env::var:RUST_LOG/<PREFIX>_LOG_FORMAT/<PREFIX>_LOG_SOURCE_LOCATIONin.env.developmentreach the logging setup, which reads the process environment long before aConfigServiceexists, andOTEL_*reaches the OpenTelemetry SDK. Yourmainwrites no line for it.- The default
EnvSourcereads that same parse. A customConfigSourcenever does; it supplies its own values. - The first config the boot loads does not parse it. It reads
<PREFIX>_ENVfrom the real environment and registers the resultingArc<Environment>, which is what decides which files the parse read — and files theinfoline above when the process declared none.
Every layer is optional: a file that does not exist contributes nothing, which
is what lets the same cascade run unchanged in a container with no .env at
all.
Variable naming
Section titled “Variable naming”Inside the cascade and in real env vars, every configurable field follows the same scheme:
<PREFIX>_<NAMESPACE>__<KEY><PREFIX>_— the deployment’s prefix:NESTRSunless the process setsNESTRS_ENV_PREFIX, which renames every variable (your own prefix).<NAMESPACE>— the namespace from#[config(namespace = "…")], uppercased.__— a double underscore separator (single underscores are reserved for word boundaries inside keys).<KEY>— the field name, uppercased:#[config]reads each field under its own name, and a duration’s key adds its unit (_SECS,_MS) through its bounds.
Examples, under the default prefix:
NESTRS_SEAORM__URLNESTRS_SEAORM__MAX_CONNECTIONSNESTRS_OAUTH__SERVER__CLIENTSNESTRS_HTTP__PORTA feature reads only its own namespace. To borrow a
sibling variable, which is rare, call env_var(&var_name("<other>", "<KEY>"))
directly: var_name spells it under the deployment’s prefix.
Quoting rules inside .env files
Section titled “Quoting rules inside .env files”The minimal parser handles three forms:
# Unquoted: as-is, no escapingURL=postgres://localhost/app
# Double-quoted: expands \n \t \r \\ \"JWT_PUBLIC_KEY="-----BEGIN-----\nMIIB...\n-----END-----"
# Single-quoted: literal, no escape expansionRAW='a\nb' # value is the four characters: a, backslash, n, bLines starting with # are comments. Empty lines are skipped. An
export prefix is tolerated for shell compatibility. Empty keys and
lines without = are dropped and counted: the cascade loads before any
subscriber exists, so one line on stderr names the file and how many it
skipped, never what they held — nestrs: skipped malformed .env lines path=./.env.local skipped=2. A file that exists but cannot be read is
skipped and said the same way.
The double-quoted escape set exists for one reason: PEM keys fit on a
single line with \n instead of literal newlines.
Going further
Section titled “Going further”- Configuration overview — the typed-struct contract.
- Alternative sources — replace
EnvSourcewith Vault or a K8s ConfigMap. - Overriding in tests — seed pinned values, unit-test a config on a map of variables.
- Env-var reference — every
<PREFIX>_*variable, by namespace.