Skip to content

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.

real env > .env.<environment>.local > .env.local > .env.<environment> > .env

Read 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.

LayerCommitted?Purpose
Real process envn/aDeployment overrides, secrets injected by the orchestrator
.env.<env>.localgitignoredPer-machine secrets for one environment (e.g. local prod creds)
.env.localgitignoredPer-machine secrets shared across environments
.env.<env>committedNon-secret defaults for one environment
.envcommittedNon-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.

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> > .env
apps/api/.env
NESTRS_HTTP__PORT=3002
NESTRS_AUTHN__AUDIENCE=http://localhost:3002

So 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 <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.

nest_rs::config::Environment
pub enum Environment {
Development,
Test,
Staging,
Production,
}
<PREFIX>_ENVVariant
development / devDevelopment
testTest
staging / stageStaging
production / prod, unset, anything unrecognizedProduction

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).

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 ← loaded

If a test sets <PREFIX>_ENV to something else explicitly (CI asserting prod behavior, for instance), the cascade follows that.

Exactly once per process, before your main runs:

  • #[nest_rs::main] parses it and merges it into std::env (set-if-absent, so the real environment still wins) before it builds the runtime, while the process still has one thread. Everything main does therefore sees the cascade, including the many consumers that only know std::env::var: RUST_LOG / <PREFIX>_LOG_FORMAT / <PREFIX>_LOG_SOURCE_LOCATION in .env.development reach the logging setup, which reads the process environment long before a ConfigService exists, and OTEL_* reaches the OpenTelemetry SDK. Your main writes no line for it.
  • The default EnvSource reads that same parse. A custom ConfigSource never does; it supplies its own values.
  • The first config the boot loads does not parse it. It reads <PREFIX>_ENV from the real environment and registers the resulting Arc<Environment>, which is what decides which files the parse read — and files the info line 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.

Inside the cascade and in real env vars, every configurable field follows the same scheme:

<PREFIX>_<NAMESPACE>__<KEY>
  • <PREFIX>_ — the deployment’s prefix: NESTRS unless the process sets NESTRS_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__URL
NESTRS_SEAORM__MAX_CONNECTIONS
NESTRS_OAUTH__SERVER__CLIENTS
NESTRS_HTTP__PORT

A 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.

The minimal parser handles three forms:

.env
# Unquoted: as-is, no escaping
URL=postgres://localhost/app
# Double-quoted: expands \n \t \r \\ \"
JWT_PUBLIC_KEY="-----BEGIN-----\nMIIB...\n-----END-----"
# Single-quoted: literal, no escape expansion
RAW='a\nb' # value is the four characters: a, backslash, n, b

Lines 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.