How does Nx compute a task hash, and what are named inputs?
Before Nx runs a cacheable task, it computes a hash from everything declared as able to affect the result. If that hash matches a stored entry, Nx replays the cached terminal output and restores the declared outputs instead of executing the command. The hash typically combines:
- Project files matched by the target's
inputs, usually expressed with tokens such as{projectRoot}and{workspaceRoot}. - Upstream project inputs, using the
^prefix.^productionmeans "the production file set of every project this one depends on," so changes to a shared library invalidate its consumers. - The command and target configuration, including the executor, its options, and any arguments passed on the command line.
- External dependency versions, resolved from your package manager's lockfile.
- Explicit
envandruntimeinputs, such as a variable's value or the output of a command likenode --version.
Named inputs are reusable, named file sets defined under namedInputs in nx.json. Common conventions are:
default: all files in a project, plus shared globals.production:defaultwith test, spec, and lint config files excluded using!patterns.sharedGlobals: workspace-wide files that should invalidate everything, such as a root config file.
Targets reference these names in their inputs array. A project can redefine a named input in its own configuration to override or extend the workspace definition.
The key constraint is that Nx cannot detect an input you never declared. A cache hit is only as correct as the inputs list behind it. Missing an input causes Nx to restore stale artifacts without any warning. Including too much just reduces how often you get cache hits.
Default named inputs and generated targets have changed across Nx releases, so check the documentation for your installed version before you rely on them.
+--- nx.json: namedInputs ------------------------+
| sharedGlobals: workspace-wide files (root cfg) |
| default: {projectRoot}/** + sharedGlobals |
| production: default, minus !test/!spec/!lint |
+-------------------------------------------------+
v referenced in target "inputs" (projects may override)
+------------------+ +------------------+ +------------------+
| Project files | | ^production: | | Command + target |
| matched by the | | file sets of all | | config: executor,|
| target's inputs | | upstream deps | | options, args |
+------------------+ +------------------+ +------------------+
| | |
+------------------+ +------------------+ |
| Lockfile: ext. | | env / runtime | |
| dep versions | | e.g. node -v | |
+------------------+ +------------------+ |
| | |
+----------+----------+---------------------+
v
+-----------------+
| Task hash |
+-----------------+
match | | no match
v v
+-------------------+ +---------------------+
| Replay terminal | | Run command, store |
| log, restore | | outputs + log under |
| declared outputs | | this hash |
+-------------------+ +---------------------+
Undeclared input => never hashed => stale cache hit, no warning
Named inputs from nx.json feed a target's inputs, which Nx combines with upstream, command, lockfile, and env/runtime inputs into a task hash that decides whether to replay the cache or run the task.
How does it work during a real run?
When you run a target such as nx build orders-api or nx affected -t build, Nx follows these steps for each task in the task graph:
- Resolve inputs. Nx expands the target's
inputsarray, using the project's own configuration first, thentargetDefaults, then the workspace's named inputs. Named inputs are expanded recursively, soproductionpulls indefault, anddefaultpulls insharedGlobals. Negated globs are then applied. - Walk dependencies. For each
^entry, Nx follows the project graph to every upstream project and collects the matching file set from each one. - Hash. Nx hashes the contents of the resolved files together with the command, target options, relevant lockfile entries, and any
envandruntimevalues. - Look up the hash. Nx checks the local cache first, then a remote cache if one is configured.
- Replay or execute. On a hit, Nx restores the files listed in
outputsand prints the stored terminal output. On a miss, it runs the command and stores the outputs and log under the new hash.
Because dependsOn orders tasks, an upstream miss usually changes the downstream hash as well. Downstream targets that hash ^production see the changed upstream files. Downstream targets that do not hash it can still hit cache if nothing they declared has changed.
Named inputs change step 1. Everything after that follows from what the inputs list resolves to.
Why do backend services need custom Nx cache inputs?
This section is for backend and platform engineers whose build output depends on more than the source files in a project directory. A service bundle can change because of a DATABASE_URL-driven config switch, a different Node or JVM version on the runner, a dependency bump in the root lockfile, or a regenerated client from an OpenAPI or protobuf schema. Nx only knows about these factors if you declare them as inputs.
A typical project-wide input set errs in both directions at once:
| Failure mode | Example | Result | Cost |
|---|---|---|---|
| Too broad | Editing a *.spec.ts file or a README changes the build hash |
Cache miss, full rebuild | Wasted CI minutes, slower feedback |
| Too narrow | A build-time env var, runtime version or generated code is not in the hash | Cache hit on an outdated artifact | Stale or wrong build reaches deploy |
These costs are not equal. Over-broad inputs make CI slower and more expensive, but the failure is visible and safe. Over-narrow inputs produce false cache hits that look like successful builds. Nx replays the old output and logs, so nothing flags the problem. These are the bugs that take hours to trace, because the code on the branch is correct.
So lean broad and narrow with evidence. Add an exclusion only after you have confirmed that the file cannot affect the target's output.
The effort pays off most in monorepos that share a remote cache and run CI on every push. Each unnecessary miss is repeated across many pipelines, and each false hit can spread to every developer and branch that reads from the same cache.
Who should use custom named inputs?
Tuning named inputs makes sense when most of these conditions apply:
- You already run an Nx monorepo with several backend projects that share libraries, so one change fans out to many targets through
^inputs. - Build, test, or typecheck targets take long enough to matter. If a full CI run takes minutes rather than seconds, each avoidable miss costs real time.
- You use a shared remote cache, or plan to. A correct hash then saves time on every machine that reads the cache. An incorrect hash spreads to all of them as well.
- Build output depends on things outside the project directory, such as env vars, toolchain versions, generated code, or root-level config.
- Someone owns the build configuration. Named inputs need maintenance when the toolchain or project layout changes. Platform or developer-experience teams are usually best placed to do that work.
Teams that probably should not bother include small repos with fast builds, repos where most work happens in a language toolchain that already caches incrementally, and teams that cannot commit to reviewing inputs when targets change. The later section on when to avoid caching covers these cases in more detail.
How do you build a production named input for backend code?
The illustrative nx.json below is not taken from a real repository. It defines three named inputs that the rest of this guide builds on.
default covers every file under {projectRoot} plus sharedGlobals. production starts from default and removes files that cannot change the compiled artifact, using negated globs such as !{projectRoot}/**/*.spec.ts, !{projectRoot}/test/**/*, !{projectRoot}/**/__fixtures__/**, !{projectRoot}/**/*.md and !{projectRoot}/.eslintrc.json. With these exclusions, editing a test helper or a README no longer changes the build hash.
The caret controls scope. production means this project's production files, and ^production means the production files of every dependency. A build target uses ["production", "^production"] because it only needs shippable code. A test target uses ["default", "^production"]: its own specs count, but a dependency's specs do not affect whether this project's tests pass.
sharedGlobals holds root-level files that change behavior everywhere, such as tsconfig.base.json, CI config that sets build flags, and the Dockerfile or base-image definition your services share. Keep this list short. Every entry is part of every project's hash, so adding a frequently edited root file will invalidate the whole repo's cache on every change.
Exclusions are only safe if they are true. If a bundler globs a whole directory, or the service reads fixtures from disk at runtime, those files belong in production. Excluding them produces false cache hits.
{
"namedInputs": {
"default": ["{projectRoot}/**/*", "sharedGlobals"],
"production": [
"default",
"!{projectRoot}/**/*.spec.ts",
"!{projectRoot}/test/**/*",
"!{projectRoot}/**/__fixtures__/**",
"!{projectRoot}/**/*.md",
"!{projectRoot}/.eslintrc.json"
],
"sharedGlobals": [
"{workspaceRoot}/tsconfig.base.json",
"{workspaceRoot}/.github/workflows/ci.yml",
"{workspaceRoot}/docker/base.Dockerfile"
]
},
"targetDefaults": {
"build": {
"dependsOn": ["^build"],
"inputs": ["production", "^production"],
"cache": true
},
"test": {
"inputs": ["default", "^production"],
"cache": true
}
}
}
Illustrative nx.json, not from a real repo: production removes specs, fixtures, docs and lint config from default, build hashes production plus ^production, test hashes default plus ^production, and sharedGlobals stays short.
How do you declare environment variables, runtime versions and lockfile inputs?
File globs only cover what sits on disk. Nx does not see environment variables, toolchain versions or the tools a shell command calls unless the target declares them. If any of these change the artifact, leave them out and the cache will happily return a stale build.
Environment variables
Use an env input, such as { "env": "BUILD_TARGET_ARCH" }, for every variable that changes compiled output. Feature flags inlined at build time, a NODE_ENV that switches code paths, and a target architecture all count. Variables that are only read at runtime do not need to be declared.
Runtime versions
A runtime input runs a command and hashes what it prints, for example { "runtime": "node --version" } or { "runtime": "go version" }. This matters when a compiler upgrade changes the output while the source stays the same.
External dependencies
Nx derives npm package versions from the lockfile for dependencies it can see in the project graph. A run-commands target that shells out to a CLI should name that tool explicitly with { "externalDependencies": ["esbuild"] }.
A typical build target might list production, ^production, one env entry, one runtime entry and one externalDependencies entry.
Trade-offs
Every non-file input can vary from machine to machine. A runtime command that prints an absolute path, or a laptop with a different patch version of a tool, gives that machine a different hash from CI. The result is a split remote cache: developers never hit CI's entries. Prefer commands with stable output and pin toolchains the same way everywhere.
Secrets need the same care. Leaving a secret out of the inputs is only safe if it never affects the output. If a build bakes in an API endpoint or a key, either declare it as an input or move that configuration to runtime so the artifact does not depend on it.
{
"name": "orders-api",
"targets": {
"build": {
"executor": "nx:run-commands",
"options": {
"command": "esbuild src/main.ts --bundle --platform=node --outfile=dist/orders-api/main.js",
"cwd": "apps/orders-api"
},
"cache": true,
"outputs": ["{workspaceRoot}/apps/orders-api/dist/orders-api"],
"inputs": [
"production",
"^production",
{ "env": "BUILD_TARGET_ARCH" },
{ "runtime": "node --version" },
{ "externalDependencies": ["esbuild"] }
]
}
}
}
An illustrative project.json build target whose cache key covers production files, dependency projects, one build-time env var, the Node version and the lockfile version of the esbuild CLI that the command calls.
Per-target inputs and outputs for build, test, lint, Docker and codegen
Each target type depends on a different set of files, so each needs its own inputs and outputs. The table below lists sensible starting points for a backend service. With these settings, every target is hashed on what actually affects it and can be cached without leaking deployment-specific values.
| Target | Recommended inputs | Outputs | Why |
|---|---|---|---|
| build | production, ^production, runtime version, lockfile |
compiled dist directory only |
Tests and docs never change the artifact |
| test | default, ^production, test config |
coverage directory, if consumed | Test files matter here; dependents' tests do not |
| lint | default, root lint config |
none | Results replay from terminal output |
| typecheck | production + type declarations, ^production, tsconfig chain |
.tsbuildinfo, if emitted |
Type errors can come from upstream signatures |
| Docker image | build outputs, Dockerfile, base image tag | image digest or metadata file | The image is a registry side effect, not a file |
| codegen | schema or .proto files, generator version |
generated client directory | Output is a pure function of the schema |
Treat codegen as a real target
Generated files that sit untracked in the source tree are a common cause of stale caches. If the ORM client or protobuf stubs only appear as a side effect of postinstall, Nx cannot see when they change. It can also restore a build that was compiled against an older schema. A dedicated codegen target fixes this. Its inputs are the schema files, and its declared outputs are the generated directory. build then lists codegen in dependsOn and includes the generated path in its inputs. A schema edit then invalidates both targets in order, and a cache hit restores the generated client together with the compiled code that depends on it.
Outputs need the same care as inputs
Correct inputs only guarantee a correct hash. What Nx restores is whatever outputs declares. If an output is missing, a cache hit leaves the expected files absent, and the next step fails. If outputs are too broad, such as the whole projectRoot, the cache stores and restores unrelated files and can overwrite local edits.
{
"name": "orders-api",
"targets": {
"codegen": {
"executor": "nx:run-commands",
"options": {
"command": "prisma generate --schema=apps/orders-api/prisma/schema.prisma"
},
"cache": true,
"inputs": [
"{projectRoot}/prisma/schema.prisma",
{ "externalDependencies": ["prisma"] }
],
"outputs": ["{projectRoot}/src/generated/prisma"]
},
"build": {
"executor": "nx:run-commands",
"options": {
"command": "tsc -p apps/orders-api/tsconfig.app.json"
},
"cache": true,
"dependsOn": ["codegen", "^build"],
"inputs": [
"production",
"^production",
"{projectRoot}/prisma/schema.prisma"
],
"outputs": ["{workspaceRoot}/dist/apps/orders-api"]
}
}
}
A project.json where codegen hashes the Prisma schema and generator version and declares the client directory as output, and build runs after it and hashes the schema too, so a schema edit invalidates both and a cache hit restores matching files.
What are the alternatives to tuning Nx named inputs?
Named inputs are one way to cut redundant work. Depending on the repo, other approaches may be enough on their own or may work well alongside them:
- Keep Nx's broad defaults. Hash everything under
{projectRoot}and accept some extra misses. This has no maintenance cost and the lowest risk of false hits. It is often the right choice for small or fast repos. - Run only affected projects without caching.
nx affectedlimits a run to projects touched by a change, measured against a base commit. This cuts work without relying on hash correctness. However, it reruns everything affected every time, even when an identical run already happened on another branch. - Use the language toolchain's incremental compilation. Go, Cargo and Gradle track their own build state. TypeScript project references with
.tsbuildinfodo something similar. These tools know their own inputs precisely, but they usually only cache within one machine's working directory. - Use CI-level directory caching. Many CI systems can save and restore directories keyed on a lockfile hash. This handles dependency installs well. It is too coarse for per-project build artifacts, because a single key covers the whole directory.
- Use Docker layer caching. Ordering Dockerfile instructions so that dependency installs come before source copies lets unchanged layers be reused. It works for image builds but does not help with tests, lint or typecheck.
- Adopt a hermetic, sandboxed build system. Some build systems run every action in a sandbox and fail when an undeclared file is read. That catches missing inputs automatically. The trade-off is a much larger migration and a stricter build definition for every target.
Nx named inputs sit between these options. They give per-target, shareable caching across languages without requiring a sandbox, but the correctness of the inputs depends on you.
How can tuned named inputs save engineering time?
The savings come from three places:
- Fewer avoidable rebuilds. Excluding specs, docs and fixtures from
buildmeans test-only or docs-only changes restore build artifacts from cache instead of recompiling. - Shared work across machines. With a remote cache, a build that CI has already run on
maincan be restored on a developer's laptop or another branch, as long as the hashes match. Stableruntimeandenvinputs make that more likely. - Less time debugging stale artifacts. Declaring env vars, toolchain versions and codegen correctly removes a class of "works after clearing the cache" bugs. These tend to cost the most per incident because nothing in the logs points to them.
Illustrative estimate. All inputs below are assumed, not measured:
- Assumed 100 CI pipeline runs per day.
- Assumed 40% of those runs change only test files, docs or fixtures.
- Assumed each such run triggers builds in 5 backend services.
- Assumed 3 minutes per service build.
If production correctly excludes those files, the avoided rebuilds come to 100 × 0.4 × 5 × 3 = 600 CI minutes per day. Developers also wait less for those pipelines. Your numbers will differ, so measure before and after with the verification steps below, comparing cache hit counts and pipeline durations on comparable changes.
The cost side matters too. Time spent writing and maintaining inputs, plus any stale-cache incident caused by an over-narrow input, comes out of the same budget. That is why the rollout below narrows one target at a time.
When should you avoid caching or narrowing inputs?
Caching assumes the same inputs always produce the same outputs. Some backend tasks break that assumption. A build that embeds a timestamp, stamps the current git SHA into a version file, or downloads a schema or dependency from the network at build time produces different artifacts from identical inputs. Narrowing inputs makes this worse, because a cache hit can then return a stale SHA or an outdated schema. Either make the task deterministic, for example by passing the SHA in as a declared env input or vendoring the schema, or mark the target with cache: false.
Exclusion patterns carry their own risk. If a build reads a file your production input filters out, such as a fixture loaded at startup, a SQL migration directory, or a config file matched by a test glob, that file never affects the hash. Changing it will not trigger a rebuild, and nothing reports the problem.
| Situation | Better choice |
|---|---|
| Task output depends on time, git state, or the network | cache: false, or make the task deterministic |
| Small repo with fast builds | Keep the broad default inputs |
| Config that differs per environment | Read it at runtime instead of baking it into the build |
| Toolchain already compiles incrementally (Go, Cargo, Gradle) | Rely on that and cache only expensive orchestration steps |
Weigh the maintenance cost honestly. Named inputs are configuration that drifts. Each new env var, generated directory, or toolchain upgrade needs a matching input change, and missing one leads to stale cache hits rather than a visible error. In a repo where a full build already takes seconds, that upkeep can cost more than the cache saves.
How do you verify Nx cache hashing and roll out changes safely?
Treat every inputs change as a hypothesis and test it before trusting it. Three quick experiments cover most mistakes:
- Change a spec file in a backend project and rerun
build. It should restore from cache. If it misses, test files are still reaching the build hash, and your production input is not excluding them. - Change a declared environment variable or a lockfile entry and rerun. It should miss. A hit here means a real dependency is invisible to the hash, which is the dangerous direction.
- Inspect what Nx actually hashed. Use the project details view in
nx graphornx show project <name>to see the resolved inputs for each target. Then compare against the run output, which marks tasks restored from cache.
Run these on a branch, both locally and in CI. Environment differences between the two are a common source of surprises.
Rolling out
Start with conservative defaults in nx.json, where targets hash broadly and occasionally miss. Narrow one target at a time, and only after an experiment shows the narrower set still misses when it should. Re-run the experiments periodically and after toolchain upgrades, because inputs drift silently as code and dependencies evolve.
Review checklist for new targets
- Inputs exclude tests, docs and fixtures where irrelevant
- Environment variables and runtime versions that affect output are declared
- Outputs list every artifact the target produces
- The task is deterministic, with no timestamps or random IDs in artifacts
- Generated code is a declared dependency, not an assumed side effect
Getting this right means fewer "rerun CI and hope" cycles. It also means fewer hours spent tracing a bug to an artifact built from yesterday's 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 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.