How does Nx compute a task hash, and where do environment variables fit?

Before Nx runs a task, it computes a hash from everything it has been told can affect the result. If a matching hash exists in the local or remote cache, Nx restores the stored outputs and terminal log instead of running the task. The hash is built from:

  • Fileset inputs: the files matched by the target's inputs, usually the project's sources plus shared config.
  • Dependencies: hashes of upstream projects and tasks, and optionally their output files.
  • Command and options: the executor or script plus its resolved options and configuration.
  • Env inputs: named environment variables whose values are hashed.
  • Runtime inputs: the output of a command Nx runs to produce a value, such as a tool version.
  source files ─────┐
  dependency hashes ┤
  command + options ┼──► [ task hash ] ──► cache lookup
  env inputs ───────┤
  runtime inputs ───┘
 ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
  undeclared env vars (API_URL, FEATURE_X, ...)
  read by the tool, never seen by the hash

Nx does not trace what a process reads at runtime. If your bundler inlines process.env.API_URL and you have not declared it, Nx has no way to know that value matters.

Here is the consequence. A CI job builds the frontend with API_URL set to the staging endpoint, and the output is cached. A later production job sets API_URL to the production endpoint, but no source files have changed. The hash is identical, so Nx reports a cache hit and replays the staging bundle. The deploy succeeds and the app calls the wrong backend. Nothing in the log flags it, because from Nx's point of view nothing changed.

 +------------------------ Nx hash boundary ------------------------+
 |                                                                  |
 |  +-------------------+                                           |
 |  | fileset inputs    |--+                                        |
 |  | dependency hashes |--+   +-----------+    +--------------+    |
 |  | command + options |--+-->| task hash |--->| cache lookup |    |
 |  | env inputs        |--+   +-----------+    +------+-------+    |
 |  | runtime inputs    |--+                           |            |
 |  +-------------------+                              |            |
 |                                         hit  +------+------+ miss|
 |                                              |             |     |
 |                                              v             v     |
 |                                       +------------+ +----------+|
 |                                       | replay     | | run task ||
 |                                       | cached     | | (bundler)||
 |                                       | outputs    | +----^-----+|
 |                                       +------------+      |      |
 +-----------------------------------------------------------|------+
                                                             |
   undeclared env vars: API_URL, FEATURE_X, ...              |
   read by the tool at runtime ------------------------------+
   never hashed: staging and production builds share one hash

Only declared inputs feed the Nx task hash. Undeclared environment variables such as API_URL reach the bundler at runtime but stay outside the hashing boundary, so a build that differs only in API_URL can be served the cached output of an earlier build.

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

Nx does two separate things with .env files, and they don't talk to each other.

The first is loading. Before running a task, Nx reads .env files from the workspace root and the project root and merges their values into the task's process environment. It also recognizes more specific variants scoped to a target or a target-plus-configuration, so a build running under a production configuration can pick up values that a development run would not. The exact file names, which ones are supported, and which file wins when the same key appears twice have changed across Nx releases. Check the documentation for your installed version instead of relying on a list from a blog post, including this one.

The second is hashing. Nx builds the task hash from its declared inputs, and loading a file into the environment does not add it to those inputs. Nx's file-based inputs operate on the files Nx tracks in the workspace, and that set excludes anything matched by .gitignore or .nxignore. Most teams gitignore .env files to keep secrets out of version control, which makes those files invisible to the hasher. A broad glob like {projectRoot}/**/* therefore looks complete but may not include them. A root-level .env also sits outside {projectRoot} entirely, so a project-scoped glob would miss it even if it were tracked.

Don't assume your setup is covered. Change a value in each .env file you depend on, rerun the task, and confirm the hash actually changes.

Which variables belong in the build hash: build-time vs runtime configuration

Once Nx can see your .env values, decide which ones it should hash. For each variable, ask one question: does changing it change the bytes in the build output?

A bundler that replaces references to an API base URL at build time writes that URL into the JavaScript it emits. Two builds with different URLs produce different artifacts, so the variable must be part of the hash. If it isn't, Nx can restore a bundle that points at staging into a production deploy. Compiled feature flags work the same way. With dead-code elimination, flipping a flag can remove whole modules from the bundle.

A backend service that reads DATABASE_URL when the process starts is different. The compiled output is identical whatever the value is. Hashing it only causes cache misses for builds that were already correct.

Variable Read when Changes the artifact? Hash it?
Public API base URL inlined by the bundler Build Yes Yes
Compiled feature flag Build Yes Yes
NODE_ENV / build mode Build Usually yes Yes
DATABASE_URL in a backend service Process startup No No
Third-party API secret Request time No No, keep runtime-only

Per-variable env inputs pay off most for teams that:

  • ship frontend bundles
  • compile flags into code
  • switch build modes
  • share a remote cache, where one wrong hit spreads to every machine

Teams whose builds produce only server code that reads configuration at startup may need few or none.

Keep secrets runtime-only. If a secret changes the artifact, it has been embedded in that artifact. Anyone who can download the bundle or the cache entry can then read it. Fix that in the code rather than by adding the secret to the hash.

How do you declare env and runtime inputs in nx.json?

Once you know which variables shape the artifact, you list them as inputs. Each variable gets its own entry of the form { "env": "API_BASE_URL" }. Nx reads that variable's value from the process environment when it computes the hash and folds the value in. Change the value and the hash changes. Leave it out and Nx never looks at it.

Don't repeat those entries on every project. Define a named input such as buildEnv under namedInputs in nx.json, put the env entries there, and reference buildEnv in the inputs array of the build target in targetDefaults, next to your file-based inputs. Every project's build then picks up the same list. When a new build-time variable appears, there is one place to add it, and a reviewer can see the whole set in one diff instead of hunting through project.json files.

Some things that affect output are not variables at all. The Node version, the compiler version, and the target OS or architecture are common examples. For these, use { "runtime": "node --version" } or a similar command. Nx runs the command and hashes what it prints to stdout.

Because these commands run during hashing, they run on every invocation, including cache hits. Keep them fast and side-effect free. They must also be deterministic: anything that prints a timestamp, a random value, or network-dependent output will produce a new hash every run and quietly disable caching.

Input syntax and supported input types have shifted between Nx releases. Check these forms against the documentation for the version pinned in your workspace.

{
  "namedInputs": {
    "default": ["{projectRoot}/**/*"],
    "production": ["default", "!{projectRoot}/**/*.spec.ts"],
    "buildEnv": [
      { "env": "API_BASE_URL" },
      { "env": "PUBLIC_APP_REGION" },
      { "env": "FEATURE_FLAGS_PROFILE" },
      { "runtime": "node --version" },
      { "runtime": "node -p \"process.platform + '-' + process.arch\"" }
    ]
  },
  "targetDefaults": {
    "build": {
      "cache": true,
      "inputs": ["production", "^production", "buildEnv"]
    }
  }
}

An nx.json that keeps build-time env vars and cheap, deterministic runtime commands (Node version, platform-arch) in one buildEnv named input, reused by every build target through targetDefaults; check the syntax against your Nx version.

What are the alternatives to per-variable env inputs, and when should you avoid them?

Per-variable env inputs are one of four options. Each fails differently.

Approach Precision Maintenance cost Typical failure mode
Ignore .env files entirely None None Stale cache hits: a changed API base URL ships in an old bundle
Hash the whole .env file as a fileset input Coarse Low Over-invalidation: editing an unrelated key or a comment busts every dependent task
Per-variable env inputs Exact Medium: the list must track the code A newly read variable is never added, so its changes are invisible to the hash
Runtime inputs (a command's output) Exact for derived values High: the command runs on every hash calculation Non-deterministic or slow commands that are hard to diagnose

Hashing the whole file is a reasonable default for a small project. Its costs grow when one .env serves several apps. It also misses variables injected by CI, because those values never appear in the file.

When not to declare a variable

Leave out values that change on every run:

  • Timestamps
  • Build numbers
  • Commit SHAs
  • Per-developer absolute paths

Each of these gives every run a unique hash. Caching stops working without any error. If a build artifact needs a SHA, stamp it in a separate uncached step.

Also leave out runtime-only service configuration, such as database URLs or queue names that the process reads at startup. These values do not change the build output, so including them only splits the cache.

Be careful when hashing secrets with few possible values, such as a feature flag or a short token. A task hash is deterministic. If an attacker can see the hash and knows or can guess the other inputs, they can hash each candidate value and compare. That reveals the secret without ever reading it.

How do undeclared env values affect a shared remote cache?

A remote cache turns every machine that shares it into a single build system. The hash is the only thing Nx checks before replaying an artifact. If a variable affects the output but is not part of the hash, two machines with different values compute the same hash, and whichever one uploads first defines the artifact for everyone.

Here is a concrete failure. A developer has API_BASE_URL= in a local .env` file, builds the web app, and the result is uploaded. Later CI runs the same task with the production URL. It computes an identical hash, gets a remote hit, and ships a bundle that points at localhost. No step failed, and the log shows a successful cache restore. Nothing signals a problem until users report it.

Declaring the variable as an env input fixes this because its value becomes part of the hash. The developer's build and the CI build now produce different hashes and occupy separate cache entries. You get fewer cross-machine hits, which is the correct outcome. Those artifacts were never interchangeable.

This is why under-declaration is worse than over-declaration. An extra input costs you a cache miss and a slower build, and you can see and measure both. A missing input produces wrong artifacts silently.

For CI:

  • Set every declared variable explicitly in the pipeline configuration. Do not rely on whatever .env file is present in the checkout.
  • Consider not loading local .env files in CI at all. That way the values that feed the hash are visible in one place.
  • Consider allowing only CI to write to the shared cache, so artifacts built on developer machines never reach deployments.

How do you debug a stale or missing Nx cache hit caused by env vars?

Start from what Nx thinks the task depends on, not from what you think it depends on.

  1. Inspect the resolved inputs. Run nx show project <name> and find the target in question. Check that every variable the build actually reads appears as an env input, either directly or through a named input. If a variable is missing here, Nx cannot see it, and no amount of cache clearing will fix the underlying problem.

  2. Establish a baseline. Run the target once so its result is cached. Run it again with nothing changed and confirm Nx reports a cache hit. If the second run misses, something other than your variable is unstable, such as a generated file or a timestamp in an input. Fix that first.

  3. Change exactly one variable and rerun. If the variable is declared, the run should miss the cache and produce a new entry. If it hits, the declaration is absent or attached to a different target. Change only one value per round. If you change two at once, you cannot tell which one moved the hash.

  4. Revert and rerun. Restoring the original value should give a cache hit again. This confirms the hash is deterministic.

The variable list is a second source of truth, and it drifts. Code gains a new process.env read at build time, and nobody updates nx.json. Add a lint rule or code-review checklist item that flags new build-time env reads. Keeping the list accurate costs minutes per change. In return, it avoids long investigations into why staging shipped a production API URL, and cache hits stay useful because you can trust them.

#!/usr/bin/env bash
# Debug env-var cache behavior for one target, changing one thing at a time.
set -euo pipefail
PROJECT=web
TARGET=build

# 1. Inspect resolved inputs. API_URL should appear as {"env": "API_URL"},
#    either here or inside a named input listed under namedInputs.
nx show project "$PROJECT" --json | jq ".targets.$TARGET.inputs"
nx show project "$PROJECT" --json | jq '.namedInputs'

# 2. Baseline. The first run populates the cache. The second run, with
#    nothing changed, must report a cache hit. If it misses, an input
#    other than the env var is unstable. Fix that before going further.
export API_URL=
nx run "$PROJECT:$TARGET"
nx run "$PROJECT:$TARGET"   # expect: cache hit

# 3. Change exactly one variable. A declared variable produces a miss.
#    A hit here means the declaration is missing or on a different target.
export API_URL=
nx run "$PROJECT:$TARGET"   # expect: cache miss, new entry

# 4. Revert. The original value should hit the first cache entry again,
#    which shows the hash is deterministic.
export API_URL=
nx run "$PROJECT:$TARGET"   # expect: cache hit

# Drift check for code review: list build-time env reads in source so
# you can compare them against the env inputs printed in step 1.
grep -rhoE 'process\.env\.[A-Z0-9_]+' "apps/$PROJECT/src" | sort -u

A shell walkthrough that inspects a target's resolved inputs, takes a stable baseline, changes and then reverts a single env var to confirm hits and misses, and ends with a grep that lists process.env reads to compare against the declared inputs.

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