How does Nx decide whether a task is a cache hit?

Before running a target, Nx computes a hash for the task. The hash covers everything the task declares it depends on:

  • File sets resolved from the target's inputs, such as the project's source files minus specs, or shared config files at the workspace root.
  • Runtime inputs, the output of a command such as a tool's version string.
  • Environment variables listed as inputs.
  • External dependencies, the versions of third-party packages the project uses, resolved from the lockfile.
  • Upstream contributions, the hashed inputs of projects and tasks this task depends on, pulled in through ^ inputs and the task graph.
  • The task definition itself, meaning the target, its options and its configuration.
 file sets ─┐
 runtime   ─┤
 env vars  ─┼──► target inputs ─┐
 external  ─┘                   ├──► task hash ──► lookup: local cache
                                │                          remote cache
 dependency task hashes ────────┘                    hit  → restore
                                                     miss → run, store

If a stored run has the same hash, Nx does not execute the task. It replays the recorded terminal output and restores the files from the paths declared as the target's outputs. Nx assumes that identical inputs produce identical results. That assumption only holds if the inputs are complete, and it is only useful if they are not padded with irrelevant files.

The core claim of this article: most unnecessary rebuilds come from inputs that are too broad, not from a cache that is slow or unreliable. A target that hashes every file in the project rebuilds when a README or a test fixture changes. Every downstream task whose hash includes that target's inputs misses the cache too.

┌───────────────────── target inputs ──────────────────────┐
│ file sets     runtime       env vars      external       │
│ (src minus    (tool version (listed as    (lockfile      │
│ specs, root   output)       inputs)       versions)      │
│ config)                                                  │
└────────────────────────────┬─────────────────────────────┘
                             │
┌───────────────────────┐    │    ┌──────────────────────────┐
│ dependency task       │    │    │ task definition          │
│ hashes (^ inputs,     ├───►┼◄───┤ (target, options,        │
│ task graph)           │    │    │  configuration)          │
└───────────────────────┘    │    └──────────────────────────┘
                             ▼
                     ┌───────────────┐
                     │   task hash   │
                     └───────┬───────┘
                             ▼
               ┌───────────────────────────┐
               │ lookup: local cache,      │
               │ then remote cache         │
               └─────┬─────────────┬───────┘
                 hit │             │ miss
                     ▼             ▼
           ┌──────────────────┐  ┌──────────────────────┐
           │ replay terminal  │  │ run task, then store │
           │ output, restore  │  │ terminal output and  │
           │ declared outputs │  │ declared outputs     │
           └──────────────────┘  └──────────────────────┘

Nx combines a target's resolved inputs, the hashes of the tasks it depends on and the task definition into one task hash, then looks it up in the local or remote cache to either restore stored results or run and store the task.

What are nx namedInputs and why treat them as a dependency contract?

namedInputs is where you stop the rebuilds caused by unrelated files. It is a map in nx.json that gives a name to a set of inputs. A target then lists those names in its inputs array instead of repeating globs. Projects can override or extend the sets in their own configuration. Most workspaces use three conventional sets:

Named input Typical contents Purpose
sharedGlobals Root-level files such as a shared CI config or root tsconfig Changes here should invalidate every project
default Every file under {projectRoot}, plus sharedGlobals The broad set, suited to tests and lint
production default minus spec and test files, lint config, stories and docs What a shipped artifact actually depends on

The ^ prefix changes whose files are hashed. production means this project's production files. ^production means the production inputs of every project this one depends on. A build target that declares both production and ^production therefore stays valid when a library's tests change, and rebuilds when that library's source changes.

Treat these sets as a dependency contract. Each one states in a single reviewable place what an artifact is allowed to depend on. If a file is missing from the contract, the cache returns stale results. If a file is included that shouldn't be, you get needless misses. Either mistake shows up directly in a diff to nx.json.

The payoff is largest for backend and platform engineers running monorepos with deep dependency graphs and a shared or remote cache. In that setup, one overly broad input in a low-level library forces cache misses on every consumer and in every CI run.

{
  "namedInputs": {
    "sharedGlobals": [
      "{workspaceRoot}/.github/workflows/ci.yml",
      "{workspaceRoot}/tsconfig.base.json"
    ],
    "default": ["{projectRoot}/**/*", "sharedGlobals"],
    "production": [
      "default",
      "!{projectRoot}/**/?(*.)+(spec|test).[jt]s?(x)",
      "!{projectRoot}/tsconfig.spec.json",
      "!{projectRoot}/.eslintrc.json",
      "!{projectRoot}/eslint.config.mjs",
      "!{projectRoot}/**/*.stories.@(js|jsx|ts|tsx|mdx)",
      "!{projectRoot}/**/*.md"
    ]
  },
  "targetDefaults": {
    "build": {
      "dependsOn": ["^build"],
      "inputs": ["production", "^production"],
      "cache": true
    },
    "test": {
      "inputs": ["default", "^production"],
      "cache": true
    },
    "lint": {
      "inputs": ["default", "{workspaceRoot}/eslint.config.mjs"],
      "cache": true
    }
  }
}

An nx.json defining sharedGlobals, default and production named inputs, with build hashing its own and its dependencies' production files so a library's test edits don't invalidate downstream builds.

How should inputs differ for build, test and lint targets?

The fix is to give each target the inputs that match its job, instead of letting every target inherit default plus ^default.

Build: production and ^production

A build artifact depends only on shipping code, in the project itself and in every dependency. Spec files, stories and docs cannot change the output, so they should not invalidate it.

Test: default and ^production

A test run must see its own spec files, which is why it uses default. It does not need to rerun when a dependency's tests change, because those tests never execute in this project's suite. ^production captures what the tests actually import.

Lint: own sources plus lint config

Lint checks the files in one project against a rule set. It needs default plus the root and project lint config files. It needs nothing from dependencies.

The table below shows what happens to a library util and an app api that depends on it. It assumes production excludes spec files and Markdown, and that the "before" setup never declared the root lint config as an input.

Edit Misses before (default, ^default everywhere) Misses after (per-target inputs)
util spec file all six targets util:test, util:lint
util/README.md all six targets util:test, util:lint
Root lint config none (stale cache hits) every lint target
util source file all six targets util:build/test/lint, api:build/test

The new setup has fewer misses. It also catches the lint-config change that the old setup missed, which previously replayed stale passing results from the cache.

// nx.json (Nx parses this file with comments allowed)
// BEFORE: every target used ["default", "^default"], so any file
// in util (spec, README) invalidated util and api, and the root
// lint config was never an input at all.
{
  "namedInputs": {
    // Every file in the project, plus workspace-wide globals
    "default": ["{projectRoot}/**/*", "sharedGlobals"],
    // Shipping code only: drop specs and Markdown
    "production": [
      "default",
      "!{projectRoot}/**/*.spec.ts",
      "!{projectRoot}/**/*.md"
    ],
    "sharedGlobals": []
  },
  "targetDefaults": {
    "build": {
      // Own shipping code + dependencies' shipping code
      "inputs": ["production", "^production"],
      "cache": true
    },
    "test": {
      // Own specs, but only what tests import from dependencies
      "inputs": ["default", "^production"],
      "cache": true
    },
    "lint": {
      // Own files (incl. project lint config) + root lint config;
      // nothing from dependencies
      "inputs": ["default", "{workspaceRoot}/eslint.config.mjs"],
      "cache": true
    }
  }
}

The per-target nx.json targetDefaults behind the "after" column: build uses production inputs, test sees its own specs plus dependencies' production code, and lint adds the root lint config.

How do you declare non-file inputs and cache outputs correctly?

File patterns only cover part of what shapes an artifact. A bundle built with a different NODE_ENV, or compiled by a different Node or compiler version, can differ even when every source file matches. Declare these values as inputs: { "env": "API_BASE_URL" } adds a variable's value to the hash, and { "runtime": "node --version" } adds a command's output. If you leave them out, the hash cannot distinguish the two builds. With a local cache that only affects one machine. With a shared or remote cache, a CI agent can upload an artifact built against staging config, and every developer and later pipeline with the same hash will restore it. That is cache poisoning: nothing fails, but the output is wrong.

For third-party code, newer Nx versions support externalDependencies inputs. These hash only the packages a target actually uses, so a lockfile bump to an unrelated package does not invalidate it. Input types and their defaults have changed across releases, so check the inputs reference for your installed version before you depend on them.

Outputs need the same care. Use tokens such as {projectRoot}/dist, {workspaceRoot}/coverage/{projectRoot}, or {options.outputPath} so the paths match what the executor writes. Nx restores only the paths you declare. Suppose you leave out a generated API client, a coverage report, or .d.ts files emitted next to the sources. The task reports a cache hit, and the downstream step then fails because the files are missing.

Declaring too broadly causes a different problem. Every declared path is archived, uploaded and restored, which slows down hits and grows the remote cache. Declaring too few produces hits with missing files. Declare exactly the files that later steps consume.

// nx.json (Nx parses this file as JSON with comments)
{
  "namedInputs": {
    "default": ["{projectRoot}/**/*", "sharedGlobals"],
    "sharedGlobals": [],
    "production": ["default", "!{projectRoot}/**/*.spec.ts"]
  },
  "targetDefaults": {
    "build": {
      "cache": true,
      "dependsOn": ["^build"],
      "inputs": [
        "production",
        "^production",
        // Values that change the bundle without changing any source file
        { "env": "NODE_ENV" },
        { "env": "API_BASE_URL" },
        // Toolchain version: a different Node can emit different output
        { "runtime": "node --version" },
        // Hash only the packages this build uses, not the whole lockfile.
        // Check the inputs reference for your Nx version before relying on this.
        { "externalDependencies": ["vite", "typescript"] }
      ],
      // Restore everything downstream steps read, including generated code
      // and .d.ts files written outside dist
      "outputs": [
        "{options.outputPath}",
        "{projectRoot}/src/generated"
      ]
    },
    "test": {
      "cache": true,
      "inputs": ["default", "^production"],
      // Coverage lands at the workspace root, so declare it explicitly
      "outputs": ["{workspaceRoot}/coverage/{projectRoot}"]
    }
  }
}

An nx.json targetDefaults block that hashes environment variables, the Node version and selected external packages, and declares output paths for build artifacts, generated clients and coverage reports using the {projectRoot}, {workspaceRoot} and {options.outputPath} tokens.

How do you diagnose unexpected cache misses in Nx?

Treat a suspected miss as a reproducible experiment:

  1. Establish a baseline. Run the target, for example nx build api, then run it again without changing anything. The second run must be a cache hit. If it is not, something nondeterministic is in the hash, such as a generated file written during the build or an environment variable that changes between runs. Fix that first, because nothing after this step is reliable until you do.
  2. Probe with an irrelevant change. Edit a file you believe the target does not depend on, such as a spec file or a README, and rerun. A miss means that file is in the input set.
  3. Find the changed input. Open the task in nx graph and look at its hash details, which break the hash down by input. Compare them against the baseline run. Where these details appear and how much they show varies between Nx releases, so check the documentation for the version you run.

Each surprise falls into one of two categories. A miss caused by an irrelevant file is a missing exclusion: the named input needs a negated pattern for that file. A hit that should have been a miss, where the output was stale, is a missing declaration: a file, environment variable or runtime value affects the result but is not in the hash. Missing declarations are the more dangerous of the two, because they produce wrong output rather than wasted time.

Decide what goes into sharedGlobals deliberately. Anything listed there, such as tsconfig.base.json, CI pipeline files or a root .env, is part of every project's hash. One broad glob there, like the whole CI directory, invalidates every project whenever someone edits a workflow file. That cancels out all the per-project tuning you have done.

How much engineering time can narrow production inputs save?

With the global inputs kept narrow, the remaining savings depend on how often commits leave production files untouched. Illustrative estimate (assumed numbers, not a benchmark):

  • 40 projects, 200 CI runs per month (C)
  • 30% of commits touch only tests or docs (p = 0.3)
  • One changed project plus 5 dependents is rebuilt per commit (F = 6)
  • Average build of 3 minutes per project (B)

Monthly build minutes are C × F × B under default inputs. Under production inputs they are C × (1 − p) × F × B. The saving is C × p × F × B.

Inputs for build Commits causing rebuilds Affected rebuilds Build minutes
default 200 1,200 3,600
production 140 840 2,520

That is 1,080 build minutes per month. Test targets still run on those 60 commits, so this saving applies to build work only. Wall-clock savings are smaller when builds run in parallel.

Weigh that against the cost of the change. Initial setup means auditing each project's file layout and writing exclusions, which takes perhaps a day or two of work. Ongoing maintenance comes from project-level overrides that drift as people add generators, fixtures, or config files.

The largest risk is a stale artifact. If an exclusion hides a file the build actually reads, the cache serves wrong output, and finding the cause can take an engineer most of a day. If even one such incident happens per quarter, it can cancel a large share of the saved minutes. Run the formula with your own C, p, F and B before deciding.

When should you avoid narrowing inputs, and what are the alternatives?

The core risk is asymmetric. A slow build costs minutes. An over-narrowed input set costs correctness. If an exclusion glob drops a file that actually shapes the artifact, Nx reports a cache hit and replays a stale output, and nothing in the logs looks wrong. Typical culprits are a helper named *.spec-utils.ts caught by a spec pattern, a JSON config read at build time, or a generator template stored outside src.

Exclusion globs also assume naming conventions hold everywhere. Fixtures in __data__, mocks in a sibling folder, or a legacy project with its own layout each need a per-project override. Those overrides drift as the code moves, and no one notices until a miss or a stale hit appears.

Centralizing in targetDefaults has its own cost. It keeps config DRY, but someone reading one project.json can't see what invalidates its build.

Narrow inputs when conventions are consistent and enforced, and rebuilds are expensive. Avoid narrowing in small repos, where the savings are minor, or in repos with irregular layouts.

Approach Risk of stale artifacts Rebuild cost Maintenance effort
Default inputs Low High Low
Affected-only runs Low Medium Low
Disable caching for risky targets None for those targets High for those targets Low
Narrow production inputs globally Medium Low Medium
Per-project overrides Medium, rises with drift Low High

Input syntax and supported input types have changed across Nx releases, so check your configuration against the documentation for the Nx version you run.

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 namedInputs, 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.