What are Nx namedInputs and how does Nx compute a task hash?
Nx skips a task only when it can prove the result would be identical to one it has already stored. That proof is a hash. Before running a target, Nx gathers everything the target declares as an input, hashes each piece, and combines them into a single cache key. Inputs can be file sets (globs relative to the workspace or project root), runtime values (the output of a shell command), environment variables, and external dependencies (the resolved versions of installed packages). Nx also folds in the task's own configuration and the relevant input hashes of the projects it depends on. If any piece changes, the key changes and the task runs. If nothing changes, Nx replays the cached output.
inputs and namedInputs are related but separate. inputs is a property on a target. It says what this target's hash should include. namedInputs are reusable, labelled lists of input definitions, declared in nx.json for the whole workspace or in a project's project.json to override or extend them locally. A target's inputs usually reference these names, such as default or production, instead of repeating globs.
A ^ prefix changes where a name resolves. production means the production file set of the current project. ^production means the production file set of each project this one depends on. This is how a change in a shared library invalidates its consumers without pulling in the library's test files.
The cache is only as correct as these definitions. If an input is missing, Nx serves stale results. If an input is too broad, Nx rebuilds work it did not need to. Treat input definitions as a deliberate contract and review them like code. Input semantics and defaults have changed across Nx releases, so check the documentation for the version you have installed.
+-------------------------------------------------------+
| namedInputs (nx.json, or project.json to override) |
| default -> project's files |
| production -> e.g. default minus test files |
+-------------------------------------------------------+
v target inputs reference names
+-------------------------------------------------------+
| target "build" inputs: ["production", "^production"] |
+-------------------------------------------------------+
v v v
+----------------+ +------------------+ +------------------+
| production | | ^production | | other inputs: |
| this project's | | each dependency | | env vars, |
| file set | | project's files | | runtime values, |
+----------------+ +------------------+ | external deps, |
| | | target config |
| | +------------------+
+--------------------+---------------------+
| hash each piece, combine
v
+-----------------------+
| task hash (cache key) |
+-----------------------+
+--------------+--------------+
v v
+-------------------+ +-------------------+
| hit: replay the | | miss: run task, |
| cached output | | store output |
+-------------------+ +-------------------+
A target's inputs reference namedInputs, with '^production' resolving against dependency projects; every declared piece is hashed and combined into one cache key that decides whether Nx replays a cached result or runs the task.
Why should you define default, production and sharedGlobals inputs?
On a monorepo with dozens of backend services, the hash is what decides whether CI rebuilds a service or replays a cached result. If the hash is too broad, editing a test file triggers a production rebuild. If it is too narrow, CI replays a stale artifact. Named inputs let you define these file sets once and reuse them, so each target's inputs are not hand-written separately.
Most workspaces converge on three sets:
sharedGlobalsholds root-level files that every task depends on. Typical entries are{workspaceRoot}/tsconfig.base.jsonand the CI workflow file, because a change to compiler paths or pipeline setup should invalidate everything.defaultis{projectRoot}/**/*plussharedGlobals. It covers every file in the project and the globals.productionstarts fromdefaultand then removes files with!negations. Common exclusions are spec files,{projectRoot}/tsconfig.spec.json, the project's Jest config, its ESLint config, and*.stories.*files. Build output does not depend on any of these, so changing them should not change a build hash.
Order matters inside an input list. Each negation removes files only from the set built up by the entries before it. A negation placed before default has nothing to remove from, so it does nothing.
The tokens are not optional. Nx replaces {projectRoot} with each project's directory and {workspaceRoot} with the repository root. If you leave the token off, the pattern resolves relative to a location you did not intend. It then matches nothing, or matches files outside the project, and Nx gives no warning. The result is a hash that looks valid but is computed from the wrong files.
// nx.json (Nx parses this file with comment support)
{
"namedInputs": {
// Root files every task depends on. A change here invalidates all hashes.
"sharedGlobals": [
"{workspaceRoot}/tsconfig.base.json",
"{workspaceRoot}/.github/workflows/ci.yml"
],
// Every file in the project, plus the shared globals.
"default": ["{projectRoot}/**/*", "sharedGlobals"],
// Start from default, then remove files the build output never depends on.
// Negations must come after "default" so they have a set to remove from.
"production": [
"default",
"!{projectRoot}/**/?(*.)+(spec|test).[jt]s?(x)?(.snap)",
"!{projectRoot}/tsconfig.spec.json",
"!{projectRoot}/jest.config.[jt]s",
"!{projectRoot}/eslint.config.mjs",
"!{projectRoot}/**/*.stories.@(js|jsx|ts|tsx|mdx)"
]
},
"targetDefaults": {
// Build hashes this project's production files and its dependencies' production files.
"build": { "inputs": ["production", "^production"], "cache": true },
// Tests need spec files, so they use default for the project itself.
"test": { "inputs": ["default", "^production"], "cache": true },
// Lint also depends on the root ESLint config.
"lint": {
"inputs": ["default", "{workspaceRoot}/eslint.config.mjs"],
"cache": true
}
}
}
An nx.json namedInputs block that defines sharedGlobals, default and production, using {projectRoot} and {workspaceRoot} tokens and placing negations after default, then wires those inputs into the build, test and lint target defaults.
How do you wire build, test and lint targets with targetDefaults?
With named inputs defined, targetDefaults in nx.json applies them to every project that has a matching target name. Three entries cover most backend workspaces. build takes production and ^production. test takes default, ^production and the project's test runner config. lint takes default plus the workspace-root lint config.
The ^production on test is the important choice. A consumer's tests run against a dependency's compiled or exported source, never against that dependency's spec files. Editing a library's spec cannot change a consumer's test result, so it should not invalidate the consumer's cache. If you used ^default there, every spec edit in a shared library would rerun tests across every dependent service.
| Target | Inputs | Reason | Should invalidate | Should not invalidate |
|---|---|---|---|---|
| build | production, ^production |
Output depends only on shipped source | src/ code, dependency source, tsconfig |
Specs, test configs, READMEs |
| test | default, ^production, runner config |
Own tests plus what dependencies export | Own specs, dependency source, runner config | Dependency specs |
| lint | default, root lint config |
Lint rules apply to all files, including tests | Any project file, root lint rules | Dependency changes |
Override inputs in a project's project.json only when that project genuinely differs, for example a service whose build reads a schema directory outside src/. Each override takes precedence over the default and lives in a separate file. Reviewers auditing cache behaviour then have to check every project file, not one central config. Keep overrides rare, and comment why each one exists.
// nx.json (Nx parses this file as JSONC, so comments are allowed)
{
"namedInputs": {
// Every file in the project, plus workspace-wide globals
"default": ["{projectRoot}/**/*", "sharedGlobals"],
"sharedGlobals": ["{workspaceRoot}/tsconfig.base.json"],
// Only what ships: drop specs, test configs and docs
"production": [
"default",
"!{projectRoot}/**/*.spec.ts",
"!{projectRoot}/jest.config.ts",
"!{projectRoot}/tsconfig.spec.json",
"!{projectRoot}/**/*.md"
]
},
"targetDefaults": {
"build": {
// Own shipped source plus dependencies' shipped source
"inputs": ["production", "^production"],
"cache": true
},
"test": {
// Own specs, but only dependencies' production files:
// editing a library's spec cannot change a consumer's result
"inputs": ["default", "^production", "{projectRoot}/jest.config.ts"],
"cache": true
},
"lint": {
// Lint covers all own files and the shared root rules,
// no ^ input because dependency changes do not alter lint output
"inputs": ["default", "{workspaceRoot}/eslint.config.mjs"],
"cache": true
}
}
}
An nx.json that defines default and production named inputs and wires them into build, test and lint through targetDefaults, so dependency spec edits never invalidate a consumer's test cache.
When do environment variables, runtime commands and externalDependencies belong in inputs?
File globs cover most of a hash, but some outputs depend on things that never appear in the repository. Nx has three non-file input types for these cases.
An env input, such as { "env": "NODE_ENV" }, adds that variable's value to the hash. Use it when the variable changes the artifact itself. A bundler that inlines NODE_ENV or strips debug branches based on it produces different bytes per value. Without the input, a development build can be restored as a production one.
A runtime input, such as { "runtime": "node --version" } or a compiler version command, hashes the command's output. For a backend service compiled by a toolchain that isn't pinned through the lockfile, this keeps artifacts built by one compiler version from being reused by another.
An externalDependencies input, such as { "externalDependencies": ["prisma", "@nestjs/core"] }, limits which third-party packages contribute to the hash. Bumping an unrelated dev tool then no longer invalidates the service's build.
A typical backend build target combines all three: production and ^production file inputs, NODE_ENV, the toolchain version command, and the few packages that actually shape the output.
These inputs have costs in both directions. env and runtime make hashes depend on the machine or CI agent, so laptops on a different patch version or agents with drifting variables will miss a shared remote cache that would otherwise hit. Omitting one is worse. Two environments then produce identical hashes for different outputs, and whichever writes to the cache first serves its artifact to the other. Add a non-file input only when it changes the output, and pin toolchains so the values stay consistent across machines.
{
"name": "orders-api",
"targets": {
"build": {
"executor": "nx:run-commands",
"options": {
"command": "node scripts/build.mjs",
"cwd": "apps/orders-api"
},
"inputs": [
"production",
"^production",
{ "env": "NODE_ENV" },
{ "runtime": "node --version" },
{ "externalDependencies": ["prisma", "@nestjs/core"] }
],
"outputs": ["{workspaceRoot}/dist/apps/orders-api"]
}
}
}
A backend build target whose hash covers production files, the NODE_ENV value, the Node.js version reported on the machine, and only the two third-party packages that shape the output, rather than the whole lockfile.
Backend gotchas: generated code, migrations, Dockerfiles and env templates
Backend projects often depend on files that sit outside their own folder. Generated OpenAPI or protobuf clients, shared .proto definitions and ORM schema files commonly live in a top-level generated/ or schema/ directory. Nx does not hash those files unless the project graph links them to the project, so a schema change can leave a stale build cache hit in place. To include them, add an explicit fileset to the target's inputs: "inputs": ["production", "{workspaceRoot}/generated/api-client/**/*"]. Paths that use {projectRoot} cannot reach these files.
Migrations, Dockerfiles and env templates belong in the inputs only for targets whose output they change:
- Migration files:
- Include them for an integration-test target that applies migrations to a real database.
- Exclude them, for example with
!{projectRoot}/migrations/**/*inproduction, when the compiled bundle never embeds them. Otherwise every new migration invalidates the build.
- Dockerfiles:
- Include them for an image-build target.
- Exclude them from compile and lint.
.env.exampletemplates:- Include them only if a codegen step turns them into typed config.
Inputs describe what Nx hashes. They do not control what your tools read. A compiler, test runner or config loader can open any file on disk, and Nx will not notice. Dynamic paths are the most common source of false cache hits. A config that does require(path.join(baseDir, process.env.APP_ENV + '.json')) reads a file that appears in no input pattern, so changing that file leaves the hash the same. If a target loads a file through a computed path, add that file to the target's inputs yourself.
How can you verify Nx cache hashes instead of trusting defaults?
Reading nx.json tells you what you intended. Inspecting the resolved inputs tells you what Nx actually uses. nx show project <name> prints each target with its resolved inputs after targetDefaults and project-level overrides are merged. nx graph lets you browse the same information visually, and in recent versions it can show the files that feed a specific task. Flags and views have changed across releases, so check nx show project --help and nx graph --help against your installed version before you script anything.
After that, test behaviour directly. Use a clean working tree for every step:
- Baseline. Run
nx run api:buildtwice. The second run should be reported as restored from cache. If it is not, something nondeterministic is in the hash, such as a timestamp or an unpinned runtime input. Fix that before going further. - Spec change. Append a comment to a
*.spec.tsfile, then runbuildandtestagain.buildshould hit the cache andtestshould miss. Ifbuildmisses, yourproductionexclusions do not match your spec files. - Shared global change. Edit a file listed in
sharedGlobals, such as a roottsconfig.base.json. Both targets should miss. If either one hits, that file is not reaching the hash.
Revert each edit after the check.
Put this sequence in a CI job that runs whenever nx.json, project configuration or lint rules change. Exclusion patterns are tied to naming conventions. If a team moves tests into __tests__/ directories or adopts *.test.ts, the old patterns stop matching. Nothing fails at that point: test edits simply start invalidating build caches without any warning. An automated hit/miss assertion is the only reliable way to catch that drift.
When should you avoid narrow inputs, and what are the alternatives?
Narrowing inputs is not free. The two failure directions carry very different costs. A false cache miss wastes CI minutes. A false cache hit restores an artifact built from code that no longer exists, and nothing flags it. Treat any exclusion you cannot justify file by file as a liability.
Over-broad inputs are the safe failure. Leaving targets on the defaults, or hashing the entire root lockfile so that any dependency bump invalidates every project, lowers hit rates. It never ships a stale binary. If your test suite is fast or your builds rarely repeat, that trade is often correct.
How you structure the definitions also matters. Centralized namedInputs in nx.json keep every project on one rule set, so a single review covers the whole repo. That same coupling means one bad pattern breaks every project at once. Per-project overrides let an unusual service declare exactly what it reads. The cost is that answering "what does this hash cover?" now means reading several files.
Some alternatives avoid fine-tuning entirely:
| Approach | Correctness risk | Hit rate | Maintenance effort |
|---|---|---|---|
| Aggressively narrow inputs | High | High | High |
| Nx defaults / broad inputs | Low | Low to moderate | Low |
Centralized namedInputs only |
Moderate, repo-wide | Moderate to high | Moderate |
| Per-project overrides | Moderate, hard to audit | High | High |
| Disable caching for risky targets | None for those targets | None for those targets | Low |
| Build tool's own incremental cache | Depends on the tool | Varies | Low in Nx, tool-specific |
For targets with side effects, such as migrations or image pushes, turn caching off. Don't try to model every input for them.
How do precise inputs affect CI cost and engineering time?
Illustrative estimate (assumed numbers, not a benchmark)
Assume a backend monorepo with 40 projects, 60 commits per day reaching CI, and 25% of those commits touching only spec files, fixtures or docs. Each such commit invalidates the build of 6 projects on average, and an average build takes 4 minutes.
Minutes saved per day = commits/day × test-or-docs fraction × projects affected × build minutes
60 × 0.25 × 6 × 4 = 360 CI minutes per day, or about 7,500 per month over 21 working days. Tests still run on those commits because their hash includes spec files. Only the build reuses its cache.
The savings are real only if the production input set is correct. An exclusion pattern that also matches a runtime config file produces a stale artifact that passes CI. One incident like that can cost more engineering time than months of saved minutes, which is why the costs below matter.
| Where time is spent | Where time is saved |
|---|---|
Initial design of namedInputs and targetDefaults (assume 2–3 engineer-days) |
Shorter queue and feedback time on test-only and docs-only PRs |
| Review of every input change, treated like a build-script change | Fewer "why did this rebuild?" investigations |
| Periodic hash verification, such as a quarterly check that edits the files you exclude | Fewer reruns with caching disabled "just to be safe" |
| Onboarding engineers to the input model | Smaller cache storage and less cache upload traffic |
If your test-only fraction or build time is small, the formula may show that broad default inputs are the cheaper option.
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
.envby 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.