How does Nx compute a task hash?

Before running a task, Nx computes a hash from everything the task declares it depends on. If that hash matches a stored entry, Nx replays the cached terminal output and restores the recorded output files without running the command. Nx cache inputs are how you tell Nx what goes into that hash.

The hash combines four groups of values:

  • The target's own inputs. These are file sets from the project, the output of runtime commands, and the values of environment variables.
  • Dependency inputs. These are hashes of the inputs of projects this one depends on in the project graph.
  • The task definition. This is the executor or command and its resolved options.
  • Relevant workspace configuration. This covers settings and external dependency versions that can change how the task behaves.
 project filesets ─┐
 runtime values ───┤
 env variables ────┼──► target inputs ─┐
                   │                   │
 dependency project inputs ────────────┼──► task hash ──► cache lookup
 command + options ────────────────────┤
 workspace config ─────────────────────┘

A cache hit requires every component to match. A single changed byte in any declared file produces a new hash. So does a different flag value or a changed environment variable.

Treat inputs as a contract: "this output is a function of exactly these things." The contract can be wrong in two directions:

  • Too broad. If inputs include files that don't affect the output, such as a README or unrelated test fixtures, unrelated changes cause cache misses. You lose speed, but the results are still correct.
  • Too narrow. If a real dependency is missing, Nx returns a stale artifact as if it were current. A build that reads an undeclared config file or environment variable will produce a cache hit that ships the wrong output, and nothing reports an error.

The second failure is worse. A cache miss only costs time. A false hit gives you wrong results that look correct.

+--------------------------+
| TARGET INPUTS            |
|  project filesets        |---+
|  runtime command output  |   |
|  environment variables   |   |
+--------------------------+   |
                               |
+--------------------------+   |
| DEPENDENCY INPUTS        |   |
|  hashes of inputs of     |---+
|  upstream projects       |   |
+--------------------------+   |     +-------------+     +--------------+
                               +---->|  TASK HASH  |---->| CACHE LOOKUP |
+--------------------------+   |     +-------------+     +--------------+
| TASK DEFINITION          |   |                          |          |
|  executor or command     |---+                       match?     no match
|  resolved options        |   |                          |          |
+--------------------------+   |                          v          v
                               |                     +--------+ +---------+
+--------------------------+   |                     | replay | | run the |
| WORKSPACE CONFIG         |   |                     | output,| | task,   |
|  relevant settings       |---+                     | restore| | store   |
|  external dep versions   |                         | files  | | result  |
+--------------------------+                         +--------+ +---------+

Nx folds target inputs, dependency project input hashes, the task definition and relevant workspace configuration into one task hash; a cache hit requires every component to match.

What are the types of input entries, and when should you use each?

Nx accepts five kinds of input entry. Each one answers a different question about what can change a task's result. A target's inputs array is usually a mix of them.

Entry type What it captures Typical backend use case Main risk
Fileset glob ({projectRoot}/..., {workspaceRoot}/...) Contents of matching files Service source, migrations, OpenAPI specs {workspaceRoot} globs that are too wide invalidate every project on unrelated edits
Negated glob (!{projectRoot}/...) Removes files from an earlier match Excluding *.spec.ts and fixtures from a build Excluding a file the task actually reads causes a false hit
runtime Output of a shell command node --version, a compiler or protoc version Commands with machine-specific output, such as hostnames or full kernel strings, prevent sharing the cache across agents
env Value of one environment variable A build-time API_BASE_URL or feature flag inlined into a bundle Easy to forget, and a missing entry gives false hits
externalDependencies Resolved versions of named npm packages Pinning a codegen tool such as prisma or typescript Listing too few packages means a tool upgrade fails to invalidate the cache

The {projectRoot} and {workspaceRoot} tokens anchor every glob to a known root. Without them, the same pattern would match different files depending on where the task runs. Negations only remove files that an earlier pattern matched, so put each one after the glob it trims.

The snippet below combines these types for a typical service build:

  • Source files under the project root, with test files excluded.
  • A runtime entry for the Node version.
  • An env entry for a variable that ends up in the output.
  • externalDependencies pinning the code generator.

Every entry in it names something that changes the build artifact. Anything that doesn't affect the artifact stays out.

{
  "name": "orders-service",
  "targets": {
    "build": {
      "inputs": [
        "{projectRoot}/**/*",
        "!{projectRoot}/**/*.spec.ts",
        "!{projectRoot}/src/test-fixtures/**/*",
        "{workspaceRoot}/openapi/orders.yaml",
        { "runtime": "node --version" },
        { "env": "API_BASE_URL" },
        { "externalDependencies": ["prisma", "typescript"] }
      ]
    }
  }
}

A project.json build target that hashes project files and excludes specs and fixtures. It adds one anchored workspace spec file, the Node version, a build-time env var and the resolved prisma and typescript versions.

What are Nx named inputs and why use them?

A named input is a labeled list of input entries, defined under namedInputs in nx.json, that targets reference by name instead of repeating the entries. The label stands for the set: when a target declares production as an input, Nx expands it into the globs, env entries and runtime entries behind that name before hashing.

Three labels are conventional. sharedGlobals holds workspace-level files that affect every project, such as a root TypeScript base config. default usually means "every file in {projectRoot}" plus sharedGlobals. production starts from default and subtracts what never reaches an artifact: spec files, test configs, lint configs, stories. Named inputs can include other named inputs by name. production listing default and then adding negation patterns is the standard example. Each layer states one idea, so you can understand the chain without expanding every glob by hand.

Targets use these names in their inputs array. A bare name like production applies to the project's own files. A caret-prefixed name like ^production applies the same definition to the project's dependencies.

A project can define a named input with the same name in its own configuration, and that definition overrides the workspace one for that project. A package with an unusual layout can then fix its own production definition, and every target that references the name picks up the change.

Large monorepos benefit most. Platform engineers can change what counts as production source in one place instead of across dozens of target definitions. Backend teams running build and package pipelines get a contract a reviewer can read as words: "build depends on production inputs here and in dependencies." When thirty targets each carry their own copy of a glob list, the copies drift apart, and cache invalidation becomes inconsistent and hard to reason about.

{
  "namedInputs": {
    "sharedGlobals": ["{workspaceRoot}/tsconfig.base.json"],
    "default": ["{projectRoot}/**/*", "sharedGlobals"],
    "production": [
      "default",
      "!{projectRoot}/**/?(*.)+(spec|test).[jt]s?(x)",
      "!{projectRoot}/tsconfig.spec.json",
      "!{projectRoot}/jest.config.[jt]s",
      "!{projectRoot}/eslint.config.mjs",
      "!{projectRoot}/**/*.stories.[jt]s?(x)"
    ]
  },
  "targetDefaults": {
    "build": {
      "dependsOn": ["^build"],
      "inputs": ["production", "^production"],
      "cache": true
    },
    "test": {
      "inputs": ["default", "^production", "{workspaceRoot}/jest.preset.js"],
      "cache": true
    },
    "lint": {
      "inputs": ["default", "{workspaceRoot}/eslint.config.mjs"],
      "cache": true
    }
  }
}

An nx.json where sharedGlobals feeds default, production composes default and subtracts spec, test, lint and story files, and each target states its cache inputs by name, with ^production applying the same definition to dependencies.

How do named inputs work when Nx hashes a task?

Named inputs are resolved at hash time. They are a naming layer over the input entries described above, not a separate caching mechanism. For each task, Nx works through these steps:

  1. Find the target's inputs. Nx takes the inputs array from the project's target configuration if it has one. Otherwise it uses the matching entry in targetDefaults. A project-level array replaces the default rather than merging with it.
  2. Expand names. Each string that matches a named input is replaced by that input's entries. Nx looks for the name in the project's own namedInputs first, then in nx.json. Expansion is recursive, so production pulls in default, which pulls in sharedGlobals.
  3. Apply dependency inputs. For each ^name entry, Nx walks the project graph and expands name in the context of every project the current project depends on. Each upstream project uses its own definition of name, including any project-level override.
  4. Evaluate filesets. Positive globs collect files and negated globs remove files from that collection. {projectRoot} and {workspaceRoot} are substituted for the project being evaluated. Nx then hashes the contents of the files that remain.
  5. Evaluate non-file entries. runtime commands are executed and their output is hashed. env entries contribute the variable's value. externalDependencies contribute resolved package versions.
  6. Combine. These hashes are combined with the task definition and relevant workspace configuration into the final task hash. That hash is used to look up the local cache and, if one is configured, the remote cache.

Because expansion happens per project, one name can resolve to different file sets in different projects. nx show project <name> shows the resolved result for a specific project. It is the most direct way to confirm what a name actually means there.

Who should use named inputs?

Named inputs are worth setting up in any Nx workspace that has caching enabled and more than a handful of projects. They pay off most for these groups:

  • Platform and developer-experience engineers who own nx.json. They can define default, production and sharedGlobals once and change cache behavior for the whole workspace from one file.
  • Backend teams with build, typecheck and package pipelines. Their artifacts depend on source, generated code, environment variables and toolchain versions. Those dependencies need to be stated explicitly, so that test-only changes don't trigger rebuilds and environment changes always do.
  • Teams sharing a remote cache between CI and developer machines. Consistent named inputs across projects make hashes predictable. A developer who checks out a commit CI has already built can then get hits instead of rebuilding.
  • Maintainers of libraries deep in the project graph. Through ^production, their definition of production files affects the hash of every downstream project. A correct definition at the bottom of the graph protects everything above it.

A small workspace with two or three projects and short build times gets less out of them. Inline inputs arrays may be easier to read there. Even in that case, a production input that excludes tests is cheap to add and keeps the configuration consistent as the repository grows.

How do you design a production named input?

Start from default, which in a typical setup covers every file under {projectRoot} plus sharedGlobals. That is the "before" state: a build target keyed on default re-runs whenever anything in the project changes, including a single assertion in a spec file.

The "after" state defines production as default followed by negated globs. Exclude spec and test files (!{projectRoot}/**/*.spec.ts), test setup files such as test-setup.ts, the test runner config, lint config like .eslintrc.json, Storybook stories, and the .storybook directory. Each exclusion is safe to make because none of those files can change the compiled artifact. Then point build, typecheck and package at production and ^production. When a commit touches only a test, those three hashes stay the same and are restored from cache. Only test and lint run.

Illustrative estimate. Assume 40 test-only pull requests per week, and assume build, typecheck and package together take 6 minutes of runner time on the affected projects. Narrowing the input saves about 240 runner-minutes per week, which is 4 hours. Engineers also wait less for each of those checks to report back. These numbers are assumptions, not measurements. Plug in your own.

Exclude only files you can name and are sure never ship. If you are unsure about a file, such as a JSON fixture imported at runtime, a .d.ts file, or an asset read by the bundler, keep it in the input. An extra input costs you an occasional cache miss. A missing one lets Nx restore a stale artifact with no error, and that artifact can reach production.

{
  "namedInputs": {
    "sharedGlobals": [],
    "default": ["{projectRoot}/**/*", "sharedGlobals"],
    "production": [
      "default",
      "!{projectRoot}/**/?(*.)+(spec|test).[jt]s?(x)?(.snap)",
      "!{projectRoot}/tsconfig.spec.json",
      "!{projectRoot}/src/test-setup.[jt]s",
      "!{projectRoot}/jest.config.[jt]s",
      "!{projectRoot}/.eslintrc.json",
      "!{projectRoot}/eslint.config.[cm]?js",
      "!{projectRoot}/**/*.stories.@(js|jsx|ts|tsx|mdx)",
      "!{projectRoot}/.storybook/**/*"
    ]
  },
  "targetDefaults": {
    "build": {
      "inputs": ["production", "^production"],
      "cache": true
    },
    "typecheck": {
      "inputs": ["production", "^production"],
      "cache": true
    },
    "package": {
      "inputs": ["production", "^production"],
      "cache": true
    },
    "test": {
      "inputs": ["default", "^production"],
      "cache": true
    },
    "lint": {
      "inputs": ["default", "{workspaceRoot}/.eslintrc.json"],
      "cache": true
    }
  }
}

An nx.json that defines production as default minus test, lint and Storybook files, so build, typecheck and package keep cache hits when only a test changes.

How can named inputs save engineering time?

Time savings come from several places, and only some of them show up as CI minutes:

  • Fewer unnecessary reruns. Tasks keyed on production skip work when a change cannot affect their output. Test edits, lint config changes and stories no longer rebuild artifacts.
  • Fewer reruns up the graph. ^production stops a test-only change in a low-level library from invalidating the builds of every project that depends on it. In a deep graph, this cascade often costs more than the change to the library itself.
  • Shorter feedback loops. When cached targets are restored instead of rerun, a pull request's checks finish sooner. Engineers spend less time waiting or switching tasks while CI runs.
  • More hits from a shared remote cache. Consistent, machine-independent inputs mean a commit built once in CI can be restored on developer machines and other agents instead of being rebuilt.
  • Less configuration upkeep. Changing what counts as production source is a one-line edit in nx.json, not a search through every project.json. Reviewers read a name instead of comparing glob lists.
  • Less time debugging stale artifacts. Declaring env, runtime and externalDependencies explicitly heads off false cache hits. These are among the most expensive cache failures to track down, because nothing reports an error.

Illustrative estimate. Assume a library sits beneath 15 projects. Assume 10 test-only changes land in it per week, and assume each downstream build takes 3 minutes. If downstream builds use ^default, each of those changes reruns all 15 builds: 10 × 15 × 3 = 450 runner-minutes per week. With ^production, those builds are restored from cache. All of these inputs are assumptions chosen to show the arithmetic, not measurements. Use your own project graph and task durations.

The savings only hold if the inputs are correct. One false hit that ships a stale artifact can cost more engineering time than many weeks of saved reruns. Keep that in mind when deciding how aggressively to narrow an input.

When should a target use ^production versus broader dependency inputs?

The ^ prefix tells Nx to hash the named input of every project the target's project depends on, rather than the project's own files. ^production means "my dependencies' production files." For a build target that is usually right: a bundle depends on upstream source, not on upstream specs, stories, or lint config.

test can need more. If your tests import fixtures, mocks, or test utilities exported from a library's spec helpers, those files fall outside production. They need ^default or a dedicated named input.

This goes wrong in two directions. If build uses ^default, editing one spec file in a low-level library invalidates the build of every project above it, and the cache stops paying for itself. If test uses ^production while relying on an upstream test helper, a real change to that helper produces a cache hit and a stale pass.

^production also assumes every upstream library defines production correctly. One library that excludes too much, such as a glob that drops a generated file, silently weakens the hash of every project that depends on it.

targetDefaults in nx.json lets you set build, test, and lint inputs once for the workspace. A project that declares its own inputs for a target replaces the default array instead of adding to it. You have to restate anything you still want.

That is the trade-off of centralizing. Reading a project's config no longer shows where its inputs come from. Overrides added for a one-off fix can drift from the defaults without anyone noticing. Run nx show project <name> periodically to see the resolved configuration.

When should you avoid broad sharedGlobals, env and runtime inputs?

Every file in sharedGlobals invalidates every task that consumes it, and that includes entries in the remote cache. Treat each one as a decision about how often you are willing to rebuild the whole workspace.

A base tsconfig belongs there if path aliases or compiler options affect emitted output. The root lockfile usually does not. Nx already hashes each project's external dependencies from the project graph, so listing the whole lockfile means bumping a test library rebuilds a service that never imports it. CI pipeline files almost never change build output. Adding them means every pipeline edit costs a full cold run. Tooling config such as a root lint or formatter file should be an input only to the targets that read it, not a global one.

Backend builds that bake in a target environment, a feature-flag set or a toolchain version have the opposite problem. If those values aren't hashed, a staging artifact can be restored for a production build. Declare them with env and runtime inputs. The tradeoff is that a runtime command whose output differs per machine (OS, architecture, patch version) splits the remote cache into separate pools, and developers stop getting hits from CI. Pin toolchains so the command output is identical across machines.

Approach Hit rate Correctness risk Cost
Broad default inputs Low Low Frequent rebuilds after unrelated edits
Narrow production set High Moderate if a real input is missed Ongoing review of input lists
File added to sharedGlobals Drops workspace-wide on each change Low Full cache flush per edit
env/runtime inputs Lower, cache split per value Lowest for environment-specific builds Remote cache splits into pools if values vary by machine

How do you debug cache misses and verify inputs and outputs?

Start with nx show project <name>. It prints the resolved configuration for each target after defaults and named inputs have been expanded, so you see the actual file sets and dependency inputs rather than what you think nx.json says. Next, compare the hash details Nx records for two runs of the same task. These list the individual components that fed the hash, including file hashes, runtime values and environment variables, so a miss can be traced to one entry. Make it a rule to explain every unexpected hit or miss before you edit configuration. A change made without a diagnosis tends to hide the real cause.

Hidden dependencies

Globs only describe files that Nx can see as a fixed pattern. Some dependencies fall outside that:

  • Generated code. Clients or types produced by an earlier step may be missing from the inputs, or may be gitignored and never hashed.
  • Computed paths. A build script that builds a path from variables can read files no glob matches.
  • Implicit parent configs. Compilers, linters and test runners often walk up the directory tree for configuration files.

Static review cannot prove these are covered. Test each one: change the suspected file, rerun the task, and confirm the result is a miss.

Outputs

Outputs are the other half of the contract. If a task writes files outside its declared output paths, a cache hit restores only part of the result. The task reports success, and a later step fails on files that are missing.

Plan input changes

Any change to a target's inputs changes its hash. That invalidates its existing entries in both the local and remote caches, a one-time flush. Group input edits into one deliberate change instead of making them one at a time.

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 named inputs, 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.