Who should use explicit env and runtime inputs?

Any team that runs cached Nx targets whose output depends on something other than source files should declare env and runtime inputs. The need is greatest in these cases:

  • Build and release owners. Engineers who maintain build, bundle, container image or codegen targets, where a value read at build time is compiled into the artifact.
  • Teams using a shared or remote cache. Once artifacts move between laptops, CI agents and branches, one wrong cache entry spreads to every consumer that computes the same hash.
  • Workspaces with environment-specific builds. If the same target produces staging, preview and production artifacts that differ only by environment variables, those variables must be part of the hash.
  • Projects that ship native or toolchain-sensitive output. Targets that compile with Rust, Go or native Node add-ons depend on the compiler version and the OS and architecture. Runtime inputs capture those dependencies.

If every cached target in a workspace reads only files that are already covered by namedInputs, you have nothing to add. You still need the audit described later to confirm that this is true.

How does Nx build a task hash, and what does it ignore?

Before running a task, Nx computes a hash from everything the task has declared it depends on. If that hash matches a previous run, Nx assumes the result would be identical and skips execution. The hash is only as good as the list of inputs behind it.

What goes into the hash

A task hash combines several sources:

  • File sets. The files matched by the target's inputs, usually expressed through namedInputs such as default or production. Nx hashes file contents, not timestamps.
  • Dependency inputs. Entries prefixed with ^ (for example ^production) pull in the corresponding inputs of every project this one depends on in the project graph. A change in a library therefore invalidates the apps that consume it.
  • External dependencies. The resolved versions of third-party packages the project uses, taken from the lockfile, so a dependency bump changes the hash.
  • Env and runtime entries. env inputs hash the value of a named environment variable. runtime inputs run a command and hash its output, for example a tool version.
  • Task configuration. The target's executor or command, its options, and the selected configuration. Changing a flag produces a different hash even if no files changed.

What happens on a match

On a cache hit, Nx replays the stored terminal output and restores the files listed in the target's outputs. Nothing else is restored. The process exits as if the task had run.

The core rule

Anything not declared is invisible to the hash. Nx does not inspect what your build actually reads. If a script reads API_BASE_URL, a config file outside the declared file set, or the output of a command that isn't a runtime input, Nx has no way to know about it. When that value changes, the hash stays the same, and Nx serves an artifact built from the old value.

  DECLARED INPUTS (hashed)               NOT DECLARED (invisible)
+------------------------------+       +------------------------------+
| File sets via namedInputs    |       | env var read by a script     |
|   (file contents, not mtime) |       |   e.g. API_BASE_URL          |
| ^ dependency inputs          |       | config file outside the      |
|   e.g. ^production           |       |   declared file set          |
| External deps (lockfile)     |       | command output that is not   |
| env: named variable values   |       |   a runtime input            |
| runtime: command output      |       +------------------------------+
| Task config: executor or     |                      |
|   command, options, config   |                      x  never reaches hash
+------------------------------+
               |
               v
      +-----------------+
      |    Task hash    |
      +-----------------+
               |
               v
      +-----------------+   no    +----------------------------+
      | Hash in cache?  |-------->| Run task, store terminal   |
      +-----------------+         | output and declared outputs|
               | yes              +----------------------------+
               v
+------------------------------------+
| Cache hit: skip execution          |
|  - replay stored terminal output   |
|  - restore files listed in outputs |
|  - nothing else is restored        |
+------------------------------------+

Nx builds the task hash only from declared file sets, ^ dependency inputs, external dependencies, env and runtime entries, and task configuration. Anything a task reads without declaring it never reaches the hash, so changes to it can still produce a cache hit.

How does it work in practice when an env input is declared?

Here is what happens when a build target declares { "env": "API_URL" } in its inputs:

  1. Resolve inputs. Nx expands the target's inputs, including named inputs and ^ entries, into a concrete list of file sets, env names and runtime commands.
  2. Read values. For each env entry, Nx reads the variable's current value from the process environment that invoked Nx. For each runtime entry, Nx runs the command and captures its output.
  3. Combine into a hash. Nx combines those values with the file content hashes, external dependency versions and task configuration into a single task hash.
  4. Look up the cache. Nx checks the local cache, and the remote cache if one is configured. A build with API_URL set to staging and a build with API_URL set to production now produce different hashes, so each gets its own cache entry.
  5. Run or restore. On a miss, the task runs and Nx stores its terminal output and declared outputs under the new hash. On a hit, Nx restores them.

The mechanism does not change when you add an env input. You only widen what Nx considers part of the task's identity. The cache becomes correct when that identity covers every value that changes the output.

Why do undeclared environment variables cause stale cache hits?

Consider a frontend app whose bundler replaces process.env.API_URL with a string literal at build time. A developer runs the build with API_URL pointing at staging. Nx hashes the source files, config and dependency graph, runs the bundler, and stores the output under that hash. Later, the release pipeline runs the same target with API_URL set to production. Nothing in the hash changed, so Nx restores the cached output and reports success. The artifact still contains the staging URL. No error is raised, because from Nx's point of view the task did not change.

The same failure applies to anything that turns an environment value into build output. Feature flags read at build time decide which code paths survive tree-shaking. NODE_ENV-style switches change minification, source maps and which dependency builds get bundled. Codegen steps that read a schema location or service URL from the environment produce different clients for different values. In every case, the output depends on a value the hash does not include.

A remote or shared cache makes this worse. One bad entry can be restored on every machine and branch that computes the same hash. If a laptop with a local .env populates the shared cache, CI can restore that build. If CI writes artifacts built with pipeline secrets or release flags, developers can pull them into local runs.

Engineers who own build and release targets should treat this as a correctness bug rather than a performance setting. A stale cache hit does not fail the build. It ships the wrong artifact.

How do you declare env and runtime inputs in namedInputs and target inputs?

Nx accepts two non-file input forms alongside file globs. { "env": "API_BASE_URL" } hashes the current value of that variable. { "runtime": "node --version" } runs the command and hashes its output. Both are valid inside namedInputs in nx.json and inside any target's inputs array.

Workspace-wide variables

A variable that affects every build, such as NODE_ENV or a registry mirror that changes resolved packages, belongs in a shared named input. The usual convention is a sharedGlobals entry that default includes. Putting it there means every target that consumes default picks it up. You do not have to remember to add it to each new target.

Target-specific variables

Variables that affect only some targets, such as SENTRY_RELEASE for build or DATABASE_URL for e2e, go in targetDefaults under that target name. Use a project's own target inputs only when one project differs from the rest. A project-level inputs array generally replaces the targetDefaults value rather than extending it. Repeat default or production there, or you will silently drop file inputs.

Runtime inputs

Nx runs runtime commands every time it computes a hash, so a command must be fast and deterministic. Good candidates are toolchain versions (go version, rustc --version) and uname -sm for targets that produce native binaries. A command whose output contains a timestamp or a random ID will cause a cache miss on every run. A command that hits the network will slow down every task.

.env files

Declare {projectRoot}/.env and {projectRoot}/.env.production as explicit file inputs. Nx's automatic loading and hashing of .env files has changed across releases, so check how your installed version behaves before you rely on it.

{
  "namedInputs": {
    "sharedGlobals": [
      { "env": "NODE_ENV" },
      { "env": "NPM_REGISTRY_MIRROR" },
      { "runtime": "node --version" }
    ],
    "default": ["{projectRoot}/**/*", "sharedGlobals"],
    "production": ["default", "!{projectRoot}/**/*.spec.ts"]
  },
  "targetDefaults": {
    "build": {
      "cache": true,
      "inputs": [
        "production",
        "^production",
        { "env": "SENTRY_RELEASE" },
        "{projectRoot}/.env",
        "{projectRoot}/.env.production"
      ]
    },
    "build-native": {
      "cache": true,
      "inputs": [
        "production",
        { "runtime": "rustc --version" },
        { "runtime": "uname -sm" }
      ]
    },
    "e2e": {
      "inputs": ["default", "^production", { "env": "DATABASE_URL" }]
    }
  }
}

An nx.json that puts workspace-wide env and runtime inputs in sharedGlobals, which default includes, and declares target-specific variables, toolchain and OS/arch commands, and .env files as explicit inputs in targetDefaults.

How do namedInputs compose across default, production and dependencies?

Most workspaces define two named inputs and build on them. default usually covers every file in the project plus a sharedGlobals entry for workspace-wide files such as root config. production starts from default and subtracts with negated globs like !{projectRoot}/**/*.spec.ts or !{projectRoot}/**/*.md, so editing a test or README does not invalidate a build. Custom named inputs follow the same pattern. A deploy input, for example, could add a few runtime inputs on top of production.

The ^ prefix changes whose files an input refers to. "inputs": ["production", "^production"] on a build target means "this project's production files, plus the production files of every project it depends on." A library's production set therefore flows into the hash of each app that imports it, while the library's tests stay out.

That propagation decides where an env input should go:

  • In sharedGlobals: the variable reaches every task in the workspace, including lint and test runs that never read it.
  • In a library's production: it reaches that library's build and, through ^production, every downstream build. This is usually right for a variable the library inlines at build time.
  • Only in a target's inputs: it stays in that single target, because ^production resolves named inputs, not target inputs.
Approach Precision Maintenance cost Easy to forget?
Broad shared input (sharedGlobals) Low: busts unrelated caches One place to edit Rarely, since it is applied everywhere
Per-target or per-project scoping High: only affected tasks rerun Repeated across projects Often: new targets and projects miss it
// nx.json: workspace-wide named inputs and the default build wiring
{
  "namedInputs": {
    "sharedGlobals": ["{workspaceRoot}/tsconfig.base.json"],
    "default": ["{projectRoot}/**/*", "sharedGlobals"],
    "production": [
      "default",
      "!{projectRoot}/**/*.spec.ts",
      "!{projectRoot}/**/*.md"
    ]
  },
  "targetDefaults": {
    // This project's shipped files plus the shipped files of its dependencies
    "build": { "inputs": ["production", "^production"], "dependsOn": ["^build"], "cache": true }
  }
}

// libs/api-client/project.json: this library inlines PUBLIC_API_URL at build time.
// A project-level named input replaces the workspace one of the same name,
// so the negated globs are restated here.
{
  "name": "api-client",
  "namedInputs": {
    "production": [
      "default",
      "!{projectRoot}/**/*.spec.ts",
      "!{projectRoot}/**/*.md",
      { "env": "PUBLIC_API_URL" }
    ]
  },
  "targets": {
    "e2e": {
      // Target-level env input: only this target's hash changes.
      // ^production in dependents does not see it.
      "inputs": ["default", { "env": "E2E_BASE_URL" }]
    }
  }
}

Shows PUBLIC_API_URL placed in a library's production named input, so it reaches that library's build and every dependent build through ^production. E2E_BASE_URL is set only in the e2e target's inputs, so dependents never see it.

How do you audit an existing Nx workspace for missing env inputs?

An audit works best as three passes: find every read, attribute it to a target, then compare against what Nx actually hashes.

1. Find the reads

Search application source, build tooling and config files for process.env, import.meta.env and any helper that wraps them. Then search the commands in project.json targets and package.json scripts for shell expansions such as $VAR or ${VAR}. Executor commands are easy to overlook because they live in configuration rather than code, yet they shape the output just as directly.

2. Map each read to a target

For each hit, record which target consumes it and whether it changes that target's output. A variable baked into a bundle or used to select a build mode affects output and must be an input. A variable that only controls log verbosity or a registry token usually does not. Write the decision down so the next reviewer does not repeat the analysis.

3. Confirm what Nx resolves

Run nx show project <name>, or open the project details view from nx graph, to see the inputs each target actually resolves to after namedInputs, target defaults and plugin-inferred configuration are merged. Compare that list against your map. Any output-affecting variable that is missing is a stale-cache risk.

Limits of grepping

Static search misses indirect reads. Frameworks often inject every variable with a given prefix without any explicit reference in your code. Config files that read the environment at load time, .env loaders, and transitive tooling can also pull in values that a grep never finds. Read the documentation for each build tool in the pipeline.

Plugin-inferred inputs and other defaults can change between Nx releases. Check the resolved output for your installed version rather than relying on remembered behaviour.

#!/usr/bin/env bash
set -euo pipefail

PROJECT="web-app"   # placeholder project name
EXCLUDES=(--exclude-dir=node_modules --exclude-dir=dist --exclude-dir=.nx)

echo "== Env reads in source, tooling and config files =="
grep -rnE "process\.env|import\.meta\.env" "${EXCLUDES[@]}" \
  --include='*.ts' --include='*.tsx' --include='*.js' \
  --include='*.mjs' --include='*.cjs' . || true

echo "== Shell variable expansions in target commands and scripts =="
grep -rnE '\$\{?[A-Za-z_][A-Za-z0-9_]*' "${EXCLUDES[@]}" \
  --include='project.json' --include='package.json' . || true

echo "== Inputs Nx resolves for ${PROJECT}:build =="
npx nx show project "${PROJECT}" --json | jq '.targets.build.inputs'

A repeatable audit script that greps for direct and shell-level environment reads, then prints the inputs Nx resolves for a target so the two lists can be compared for missing env entries.

How can you verify cache correctness in CI?

Verification is a differential test. Run the target once to populate the cache, then change only the variable you declared and run it again. Nx should report a cache miss and execute the task. Restore that value, change a variable the target is not meant to depend on, and run a third time. That run should be a cache hit. The first comparison proves the input is wired in. The second proves you have not pulled in noise.

Both directions need a test because neither failure is loud. If you under-declare, Nx returns a wrong artifact from cache, and the build log looks normal. If you over-declare, you get a miss on every run. Builds stay correct but slow, and nobody notices until someone questions CI spend.

Scripting it for high-value targets

Run the full check only on targets where a stale output is expensive, such as release bundles, container images and generated clients. Run it on a schedule or when nx.json or project configuration changes. The script sets each variable explicitly and runs the target three times against a clean local cache. It then asserts hit or miss from the Nx task output and fails the job if any expectation is wrong.

Illustrative estimate

These are assumed inputs, not measured results.

  • CI time: a 6-minute target runs 40 times a day. Raising its hit rate from 50% to 80% saves about 72 CI minutes a day.
  • Engineering time: a stale release artifact that reaches users is assumed to cost two engineers half a day each to diagnose, plus a hotfix release. That is roughly one engineer-day per incident, compared with a few minutes of extra CI per scheduled check.

How can correct inputs save engineering time?

Accurate inputs save time in two places. The cache can be trusted, so engineers stop working around it, and it stays effective, so they wait on fewer rebuilds.

  • Less debugging of phantom bugs. A stale hit looks like a code problem: the wrong API endpoint, a missing feature flag, a client generated from an old schema. Engineers can spend a long time reading correct source code before anyone suspects the cache. When the inputs are declared, a changed value always produces a fresh build, and this class of investigation goes away.
  • No defensive cache bypassing. After one stale hit, teams often add --skip-nx-cache to release jobs or clear the cache with nx reset "just in case". Both remove the benefit of caching for every later run. With correct inputs, the cache can stay on in the pipelines that matter most.
  • Higher hit rates from precise scoping. If you scope a variable to the targets that read it, instead of putting everything in sharedGlobals, unrelated tasks such as lint and unit tests keep hitting the cache when that variable changes. Local feedback loops get shorter, and CI queues get shorter too.
  • Safe sharing of a remote cache. When hashes reflect every output-affecting value, developers can reuse CI-built artifacts, and CI can reuse each other's artifacts across branches. Nobody has to wonder whether an entry came from a different environment.
  • Cheaper reviews of build changes. The audit map and the differential CI check record why each input exists. A reviewer looking at a new variable can see where it belongs without having to rediscover how the build works.

Illustrative estimate, using assumed inputs only: suppose a team bypasses the cache on a 10-minute release build that runs 15 times a day, out of distrust, and correct inputs let half of those runs hit the cache. That saves about 75 minutes of pipeline wait per day. Over a week, that is time engineers no longer spend waiting on release jobs or rerunning them to be sure. Use your own CI timings in the same calculation before you draw conclusions for your workspace.

When should you avoid hashing a variable, and what are the alternatives?

Hashing more variables is not automatically safer. A variable that changes on every run turns the hash into a per-run value, so every task misses and the cache stops doing anything. Build IDs, timestamps and commit SHAs belong in the hash only when the output actually embeds them, for example a version string compiled into a bundle. If a value only appears in logs or deployment metadata, leave it out.

Secrets follow the same test. Hash an API key only if changing it changes the artifact. The values are digested, so recovering one from a hash would take brute force. The variable names and their role are still visible in project configuration and in a task's hash details, so declaring a secret as an input tells anyone who can read those details that the build depends on it.

Runtime inputs need deterministic commands. A command that prints a locale-formatted date, the current time, or output with inconsistent trailing whitespace produces a different hash on every machine or every run. Normalise the output, for example by fixing the locale and trimming whitespace, or don't use the command as an input.

Situation Approach Cost
Per-run value embedded in output Split it into a separate, uncached stamping step after the cached build One extra step that runs every time
Env dependencies cannot be enumerated Set cache: false on the target Full rebuild every run
Value affects only metadata Exclude it from inputs None

Disabling the cache is a valid choice when you make it deliberately. It gives up speed to guarantee correctness for that target. It should not be a reflex after one stale hit, because the stale hit usually means an input was not declared, and fixing that declaration keeps the cache working.

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