How does the Nx task hash decide whether environment variables are part of the cache key?

Before Nx runs a target, it computes a hash from everything the target is declared to depend on. That includes the file sets matched by the target's inputs (often through named inputs such as default or production), the inputs of the projects it depends on, any env inputs, any runtime inputs, any declared externalDependencies, and the target's command and options. If an identical hash already exists in the local or remote cache, Nx restores the stored terminal output and artifacts and skips execution.

The hash only reflects what is declared. Nx does not trace which files a process opens or which variables it reads from process.env. If a build inlines API_BASE_URL into a bundle, or a test suite switches behavior on FEATURE_FLAGS, and neither is declared as an input, changing that variable leaves the hash unchanged. Nx then reports a cache hit and replays an artifact built against a different value. It does this without any error, because from the hash's point of view nothing changed.

Environment variables are the most common undeclared input. They are set outside the repository by shells, CI job definitions, secret managers, and .env files, so they never appear in a diff, and nobody thinks to list them.

The core rule is that a cache hit is correct only if the hash covers every variable that can change the task's output.

This matters most to engineers who own CI pipelines with shared or remote caching. There, one machine's environment can produce artifacts that every other machine and branch reuses.

 DECLARED INPUTS (hashed)             UNDECLARED (invisible to hash)
+--------------------------------+    +------------------------------+
| inputs: file sets / named      |    | API_BASE_URL  (CI job, .env) |
|   inputs (default, production) |    | FEATURE_FLAGS (shell export) |
| dependency project inputs      |    +--------------+---------------+
| env inputs                     |                   |
| runtime inputs                 |                   | read via process.env
| externalDependencies           |                   | at run time only
| command + options              |                   |
+---------------+----------------+                   |
                |                                    |
                v                                    |
      +-------------------+                          |
      |    task hash      |                          |
      +---------+---------+                          |
                |                                    |
                v                                    |
  +---------------------------+   miss   +-----------v-----------+
  | local / remote cache      |--------->| run target            |
  | (keyed by task hash)      |<---------| output depends on     |
  +-------------+-------------+  store   | undeclared vars too   |
                | hit                    +-----------------------+
                v
  +---------------------------+
  | replay stored output and  |
  | artifacts; skip execution |
  +---------------------------+

 changed undeclared var => same hash => hit => stale artifact replayed

Only declared inputs feed the Nx task hash. Variables the process reads from process.env without declaring them still shape the output but never change the cache key, so a hit can replay an artifact built with different values.

How does Nx load .env files, and why doesn't that make them cache inputs?

Before running a task, Nx reads dotenv files into the task's process environment. The usual convention covers a general .env, local override files intended to stay out of version control, and files scoped to a target or configuration, such as .env.<target> and .env.<target>.<configuration>. Nx looks for these at both the workspace root and the project root. More specific files take precedence over general ones, and a variable already set in the process environment is not overridden by any file. The exact filenames, the local-override naming, and the precedence order have changed between Nx releases, so check the documentation for the Nx version you run.

Loading a file is not the same as hashing it. The loader injects values into the environment, but those values do not enter the task hash. A file affects the hash only when a file-set input matches its path. That is why location matters:

File location Loaded by Nx Hashed by a typical {projectRoot}/**/* default input
Project root .env Yes Usually yes, unless excluded by a negated pattern
Workspace root .env Yes No, unless added to a shared or named input
Variable already in the shell Not overridden by files No, unless declared as an env input

A changed workspace-root .env can therefore produce a different build with an unchanged hash, and the cache will replay stale output.

A second loader adds more risk. If the application also calls its own dotenv library, it may read different files, resolve them from a different working directory, or apply a different override rule than Nx. The effective value then depends on which loader ran first, which neither the hash nor a quick reading of the config will show you. Choose one loader and remove the other.

How do you declare env inputs per target in Nx?

Once a single loader owns the values, tell Nx which variables matter to which target. Add {"env": "API_BASE_URL"} to the inputs array of every target whose output depends on that variable. Nx then includes the variable's current value in that target's hash and nothing else's.

To avoid repeating this across projects, define it once in nx.json. Create a named input such as buildEnv that lists the env entries the build bundles, and reference it from targetDefaults.build.inputs next to production and ^production. Give test its own named input containing only what tests actually read. Variables used only at deploy time, such as registry credentials or a target region, belong on the deploy target alone. Under this scheme, rotating a deploy secret leaves lint and unit-test caches untouched, because those targets never declared the variable.

Declare the variable, not the file

An env input hashes the effective value, wherever it came from: a .env file, a CI secret, or an export in the shell. Hashing .env as a file input gets both cases wrong. It misses values that CI injects without touching the file, so a stale artifact can be restored. It also changes on edits that leave the effective value the same, such as comments, reordering, or a key that the shell overrides anyway, so the cache misses for no reason.

Check in your own workspace whether env inputs are resolved after Nx applies .env files. Do not assume the ordering. Section 7 shows how to confirm it.

Put a short comment or README entry next to each named input that lists the variables it covers and the reason each one is there. Reviewers can then catch a missing declaration at the point where it would be added.

{
  "namedInputs": {
    "default": ["{projectRoot}/**/*", "sharedGlobals"],
    "production": ["default", "!{projectRoot}/**/*.spec.ts"],
    "sharedGlobals": [],
    "buildEnv": [
      { "env": "API_BASE_URL" },
      { "env": "PUBLIC_FEATURE_FLAGS" }
    ],
    "testEnv": [
      { "env": "API_BASE_URL" }
    ],
    "deployEnv": [
      { "env": "DEPLOY_REGION" },
      { "env": "REGISTRY_TOKEN" }
    ]
  },
  "targetDefaults": {
    "build": {
      "dependsOn": ["^build"],
      "inputs": ["production", "^production", "buildEnv"],
      "cache": true
    },
    "test": {
      "inputs": ["default", "^production", "testEnv"],
      "cache": true
    },
    "lint": {
      "inputs": ["default"],
      "cache": true
    },
    "deploy": {
      "dependsOn": ["build"],
      "inputs": ["production", "deployEnv"]
    }
  }
}

An nx.json that groups env inputs into named inputs per target, so build and test hash only the variables they read, deploy-only values like DEPLOY_REGION stay off lint and test hashes, and each named input documents its variable list.

When should you use runtime inputs instead of env inputs or file inputs?

That works for values that already live in the environment. Some inputs that change a build's output are neither a file in the workspace nor a variable someone exported: the Node or compiler version on the agent, the CPU architecture a native addon is built for, or configuration a script derives from several sources. A runtime input such as {"runtime": "node -v"} covers these. Nx runs the command and hashes its output, so two agents with different toolchains produce different cache keys even when every file and variable matches.

Nx runs that command each time it computes the hash, for every task that declares it. Keep it fast and deterministic. A command that calls a remote API adds latency to every run and fails when the network is down. A command whose output includes a timestamp, a random value, or a build number produces a new hash every time, so the cache never hits and the target behaves as if caching were turned off. Print only the part of the value that affects the output. For example, print the major version if minor releases don't change the artifact.

Input type What it captures Failure mode
File set on .env Every byte of the file Misses values overridden by the shell or CI; any edit to an unrelated line invalidates the cache
Env input The value of one named variable when Nx computes the hash A variable the target reads but nobody listed is silently ignored
Runtime input The output of a command Slow or nondeterministic commands make every run slower or prevent any cache hit
Target option A literal value in the project configuration or a CLI override The value is committed to config, so it is unsuitable for secrets and can drift from the copy in .env
{
  "namedInputs": {
    "default": ["{projectRoot}/**/*", "sharedGlobals"],
    "sharedGlobals": [],
    "buildEnv": [
      { "env": "API_BASE_URL" },
      { "runtime": "node -p \"process.versions.node.split('.')[0]\"" },
      { "runtime": "node -p process.arch" }
    ]
  },
  "targetDefaults": {
    "build": {
      "cache": true,
      "inputs": ["default", "buildEnv"]
    }
  }
}

An nx.json named input that combines an env input with two fast, deterministic runtime inputs, the Node major version and the CPU architecture, so build cache keys change only when those values change.

Why does splitting build-time and run-time configuration improve cache hit rates?

A variable only belongs in a build's cache key if it changes the bytes the build produces. When a frontend bundler replaces process.env.API_URL with a string literal, the value becomes part of the artifact. It must be an env input, or Nx can restore a bundle compiled against the wrong endpoint. A server that reads its environment when the process starts is different. The compiled output is identical whatever the value, so declaring that variable as a build input only fragments the cache. Each environment, preview URL or rotated credential then produces a new hash for the same bytes.

Moving configuration to runtime is often the largest single gain because it removes inputs. Options include a config file mounted at container start, a config endpoint fetched on load, or plain process environment.

Illustrative estimate (assumed numbers, not a benchmark)

Saved build minutes per day = runs per day × affected projects × minutes per build × (miss rate before − miss rate after)

Assume 40 CI runs per day, 10 affected projects, 3 minutes per build, and a miss rate that drops from 60% to 20%:

40 × 10 × 3 × 0.4 = 480 CI minutes per day

Each run saves 12 minutes of compute. How much of that shows up as shorter waits for developers depends on how many builds sit on the critical path rather than running in parallel.

The security trade-off runs the other way. Nx stores a hash of env input values, not the values themselves, but it caches outputs exactly as produced, including terminal output. A secret inlined into a bundle or echoed to a log ends up in the local cache and in any remote cache, where anyone with read access can see it. Secrets should be read at runtime only.

When should you avoid declaring env inputs or hashing .env files?

Two failure modes sit on either side of a correct configuration, and they cost you in different ways.

Mistake Symptom Why it hurts
Over-declaring env inputs or broad .env* globs Low hit rate Tasks rerun when nothing relevant changed
Volatile variable (build timestamp, commit SHA, per-run ID) in a shared named input Every dependent task misses The hash changes on every run, so the cache never helps
Under-declaring Fast, wrong hits A stale artifact built for another config ships silently

Under-declaring is the worse of the two. A miss costs time. A wrong hit costs correctness, and nothing in the output tells you it happened. If a volatile value must reach an artifact, inject it in a step outside the cached task. Do not hash it.

Local-versus-CI drift is a quieter version of the same problem. A developer may have a .env.local that CI lacks, or shell exports that CI never sets. If those files or variables are hashed, the same commit produces different hashes on a laptop and on CI. The remote cache then stops sharing results between the two.

Shared named inputs have a tradeoff of their own. They prevent sprawl across per-target .env files, but they also hide which variables a given target actually reads. Keep shared inputs small. Declare target-specific variables on the target itself.

Sort .env files by role:

  • Commit non-secret defaults, and hash them.
  • Keep secrets in uncommitted local files or a CI secret store, and keep them out of the hash.

How can you verify that the Nx cache sees your environment variables?

Start by checking what Nx resolved, not what you think you configured. Run nx show project <name> (add --json for scripted use, or --web to browse) and inspect the target's inputs. Named inputs like production and default get expanded across project configuration, nx.json defaults, and inferred plugin targets. Confirm that the env and runtime entries you expect actually appear on that target. If they are missing there, they are missing from the hash.

Then test behaviour with a single controlled change:

  1. Run the target once so it populates the cache.
  2. Change exactly one declared variable and run the target again. It should miss the cache and execute.
  3. Run an unrelated target that does not declare the variable. It should still report a cache hit.

If step 3 misses, the variable has leaked into a shared named input. That is too broad, and it costs hit rate everywhere.

Automate step 2 in CI. Run the affected target twice with different values for the variable. Capture the task hash or cache status from Nx's output. Fail the job if the second run is a cache hit or the hash is unchanged. Where Nx exposes the hash depends on the version (terminal output, verbose logging, or run metadata), so adapt the flags and parsing to the Nx version you run.

This check is cheap compared with the failure it prevents. A wrong cache hit doesn't error. It ships an artifact built with stale configuration, and someone later spends hours working out why production points at the wrong endpoint. Catching the missing input in a pull request turns that debugging session into a red check with an obvious cause.

#!/usr/bin/env bash
# CI guard: fail if changing API_URL does not invalidate the cache for myapp:build.
# Cache-status wording varies by Nx version; adapt the grep pattern to your output.
set -euo pipefail

PROJECT=myapp
TARGET=build
HIT_PATTERN='read the output from the cache'

# 1. Inspect what Nx resolved for the target, not what we think we configured.
npx nx show project "$PROJECT" --json > project.json
if ! jq -e --arg t "$TARGET" '.targets[$t].inputs | tostring | contains("API_URL")' project.json > /dev/null; then
  echo "API_URL is not in the resolved inputs of $PROJECT:$TARGET" >&2
  exit 1
fi

# 2. Populate the cache with one value.
API_URL= npx nx run "$PROJECT:$TARGET" | tee run1.log

# 3. Same value again: should be a cache hit (proves caching works at all).
API_URL= npx nx run "$PROJECT:$TARGET" | tee run2.log
if ! grep -q "$HIT_PATTERN" run2.log; then
  echo "Expected a cache hit with an unchanged API_URL" >&2
  exit 1
fi

# 4. Different value: must miss, otherwise the env var is not part of the hash.
API_URL= npx nx run "$PROJECT:$TARGET" | tee run3.log
if grep -q "$HIT_PATTERN" run3.log; then
  echo "Wrong cache hit: changing API_URL did not change the task hash" >&2
  exit 1
fi

echo "OK: API_URL is part of the $PROJECT:$TARGET hash"

A CI script that confirms API_URL appears in the target's resolved inputs, then runs the target with the same and a different value and fails if a changed value still produces a cache hit.

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 environment variables cache, 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.
  • Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.

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.
  • Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
  • 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.