How does nx affected decide which projects changed?
Nx starts from a list of touched files, usually the git diff between a base and head commit plus any uncommitted changes. It maps each file to a project by matching the file path against project roots. A change under libs/billing/ touches the billing project. Nx then walks the project graph and adds every project that depends on billing, directly or transitively. That set is the affected set.
Files outside every project root, such as nx.json, tsconfig.base.json, package.json and the lockfile, need separate handling. They belong to no project, but Nx does not ignore them. Assume they are global unless you have checked otherwise. For some of these files Nx inspects the change. A lockfile edit, for example, can be traced to the external package nodes that changed and then to the projects that depend on those packages. For other root files, Nx falls back to treating every project as affected. Implicit dependencies declared in configuration add more edges to the graph on top of this.
Two separate mechanisms run here, and they are easy to confuse:
Affected: changed files → project roots → project graph → which projects run
Hashing: changed files → each task's inputs → task hash → cache lookup → hit (replay) or miss (execute)
Affected decides which tasks are scheduled. Input hashing decides whether each scheduled task actually executes or replays a cached result. A project can be affected and still hit the cache. A file that appears in every task's inputs, however, changes every hash and causes a cache miss for every task.
+---------------------------------------+
| touched files: git diff base..head |
| plus uncommitted changes |
+-------------------+-------------------+
|
+---------------------+-----------------------+
| AFFECTED | HASHING
v v
+-----------------------+ +--------------------------+
| in a project root? | | changed files that match |
| yes: owning project | | each task's inputs |
| no (nx.json, lockfile,| +-------------+------------+
| tsconfig.base.json): | |
| global by default; | v
| lockfile traced to | +--------------------------+
| changed packages | | task hash, one per task |
+-----------+-----------+ +-------------+------------+
| |
v v
+-----------------------+ +--------------------------+
| project graph walk: | | cache lookup |
| add dependents and | +-----+---------------+----+
| implicit dependencies | | |
+-----------+-----------+ v v
v +---------+ +---------+
+-----------------------+ | hit: | | miss: |
| affected set: these |------------------->| replay | | execute |
| tasks are scheduled | +---------+ +---------+
+-----------------------+
Touched files feed two separate paths: the affected path decides which tasks are scheduled, and the hashing path decides whether each scheduled task replays from cache or executes.
What are sharedGlobals and named inputs in nx.json?
Named inputs are reusable sets of files (and other hash sources) that you define once in nx.json and reference by name from targets. They decide what goes into a task's hash, so they control both cache hits and how far a change reaches.
A typical generated workspace defines three:
defaultusually means{projectRoot}/**/*plussharedGlobals. It covers every file in the project and whatever the workspace declares global.productionstarts fromdefaultand adds negated patterns such as!{projectRoot}/**/?(*.)+(spec|test).[jt]s?(x),!{projectRoot}/tsconfig.spec.json, and test config files. Editing a spec file then leaves the build hash unchanged.sharedGlobalsis often an empty array at first. Teams add entries like{workspaceRoot}/babel.config.jsonor a roottsconfig.base.jsonto it.
targetDefaults connects these named inputs to targets. A common pattern sets build to ["production", "^production"], where the caret pulls in the production inputs of dependency projects. test is usually set to ["default", "^production"].
The effect is direct. Every target whose inputs resolve to default includes each sharedGlobals file in its hash. That is usually build, test, and lint across every project.
Teams use global inputs for a valid reason. Some files really do affect every project: a root compiler config, a shared Babel preset, a toolchain version file. If you leave those out, Nx can replay a stale cached artifact after the config changes. That bug is quiet and hard to trace. Over-declaring inputs costs build time. Under-declaring them costs correctness.
These defaults vary across Nx versions and plugins, and inferred targets can add their own inputs. Check your resolved configuration rather than assuming it matches this example.
{
"namedInputs": {
"default": ["{projectRoot}/**/*", "sharedGlobals"],
"production": [
"default",
"!{projectRoot}/**/?(*.)+(spec|test).[jt]s?(x)",
"!{projectRoot}/tsconfig.spec.json",
"!{projectRoot}/jest.config.[jt]s"
],
"sharedGlobals": [
"{workspaceRoot}/babel.config.json",
"{workspaceRoot}/tsconfig.base.json"
]
},
"targetDefaults": {
"build": {
"dependsOn": ["^build"],
"inputs": ["production", "^production"],
"cache": true
},
"test": {
"inputs": ["default", "^production"],
"cache": true
},
"lint": {
"inputs": ["default"],
"cache": true
}
}
}
A representative nx.json where build, test, and lint all resolve to the default named input, so editing babel.config.json or tsconfig.base.json in sharedGlobals changes the hash of every one of those targets in every project. Your Nx version and plugins may resolve these defaults differently.
Why does one file change make Nx rebuild everything?
Every task hash includes the contents of every file matched by its inputs. Files in sharedGlobals, or in the default named input, feed into nearly every target in the workspace. Change one byte in such a file and every project's hash changes. Every cached result then misses, and nx affected reports all projects. Nx is doing what you told it to do. You declared that file able to change any project's output, so when it changes, Nx cannot safely reuse anything.
The real question is whether the declaration was correct. Some root files do shape every build: the TypeScript compiler options and path mappings in a base tsconfig, or the package manager configuration that determines what gets installed. Others ended up global because a broad glob such as {workspaceRoot}/*.json matched them, or because someone added a file to fix a single stale cache entry and never scoped it down.
| Root file | Usually truly global? | Where it belongs instead |
|---|---|---|
Base tsconfig (compiler options, paths) |
Yes, for build and typecheck | Keep it global, but consider excluding it from targets that don't compile, such as some lint or format tasks |
Package manager config (e.g. .npmrc) |
Yes | Keep it global |
| Lockfile | Rarely as a raw file | Rely on Nx's dependency tracking of external packages, which limits impact to projects that use the changed package |
| CI pipeline config | No | Leave it out of inputs. It changes how tasks run, not what they produce |
{workspaceRoot}/*.json glob |
No | List the specific files you need |
| Root lint or test preset | Only for that target | Add it to the inputs of the lint or test target only |
How do you diagnose a full rebuild in an Nx workspace?
Work through these in order. The early steps are cheaper, and they rule out causes that would make the later steps misleading.
-
Check the base and head before touching
nx.json. If CI runs on a shallow clone, Nx may not be able to find a merge-base withmain. Depending on how it fails, you can get an error or an affected set that covers the whole workspace. A stale localmaincauses the same symptom, because the diff then includes every commit merged since your last fetch. Fetch enough history, then rungit merge-base origin/main HEADyourself. Confirm it returns the commit you expect. -
Decide whether affected or hashing caused the full run. These are different failures:
- If
nx affectedlisted every project, the problem is in the project graph or the touched-file set. - If it listed a few projects but every task missed the cache, the problem is in hash inputs.
- If
-
Inspect resolved inputs. Run
nx show project <name>, or open the project details view innx graph. Either shows the inputs a target actually resolves to after named inputs andsharedGlobalsare expanded. A{workspaceRoot}glob that matches more than you intended usually shows up here. -
Compare task hashes across two runs. Take the same task from a cached run and an uncached run and diff their hash details. The input whose hash differs is your culprit. Where these details are exposed varies by Nx version and setup, so check your version's documentation.
-
Reproduce CI's view. Run
nx graph --affectedwith the same--baseand--headvalues CI used. The highlighted paths show which edge pulled each project in.
#!/usr/bin/env bash
# Diagnose an unexpected full rebuild in an Nx workspace.
# Use the same BASE/HEAD values your CI job uses.
set -euo pipefail
BASE=origin/main
HEAD_REF=HEAD
# 1. Rule out git history problems before touching nx.json.
# A shallow clone can hide the merge-base.
if [ "$(git rev-parse --is-shallow-repository)" = "true" ]; then
git fetch --unshallow origin
fi
git fetch origin main # avoid diffing against a stale local main
echo "merge-base: $(git merge-base "$BASE" "$HEAD_REF")"
# Confirm this is the commit you expect, then list what actually changed:
git diff --name-only "$(git merge-base "$BASE" "$HEAD_REF")" "$HEAD_REF"
# 2. Affected or hashing? Count affected projects vs. all projects.
# (`show projects --affected` is available in recent Nx versions.)
echo "affected: $(npx nx show projects --affected --base="$BASE" --head="$HEAD_REF" | wc -l)"
echo "total: $(npx nx show projects | wc -l)"
# Nearly equal counts: suspect the graph or touched files.
# Few affected but every task missed cache: suspect hash inputs.
# 3. Inspect resolved inputs for one target, after namedInputs
# and sharedGlobals are expanded. Look for broad {workspaceRoot} globs.
npx nx show project my-app
# 4. Compare task hashes from a cached run and an uncached run.
# Where hash details are exposed varies by Nx version; check your docs.
# 5. Reproduce CI's view of why each project was included.
npx nx graph --affected --base="$BASE" --head="$HEAD_REF"
A shell walkthrough that checks git history and the merge-base first, then compares affected and total project counts, inspects resolved inputs, and opens the affected graph using CI's base and head.
How can you narrow global inputs without breaking the cache?
Start by emptying sharedGlobals of anything only one kind of target reads. A root ESLint config affects linting and nothing else, so it belongs in the lint target's inputs under targetDefaults, for example as {workspaceRoot}/.eslintrc.json. It does not belong in a global input that also feeds build and test. Each file stays tracked by the targets that actually read it, so cache correctness holds. The only change is that unrelated targets stop being invalidated.
Lockfile churn works the same way. An externalDependencies input lets a target declare the specific packages it depends on, such as eslint for lint or your bundler for build. A lockfile change then only alters that target's hash when one of those packages' resolved versions changes. Without it, any dependency bump can invalidate every target.
Next, tighten the production named input with negated patterns. Exclude spec files, jest.config.*, test tsconfig files, and local ESLint configs, using entries like !{projectRoot}/**/*.spec.ts. Editing test setup will still re-run test, but it will no longer produce new build hashes downstream.
Finally, split monolithic root configs. Keep a small base, such as tsconfig.base.json with only compiler options that rarely change, and have per-project or per-domain files extend it. Path mappings and lint rules that change often then live closer to their owners, so editing one domain's rules only affects that domain.
The before snippet shows a single sharedGlobals list holding the lint config, the test config, and the lockfile. The after snippet shows target-scoped inputs plus a project tsconfig.json that extends the base.
Platform teams that own large monorepos with long CI runs gain the most here. In those workspaces, every unnecessary global invalidation is paid for across hundreds of targets.
{
"namedInputs": {
"sharedGlobals": ["{workspaceRoot}/tsconfig.base.json"],
"default": ["{projectRoot}/**/*", "sharedGlobals"],
"production": [
"default",
"!{projectRoot}/**/*.spec.ts",
"!{projectRoot}/jest.config.*",
"!{projectRoot}/tsconfig.spec.json",
"!{projectRoot}/.eslintrc.json"
]
},
"targetDefaults": {
"build": {
"dependsOn": ["^build"],
"inputs": [
"production",
"^production",
{ "externalDependencies": ["webpack"] }
],
"cache": true
},
"test": {
"inputs": [
"default",
"^production",
"{workspaceRoot}/jest.preset.js",
{ "externalDependencies": ["jest"] }
],
"cache": true
},
"lint": {
"inputs": [
"default",
"{workspaceRoot}/.eslintrc.json",
{ "externalDependencies": ["eslint"] }
],
"cache": true
}
}
}
An 'after' nx.json: sharedGlobals keeps only the rarely changing tsconfig.base.json, root lint and test configs are scoped to their targets, externalDependencies replace the whole lockfile, and production excludes test-only files.
When should you avoid narrowing inputs?
Narrowing inputs trades build time for correctness risk, and the two failure modes are not symmetric. An input set that is too wide costs CI minutes. An input set that is too narrow produces a stale cache hit: Nx computes the same hash, restores outputs built against an old config, and the target reports success. Nothing fails, so nobody investigates. You find out later, when a lint rule that should have fired didn't, or a compiled artifact behaves differently from a local build. If you cannot say with confidence that a target ignores a file, keep it in the inputs.
The lockfile shows the tension clearly. Treating the whole lockfile as an input is safe but coarse, because any dependency bump invalidates every target that includes it. Declaring only the specific external packages a target uses is more precise, but then correctness depends on Nx resolving transitive and peer dependencies correctly. If a peer dependency changes and the graph misses it, you get the silent failure described above.
Per-project configs also drift. Once each project declares its own inputs, copies diverge, and one project quietly omits a file the others include. Lint rules or generators that stamp out consistent project.json defaults help keep them aligned.
New config files are the hardest to catch. Each one ends up either ignored or global, and both mistakes look like an ordinary diff in review.
Finally, a small workspace with fast builds may not justify any of this. If a full rebuild takes a few minutes, the extra configuration and its upkeep can cost more than the CI time it saves.
What are the alternatives, and what does each approach cost?
| Approach | Correctness risk | Maintenance cost | CI time impact |
|---|---|---|---|
| Keep broad global inputs | Lowest | Lowest | Full rebuild on every root edit |
| Remote caching alone | Low | Low | No help when a root edit changes every hash, because every lookup misses |
| Narrow inputs per target | Medium: a missing input means stale cache hits | Medium: inputs must track tooling changes | Root edits rebuild only the targets that read them |
| Split configs per project | Low to medium | High: more files, and they drift | Smallest blast radius |
| Disable caching or skip affected (anti-pattern) | Hidden, because nothing is verified as unchanged | Low at first | Every run is a full run |
The trade is configuration you maintain against rebuilds you avoid. Each narrowed input is one more thing a reviewer must check. Each avoided full rebuild shortens the wait before someone can review or merge.
Illustrative estimate (assumed numbers, not a benchmark)
Assumed inputs:
- 40 projects
- 5 build minutes per project
- 6 root-file edits per week
- After narrowing, each root edit affects about 5 projects
Formula: weekly minutes saved = edits × (projects rebuilt before − projects rebuilt after) × minutes per project
With the assumed inputs: 6 × (40 − 5) × 5 = 1,050 compute minutes per week.
Parallel agents reduce how much of that shows up as wall-clock time. Compare the result against the hours your team spends keeping the inputs correct.
Whichever approach you choose, audit implicitDependencies, sharedGlobals, and named inputs on a regular schedule. Entries get added to fix one incident and are rarely removed. Over time they accumulate until every change touches every project, and affected no longer narrows anything.
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 affected all projects, 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.