What are Nx env files and how does Nx load them before a task runs?

Nx env files are ordinary dotenv-format files that Nx reads on its own before it executes a task. When you run a target such as build or serve, Nx looks for recognized .env file names in the workspace root and in the root of the project that owns the target. It loads the variables it finds into the task's process environment. Your application code then reads them through process.env as usual, without importing a dotenv library or calling a loader at startup.

Nx recognizes three families of file names:

Family Example names When Nx loads it
General .env, .env.local, .local.env Any target in that project or workspace
Target-specific .env.build, .build.env Only when the build target runs
Target plus configuration .env.build.production Only when build runs with the production configuration

This matters most to backend and platform engineers who run many services in one repository. Each service needs its own ports, database URLs and feature flags. Each also needs different values for serve, test and production builds. Without Nx's loader, every app carries its own dotenv bootstrap code. Over time those copies drift: they disagree on file names, on load order and on whether a missing file is an error. Moving loading into the task runner means every project follows one convention. A new service gets environment handling from file placement alone.

Supported names and patterns have changed between Nx releases. Check the exact list against the documentation for the Nx version installed in your workspace before you rely on a particular file name.

How does it work, step by step?

When you run a command like nx run api:serve:development, Nx works through the following steps:

  1. Resolve the task. Nx identifies the project (api), the target (serve) and the configuration (development, or the target's defaultConfiguration if you did not pass one). It also determines the project root, such as apps/api.
  2. Build the candidate file list. From the target and configuration names, Nx derives the file names it will look for: target-plus-configuration names, then target names, then configuration names, then generic names. It looks for each name in the project root and in the workspace root.
  3. Load files in order without overwriting. Nx parses each existing file as dotenv and adds its keys to the environment. A key that is already set is left alone, whether the shell set it or an earlier file did. This is why the most specific file wins and why the real process environment beats every file.
  4. Start the executor with the merged environment. The executor runs with that environment, and so does any child process it spawns, such as the command in an nx:run-commands target. Application code reads the values through process.env.
  5. Compute the cache hash separately. Nx hashes the task from its declared inputs. The loaded variables are not part of the hash unless an input names them. The cache sections below cover this in detail.

Missing files are skipped silently. Nx does not report which files it loaded, and it does not warn when a configuration has no matching file. Details such as variable expansion inside files and the exact candidate list depend on the Nx version, so verify them in your workspace.

Who should use Nx env files?

Nx env files fit teams that meet most of these conditions:

  • You run several apps or services in one Nx workspace. Each one needs its own defaults, and you want the same loading convention everywhere instead of a bootstrap snippet in every app.
  • Developers and CI start tasks through Nx. That means nx serve, nx build, nx test or nx affected. The loader only applies to tasks Nx launches.
  • Values differ by target or configuration. For example, a local database for serve, a test database for test, and a public API base URL for build:production. The naming scheme maps directly onto those differences.
  • The values are mostly non-secret defaults. Ports, log levels, feature-flag defaults and local service addresses are good candidates. Secrets should come from the process environment that CI or a secret store sets up.
  • Someone owns nx.json. That person keeps env-based cache inputs declared in targetDefaults, so loaded values that end up in build output are part of the hash.

Platform teams that maintain shared tooling for many service teams get the most out of this. One documented convention replaces many per-app variations.

How does Nx decide which .env value wins?

Nx loads the most specific files first and never overwrites a variable that is already set. Precedence follows from that rule. Once a key exists, whether from the shell or from an earlier file, later and more generic files cannot replace it. The general order is target-plus-configuration files, then target files, then generic project files, then workspace-root files. The exact list depends on your Nx version.

Trace API_URL through nx serve api --configuration=development, assuming each file defines it:

  • Root .env: root-default
  • apps/api/.env: api-default
  • apps/api/.env.serve: api-serve
  • apps/api/.env.serve.development: api-serve-development

The resolved value is api-serve-development. The configuration-specific file is read first, so the other three definitions are ignored for this key. Keys that appear only in the root .env still come through, because nothing earlier set them.

The real process environment sits above all of these. A CI secret injected as API_URL beats every file. This is the behaviour you want in pipelines: a committed .env can never replace a production credential.

The same rule causes problems locally. An export API_URL=... left over from an earlier debugging session silently overrides every file. You edit .env.serve.development and nothing changes. Before you suspect Nx, check env | grep API_URL in the terminal that runs the task.

Layering also has a cost. With four or more files plus the shell, finding where a value came from means checking each source in order. Keep the number of files that define the same key small.

printf 'API_URL=root-default\n' > .env                                       # workspace root, read last
printf 'API_URL=api-default\n' > apps/api/.env                               # generic project file
printf 'API_URL=api-serve\n' > apps/api/.env.serve                           # target file
printf 'API_URL=api-serve-development\n' > apps/api/.env.serve.development   # target + configuration, read first

nx serve api --configuration=development

export API_URL=from-shell
nx serve api --configuration=development   # now resolves to from-shell

env | grep API_URL

grep -H API_URL apps/api/.env.serve.development apps/api/.env.serve apps/api/.env .env

unset API_URL
nx serve api --configuration=development   # back to api-serve-development

Traces API_URL through four layered .env files, then shows a leftover shell export overriding all of them and how to find and clear it.

How do target configurations map to env files?

The link between a target configuration and an env file is a naming convention. Nx takes the name of the target and the name of the configuration being run, and looks for files whose names contain them. Running nx run api:build:staging makes .env.build.staging a candidate, along with the broader .env.staging and .env.build. The configuration name is only a string. Nx does not check that the file contents relate to the configuration. It only checks that the names match.

In the example that follows, apps/api/project.json defines build and serve targets, and each has development and production configurations. The project root next to it contains .env.development, .env.production and .env.serve.development. Building or serving with production reads only the shared production file. Serving with development also picks up the serve-specific file, which is where a local database URL or debug port goes. Think of each configuration block in project.json and its env file as two halves of one definition. If you rename production to prod in one place and not the other, the file stops loading, and nothing reports an error.

That coupling is hidden, and it costs you in two ways:

  • project.json does not show the inputs. A reviewer reading it cannot tell which variables a task receives. They have to list the project directory and work out the matches themselves.
  • Extra files change behavior silently. A forgotten .env.build in the project root takes effect without anyone noticing. It might be committed by accident or left over from debugging, and it starts injecting values into every build configuration.
apps/api/
├── project.json
├── .env.development        # shared by build:development and serve:development
├── .env.production         # shared by build:production and serve:production
└── .env.serve.development  # only serve:development (local DB URL, debug port)

{
  "name": "api",
  "targets": {
    "build": {
      "executor": "nx:run-commands",
      "options": { "command": "node tools/build.js" },
      "defaultConfiguration": "production",
      "configurations": {
        "development": {},
        "production": {}
      }
    },
    "serve": {
      "executor": "nx:run-commands",
      "options": { "command": "node dist/apps/api/main.js" },
      "defaultConfiguration": "development",
      "configurations": {
        "development": {},
        "production": {}
      }
    }
  }
}

A project.json with build and serve targets next to its project root, showing that the configuration name is the only link to the env files Nx loads.

Why doesn't loading a .env file invalidate the Nx cache?

That is possible because Nx treats loading and caching as two separate steps. Before a task runs, Nx merges the matching .env files into the process environment. The cache hash is computed only from the task's declared inputs. A variable that appears in a loaded file does not become part of the hash. If API_URL changes from the staging host to the production host, the hash stays the same unless something declares that variable as an input.

File patterns usually don't fill that gap. The default named input covers {projectRoot}/**/*, which excludes workspace-root .env files. Nx also builds its file map from files that aren't ignored by .gitignore or .nxignore. Most .env files are gitignored, so they are probably missing from the hash even inside the project root. Listing a gitignored path explicitly may not change that, so check what your workspace actually hashes. A more reliable fix is to declare cache inputs env directly: add { "env": "API_URL" } to a target's inputs or to a named input. In nx.json, a targetDefaults.build.inputs array of "production", "^production", { "env": "API_URL" } and { "env": "DATABASE_URL" } applies this to every build target.

Without these inputs, a pipeline can fail without any error. CI builds api for staging and populates the remote cache. The production job then gets the same hash and replays the staging artifact. Nothing fails until production traffic reaches the staging host.

Illustrative estimate (assumed inputs, not a measured result): assume two engineers each spend half a day (4 hours) ruling out deploy scripts and infrastructure. Then both spend another hour finding the cache hit. That comes to about 10 engineer-hours, plus the cost of the incident itself.

{
  "namedInputs": {
    "default": ["{projectRoot}/**/*", "sharedGlobals"],
    "production": ["default", "!{projectRoot}/**/*.spec.ts"],
    "sharedGlobals": []
  },
  "targetDefaults": {
    "build": {
      "cache": true,
      "dependsOn": ["^build"],
      "inputs": [
        "production",
        "^production",
        { "env": "API_URL" },
        { "env": "DATABASE_URL" }
      ]
    }
  }
}

An nx.json targetDefaults entry that adds API_URL and DATABASE_URL as env inputs to every build target, so a staging value and a production value produce different cache hashes even when both come from loaded .env files.

Which env vars belong in the cache hash, and when should you leave them out?

Avoiding that cost starts with matching each target's inputs to how it actually consumes configuration. Hash a variable when its value ends up in the output. Leave it out when the value is only read after the artifact exists.

In practice, define a named input such as buildEnv that lists { "env": "API_BASE_URL" } and similar entries. Reference it only from targets that inline values, such as bundler builds that replace process.env.* at compile time, or codegen that bakes a schema endpoint into generated clients. serve and run targets read variables when the process starts. Hashing those variables adds nothing, and these targets are usually not cacheable anyway.

Target type Reads env at Hash the variable?
Build with inlined config Compile time Yes
Codegen from env-specified source Generation time Yes
Serve / run / start Process start No
Unit tests with mocked config Test time Only if the value changes results

Both kinds of mistake go unnoticed. If you under-declare a variable, Nx serves a stale artifact and nothing errors. If you over-declare, every distinct value creates a new cache entry. A GIT_SHA or timestamp in the inputs means the cache never hits, and CI spends its time rebuilding with no warning.

With a remote or shared cache, inlining has a structural cost. Staging and production need separate cache entries, and each environment gets its own artifact, so the artifact you tested is not the one you deploy. It is often better to keep builds environment-agnostic and read configuration at runtime, through injected variables or a config file loaded at startup. That way one cached build serves every environment.

// nx.json (Nx parses this file with comments allowed)
{
  "namedInputs": {
    "default": ["{projectRoot}/**/*", "sharedGlobals"],
    "production": ["default", "!{projectRoot}/**/*.spec.ts"],
    "sharedGlobals": [],
    // Only variables whose values get inlined into the output.
    // Never list GIT_SHA, timestamps or build numbers here,
    // or every run gets a new hash and the cache never hits.
    "buildEnv": [
      { "env": "API_BASE_URL" },
      { "env": "PUBLIC_ANALYTICS_ID" }
    ]
  },
  "targetDefaults": {
    // The bundler replaces process.env.* at compile time, so these values are part of the artifact.
    "build": {
      "cache": true,
      "inputs": ["production", "^production", "buildEnv"]
    },
    // Generated clients bake in the schema source, so hash it.
    "codegen": {
      "cache": true,
      "inputs": ["{projectRoot}/codegen.config.ts", { "env": "SCHEMA_ENDPOINT" }]
    },
    // Tests use mocked config, so env vars stay out of the hash.
    "test": {
      "cache": true,
      "inputs": ["default", "^production"]
    },
    // serve reads env when the process starts. It is not cached, so env inputs add nothing.
    "serve": {
      "cache": false
    }
  }
}

An nx.json that hashes inlined build and codegen variables through a buildEnv named input, and leaves runtime-only variables for test and serve out of the hash.

What are the alternatives to Nx's automatic env loading?

Automatic loading is only one way to get variables into a process. The others differ in which layer owns the values, and that determines what behaves consistently outside nx run.

Mechanism Where values are resolved Good fit Main drawback
Automatic Nx env files Task runner, before the executor starts Per-project and per-configuration defaults that follow Nx's conventions Applies only to Nx-launched tasks
env / envFile on nx:run-commands Target options in project configuration Non-standard file names, or one shared file for several projects Adds a second source of values on top of automatic loading
dotenv in application code Application startup Apps that must behave the same however they are launched Path handling moves into code, and Nx cannot see it
Runtime injection (orchestrator, secret store, mounted config) Deployment platform Production and environment-agnostic builds Local development needs its own setup

An explicit envFile is the better choice when the file does not follow Nx's naming scheme, such as config/staging.vars, or when several services must read one shared file instead of keeping copies in sync. It also makes the source visible in the target definition, so nobody has to know the lookup order.

Mixing mechanisms is where problems start. If Nx loads .env.local, the target adds envFile, and the app calls dotenv at startup, the final value depends on precedence rules in three layers. Some of those layers skip variables that are already set, and some overwrite them. Choose one owner per variable and document which one it is.

Tools that run outside Nx do not use its loading rules. IDE run configurations, direct node or ts-node invocations, and Docker builds will not read the files Nx would have loaded. They can quietly run with different values than nx run uses.

When should you avoid relying on Nx env files?

Automatic loading is the wrong primary mechanism in these situations:

  • Production runtime configuration. A deployed service is usually not started through nx run, so Nx's loader never runs. Production values should come from the deployment platform or a secret store.
  • Secrets of any kind. A file on disk can be committed by accident, copied into a Docker build context, or inlined into a cached artifact. Inject secrets through the process environment instead.
  • Processes that are often launched outside Nx. If your team routinely starts services from an IDE, runs node directly, or builds inside Docker without Nx, those launches skip the files. You end up with two behaviors. Loading in application code, or explicit envFile, keeps them consistent.
  • Environment-agnostic builds. If you want one artifact for every environment, build-time env files work against that goal. Read configuration at runtime instead.
  • Cases where reviewers must see every input. If your review process requires each variable source to be visible in the target definition, the implicit naming match is a poor fit. Use envFile or env options so the source appears in project.json.
  • Small single-app repositories. If there is only one app and one way to run it, a single dotenv call or a shell wrapper is simpler. A layered naming scheme adds little.
  • Teams that cannot keep naming discipline. Configuration renames and stray files fail silently. If nobody reviews env file names alongside project.json changes, an explicit file reference is safer.

How should you lay out, secure and debug env files in a backend monorepo?

Layout

Use as few layers as possible. Put shared, non-secret defaults in a root .env, such as log format, local ports and feature-flag defaults. Each project gets a .env.<target> file only for values that target needs, like .env.serve or .env.test. Add .env.<target>.<configuration> only when a configuration really behaves differently. If its contents mostly duplicate the target file, delete it. Declare env-based cache inputs once in targetDefaults in nx.json, so a project owner cannot silently drop one. Every extra layer is another place a value can be overridden, so fewer layers with a clear owner for each file cut the time spent tracing where a value came from.

Secrets

Commit only non-secret defaults. Gitignore *.local variants so developer overrides stay on the machine. In CI, inject secrets as process environment variables from your secret store instead of writing them into files. Make sure no secret ends up in a cached output, such as a bundled config or a generated settings file. With a remote cache, a leaked value is not limited to one machine. Anyone who can read the cache can read the artifact.

Debugging

Add a small run-commands target that prints the effective value of a variable. This shows what Nx actually loaded, not what the files suggest. Use nx show project <name> and the graph view to inspect a task's declared inputs. To confirm that a variable change invalidates the cache, change the variable, run the task twice, and compare the task hashes from the two runs. Repeat these checks after every Nx upgrade, because loading order and hashing details can change between releases.

How does it affect development cost?

Automatic env loading moves cost from per-app code into shared conventions and cache configuration. The trade looks like this.

Costs it removes:

  • Bootstrap code in each app. No dotenv import or path resolution in each service, and no tests for that code.
  • Drift between copies. You no longer maintain several slightly different loaders that disagree on file names or on what to do when a file is missing.
  • Onboarding effort. A new service follows the same file-placement rules as every other project. There is no app-specific setup to learn.

Costs it adds:

  • Hidden coupling. Configuration names and file names must stay in sync, and mismatches fail silently. Reviewers need to check file names as well as project.json.
  • Cache configuration. Someone has to keep env inputs in nx.json accurate. Under-declaring gives you stale artifacts. Over-declaring causes constant cache misses.
  • Debugging layered values. Tracing a value through the shell, several files and possibly envFile or app-level dotenv takes longer than reading one explicit source.
  • Upgrade checks. Loading order and supported names can change between Nx releases, so you re-verify after upgrades.

Illustrative estimate (assumed inputs, not a measured result): assume a workspace with 12 services. Writing, reviewing and testing per-app dotenv bootstrap is assumed to take 2 hours per service, which is about 24 hours removed. Against that, assume a one-time 4 hours to document the convention and set targetDefaults inputs. Then assume about 1 hour per month to review env inputs and recheck after upgrades. Under these assumptions the convention pays back within the first year. That holds only if it prevents at least one silent cache incident like the roughly 10 engineer-hour scenario described earlier, rather than causing one. With different inputs, the result can go either way. The deciding factor is whether cache inputs are maintained.

How can it save engineering time?

The savings come from removing repeated decisions and from making the cache trustworthy:

  • New services need no env code. Create the project, drop a .env.serve next to project.json, and nx serve picks it up. There is no loader to copy or adapt.
  • One debugging procedure for every project. Because every project uses the same lookup order, the same checks work everywhere: env | grep, then the file list from most to least specific, then the print-variable target. Engineers moving between services do not relearn each app's loading logic.
  • Per-target defaults without flags. Developers run nx test api or nx serve api without exporting variables or passing extra arguments. The target and configuration select the right file.
  • Correct cache hits. With env inputs declared for inlined values, CI can reuse cached builds safely and rebuilds only when a relevant value changes. Leaving runtime-only variables out of the hash keeps unrelated changes from invalidating the cache.
  • Less configuration in CI scripts. Non-secret defaults live in committed files that Nx loads. Pipeline definitions only need to inject secrets and the true environment-specific overrides.

These savings depend on the practices in the earlier sections: few layers, one owner per variable, cache inputs declared centrally, and secrets kept out of files. Without them, the time saved on setup is easily lost to tracing values and investigating stale cache hits.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to nx env files, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.