How does Nx compute a task hash, and why are env vars ignored by default?

Before running a target, Nx computes a hash for that task. If the hash matches an entry in the local or remote cache, Nx replays the stored terminal output and restores the stored files instead of running the command. The hash is the only thing compared, so whatever goes into it decides whether two runs count as the same.

A task hash is built from:

  • Source files of the project and of the projects it depends on. Which files count is set by the target's inputs, which usually point to named inputs such as default or production.
  • Target configuration: the executor or command, its options, and the active configuration.
  • Workspace-level factors, such as relevant parts of nx.json and the versions of external dependencies resolved from the lockfile.
  • Declared non-file inputs: environment variables listed as env inputs and command outputs listed as runtime inputs.

Nx leaves environment variables out unless you declare them, and the reason is portability. A shell holds many machine-specific values, such as PATH, HOME, and CI job IDs. If Nx hashed all of them, two machines would almost never produce the same hash, and the remote cache would rarely get a hit.

The cost of that choice is the subject of this guide. If a build reads an environment variable that is not declared as an input, that variable never changes the hash. Nx will return a cached artifact built with a different value without any warning.

flowchart LR
    A[Project source files] --> H[Task hash]
    B[Dependency source files] --> H
    C[Target config and options] --> H
    D[Declared env and runtime inputs] --> H
    H --> L{Cache lookup}
    L -->|hit| R[Restore outputs]
    L -->|miss| X[Run task]
    E[Undeclared env var, e.g. API_URL] -.read only at execution.-> X
+--------------------------+
| Project source files     |--+
+--------------------------+  |
+--------------------------+  |
| Dependency source files  |--+
+--------------------------+  |
+--------------------------+  |    +-----------+    +--------------+
| Target config + options  |--+--->| Task hash |--->| Cache lookup |
+--------------------------+  |    +-----------+    +--------------+
+--------------------------+  |                       |           |
| Workspace: nx.json,      |--+                      hit         miss
| lockfile deps            |  |                       |           |
+--------------------------+  |                       v           v
+--------------------------+  |             +-------------+  +----------+
| Declared env + runtime   |--+             | Restore     |  | Run task |
| inputs                   |                | outputs     |  +----------+
+--------------------------+                +-------------+       ^
                                                                  : read only
    +----------------------------------+                          : at run time
    | Undeclared env var, e.g. API_URL |..........................:
    | read by build, never hashed      |
    +----------------------------------+

Only source files, target configuration, workspace factors and declared env and runtime inputs feed the task hash. An undeclared variable such as API_URL is read only when the task actually runs, so a cache hit can return outputs built with a different value.

Why do stale cache hits happen when builds read API_URL or NODE_ENV?

Consider a frontend bundle whose build step replaces references to API_URL and NODE_ENV with literal strings, or a backend service that bakes FEATURE_FLAGS into a generated config module. The CI job for staging runs with API_URL pointing at the staging gateway. It builds, and Nx stores the output under a hash computed from source files, dependencies, and target options. The production job then runs on the same commit with a different API_URL. No file changed, so the hash is identical. Nx restores the staging artifact and reports the task as successful.

A cache miss only costs time. A stale hit costs correctness, and nothing signals it. The logs look clean, tests that ran against the cached output pass, and the deploy ships a bundle that calls staging endpoints or has development-mode checks enabled. You usually find out from users or from traffic dashboards.

A remote cache shared between developer laptops and CI makes this worse. Any participant can write an entry, and any other participant can restore it. A developer who builds locally with a personal .env can populate the entry that CI later restores for a release. Values inlined at build time travel with the artifact, so a token or private key read during the build ends up stored in the shared cache. Anyone with read access to that cache can retrieve it, and it stays there after you rotate the secret in your secret manager.

Teams that use remote caching and build one commit for several environments are the most exposed. A single build configuration that varies only through environment variables is exactly the case the default hash cannot distinguish.

How do you declare env inputs in Nx targets and namedInputs?

Each entry in a target's inputs array adds to the hash, so an env entry should sit next to the file inputs, not replace them. A build target that reads API_URL keeps production and ^production and adds { "env": "API_URL" }. If you list only the env entry, Nx stops hashing source files. The cache then misses on a config change but hits on a code change, which is the opposite of what you want.

To share an env set, define it once in nx.json as a named input, for example buildEnv containing API_URL and NODE_ENV. Then reference it from targetDefaults.build.inputs alongside the file-based named inputs. Every build target gets the same variables, and adding one later is a one-line change. A project that reads an extra variable, such as a feature flag, declares its own inputs for build. Project-level inputs replace the default array instead of merging with it, so restate production, ^production and buildEnv before adding the new entry.

If builds read .env files, hash them as files. Add a fileset entry such as {projectRoot}/.env* (or the workspace-root equivalent) so that editing the file invalidates the cache.

Test-only variables belong in a separate named input used only by test. Examples are a database URL or a test-mode flag. Lint and typecheck should not depend on any of these, because their output cannot change with runtime configuration. Extra inputs on those targets only cost you cache hits.

Input semantics, project-level merge behavior and automatic .env loading have changed across Nx releases. Check the documentation for your installed version before relying on any of the behavior described here.

{
  "namedInputs": {
    "default": ["{projectRoot}/**/*", "sharedGlobals"],
    "sharedGlobals": [],
    "production": ["default", "!{projectRoot}/**/*.spec.ts"],
    "buildEnv": [
      { "env": "API_URL" },
      { "env": "NODE_ENV" },
      { "fileset": "{projectRoot}/.env*" }
    ],
    "testEnv": [
      { "env": "DATABASE_URL" },
      { "env": "TEST_MODE" }
    ]
  },
  "targetDefaults": {
    "build": {
      "cache": true,
      "inputs": ["production", "^production", "buildEnv"]
    },
    "test": {
      "cache": true,
      "inputs": ["default", "^production", "testEnv"]
    },
    "lint": {
      "cache": true,
      "inputs": ["default"]
    },
    "typecheck": {
      "cache": true,
      "inputs": ["production", "^production"]
    }
  }
}

An nx.json that keeps file inputs in every target, adds shared build env vars and .env files via a buildEnv named input, gives test its own env set, and keeps lint and typecheck env-free. A project override must restate all three build inputs before adding its own env entry.

When should you use runtime inputs instead of env inputs?

Some facts that change a build's output are neither files in the workspace nor environment variables. Examples are the Node.js version producing a bundle, the platform a native addon was compiled for, or the version of a system-installed compiler. For these, Nx accepts a runtime input: an entry such as { "runtime": "node --version" } or { "runtime": "uname -sm" } in a target's inputs or in a named input. Nx runs the command and adds its output to the task hash. Two machines with different toolchains therefore produce different hashes, even when every file and declared variable matches.

Prefer this over an env input when the value is not reliably present in the environment. A CI image may set NODE_VERSION, but a developer laptop may not, and the variable can drift from the binary that actually runs. Asking the tool directly hashes what is really installed.

The command has two hard constraints:

  • It must be fast. It runs as part of hash calculation, so a slow command delays tasks, including tasks that end up as cache hits. A version flag or uname is cheap. Scanning a directory or calling a network service is not.
  • It must be deterministic. The same machine state must produce byte-identical output on every run. If the output includes a timestamp, a process ID, or a list whose order varies between runs (unsorted directory listings, hash-map iteration), the hash changes on every run. The task never matches a previous entry, so caching silently stops working. You get no error, only permanent cache misses. If the source data is unordered, pipe it through sort, and strip volatile fields before Nx sees the output.
{
  "namedInputs": {
    "default": ["{projectRoot}/**/*"],
    "toolchain": [
      { "runtime": "node --version" },
      { "runtime": "uname -sm" }
    ]
  },
  "targetDefaults": {
    "build": {
      "inputs": ["default", "^default", "toolchain"],
      "cache": true
    }
  }
}

An nx.json named input that hashes the installed Node.js version and OS/architecture with fast, deterministic runtime commands and applies them to every build target.

When should you avoid adding more env inputs?

Every env input is a promise that the variable changes the output. When that promise is false, you pay for it in cache misses. The worst offenders are the variables CI injects automatically: build numbers, run IDs, commit timestamps, runner hostnames, and job-attempt counters. Their value differs on every pipeline run by design. If one of them ends up in a hash, no two runs ever produce the same key. The cache keeps storing entries that nothing will ever read, and remote cache hit rates fall to zero without any visible failure.

This usually starts innocently. A build stamps BUILD_NUMBER into a version banner, someone adds { "env": "BUILD_NUMBER" } so the banner is "correct," and caching for that target is gone. In most cases the better fix is to stop baking the value into a cacheable artifact at all. Section 6 covers how to inject it later.

Centralized targetDefaults in nx.json cause a different problem. Declaring API_URL for every build target is tidy, but it invalidates projects that never read it, such as shared libraries and CLI tools, whenever the value changes. It also hides the opposite case: a project that genuinely depends on FEATURE_FLAGS_ENDPOINT inherits a list that doesn't mention it, and nobody notices. Put workspace-wide defaults only on variables that truly apply everywhere, and declare the rest on the projects that use them. Run nx show project <name> to see the inputs a project actually resolves to.

The rule of thumb: declare exactly the variables that change the bytes of the output, and no more.

What are the alternatives to hashing build-time configuration?

Option Cache reuse Correctness risk App changes Deployment contract
Declare env inputs One entry per distinct value combination Low if the list is complete. A missed variable silently reuses old output None Each artifact is tied to one environment
Read config at run time One artifact shared by every environment Moves to startup. Missing values fail on boot instead of at build Load config at service start or from a runtime config endpoint, and validate it on startup Artifact plus a documented set of required variables
Per-environment targets or configurations Reused within each configuration Low, because values live in versioned project config Minimal. Pipelines select the configuration Explicit: a staging build yields a staging artifact
Disable cache for the target None None from caching None Unchanged, but every run pays full cost

Env inputs and per-environment configurations both accept that the output differs by environment. They only make that difference visible to the hash. Runtime configuration removes the difference: the bytes stop depending on the variable, so there is nothing to hash. You pay for that with startup code. Validate every required value when the process boots and exit on the first missing one, so a bad deploy fails in seconds instead of serving wrong URLs.

For secrets, use runtime injection. If a secret is baked into a build, it ends up inside an artifact that a remote cache may store and share. Adding the secret to the hash also has a cost: every rotation invalidates every dependent cache entry, and the cache never prevents the leak.

Disabling the cache is the right choice only when a target is cheap or cannot be made deterministic. It fixes stale outputs by giving up reuse entirely.

How do you audit and verify Nx cache inputs to save engineering time?

Start the audit with a list of every variable that can change an artifact. Search build configs (bundler configs, project.json, custom executors, scripts) and source for build-time access, such as grep -rn "process.env" apps libs tools and the same for import.meta.env or any define-style replacement your bundler performs. Record each variable name and the target that reads it.

For each variable, decide one of three outcomes:

  • Declare it as an env input if it is inlined into output.
  • Move it to run time if the artifact should be environment-agnostic.
  • Confirm it has no effect on output. Write down why, so the next auditor does not repeat the work.

Then verify each declared variable:

  1. Run the target, change only that variable, and run it again. The second run must be a cache miss. A hit means the input is not wired up.
  2. Run the target with --skip-nx-cache and diff the fresh output directory against the cached one. Any difference points to an input you missed.
  3. If you suspect earlier entries were poisoned, run nx reset to clear the local cache before trusting results. Remote cache entries need separate handling.

Illustrative estimate (assumed numbers, not a benchmark).

The cost of the audit is roughly variables × minutes per check. Assume 15 variables at 10 minutes each, which comes to about 2.5 hours, paid once.

The cost of skipping it is incidents × (debug hours + redeploy hours). Assume one wrong-API_URL incident per quarter at 6 hours each, which comes to 24 hours a year.

The audit also lets you drop unnecessary inputs. That recovers cache hits that blanket hashing would otherwise discard.

#!/usr/bin/env bash
# Repeatable Nx cache-input audit. Assumes a project named "web"
# that builds to dist/apps/web. Adjust names and paths for your repo.
set -euo pipefail

# 1. Inventory build-time env access in source, configs, and tools.
#    Record each variable name and the target that reads it.
grep -rnE 'process\.env|import\.meta\.env' apps libs tools \
  --include='*.ts' --include='*.tsx' --include='*.js' --include='*.mjs' \
  --include='*.json' --exclude-dir=node_modules \
  | tee /tmp/env-audit.txt

# 2. Change only one declared variable between two runs.
#    The second run must NOT be served from the cache. If Nx reports
#    the task as read from cache, the variable is not a hashed input.
API_URL= npx nx build web
API_URL= npx nx build web

# 3. Compare cached output with a fresh build.
#    This run is a cache hit, so Nx restores the cached artifact.
API_URL= npx nx build web
rm -rf /tmp/web-cached && cp -r dist/apps/web /tmp/web-cached

#    Rebuild from scratch with the same inputs, bypassing the cache.
API_URL= npx nx build web --skip-nx-cache

#    Any difference means some input affects output but is not hashed.
if diff -r /tmp/web-cached dist/apps/web; then
  echo "Cached and fresh outputs match."
else
  echo "Mismatch: look for an undeclared input." >&2
fi

# 4. If earlier entries may be poisoned, clear the local cache.
#    Remote cache entries are not removed by this and need separate handling.
npx nx reset

A bash audit that lists build-time environment variable reads, checks that changing one declared variable causes a cache miss, diffs the cached output against a fresh --skip-nx-cache build, and clears the local cache with nx reset.

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 cache environment variables, 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.