What is Nx affected?

Nx affected is not change detection in the sense of watching a filesystem or diffing build outputs. It is a deterministic computation over two inputs, a pair of git commits and the project graph. Given the same SHAs, the same working tree and the same graph, it returns the same set of projects every time. That property lets you trust it in CI and reproduce a CI result on a laptop.

How does it work?

The computation has two steps.

Step one: collect changed files. Nx resolves a base SHA and a head SHA, then asks git which files differ between them. When you run it locally without an explicit head, it also includes uncommitted and untracked files. That way, work you haven't committed yet still counts as changed. The output of this step is a flat list of file paths. Nothing project-aware has happened yet.

Step two: map files to projects and expand. Each path is assigned to the project whose root directory contains it. When project roots are nested, the most specific root wins. Those projects are marked as directly touched. Nx then walks the project graph in reverse, from each touched project to everything that depends on it. It repeats this transitively until no new projects appear. The union is the affected set. Your requested target, such as test or build, then runs only on projects in that set that define it.

The rest of this article examines each stage in order:

  • SHA resolution
  • File collection
  • File-to-project mapping
  • Reverse-dependency traversal

Most surprising results trace back to an input at one of these stages, not to a bug in the algorithm.

 +-----------+   +-----------+
 | base SHA  |   | head SHA  |
 +-----+-----+   +-----+-----+
       |               |
       +-------+-------+
               v
 +---------------------------+     +----------------------------+
 | 1. git diff base..head    |<----| local only: uncommitted +  |
 | (file collection)         |     | untracked files            |
 +-------------+-------------+     +----------------------------+
               | flat list of file paths
               v
 +---------------------------+     +----------------------------+
 | 2a. map each file to the  |<----| project roots              |
 | project whose root holds  |     | (directories)              |
 | it (most specific wins)   |     +----------------------------+
 +-------------+-------------+
               | directly touched projects
               v
 +---------------------------+     +----------------------------+
 | 2b. reverse-dependency    |<----| project graph              |
 | walk, transitive, until   |     | (who depends on whom)      |
 | no new projects appear    |     +----------------------------+
 +-------------+-------------+
               | affected set (union)
               v
 +---------------------------+
 | run target (test, build)  |
 | on affected projects that |
 | define it                 |
 +---------------------------+

Nx affected as a deterministic pipeline: resolve base and head SHAs, collect changed files from git, map each file to its owning project, then expand transitively through reverse dependencies in the project graph to get the affected set.

How does Nx resolve the base and head SHA?

SHA resolution takes two inputs. --base is the reference you compare against. When you omit it, Nx uses the defaultBase setting in nx.json, and falls back to main if that setting is absent. --head is the commit that represents "now", and it defaults to HEAD. Omitting --head has a side effect that is easy to miss: Nx also adds uncommitted and untracked files to the change set. Locally that is usually what you want. In CI, where the working tree should be clean, set both flags explicitly so the result never depends on stray files.

Nx does not diff head against the tip of base. It first computes the merge-base, which is the most recent common ancestor of the two commits, and diffs from that point. The reason is that a comparison against the tip would count every commit that landed on main after you branched as one of your changes. On an active repository, that would mark large parts of the graph as affected for unrelated work.

The merge-base has its own consequence on long-lived feature branches. Until you merge or rebase main into the branch, the merge-base stays at the original fork point. The diff then contains everything the branch has accumulated since that point, not only its latest commits. The affected set grows steadily, and the branch is tested against an older view of main than the one it will eventually merge into.

You can reproduce Nx's input with two commands. Run git merge-base <base> <head> to get the comparison commit. Then run git diff --name-only <merge-base-sha> <head> to list the changed files. The three-dot form git diff --name-only <base>...<head> performs both steps in one command. If this list differs from what you expected, the problem is in the SHAs, not in the graph.

#!/usr/bin/env bash
set -euo pipefail

BASE="origin/main"   # what you would pass as --base
HEAD_REF="HEAD"      # what you would pass as --head

git fetch origin main

MERGE_BASE=$(git merge-base "$BASE" "$HEAD_REF")
echo "tip of $BASE:  $(git rev-parse "$BASE")"
echo "merge-base:    $MERGE_BASE"

echo "--- changed files (two-step) ---"
git diff --name-only "$MERGE_BASE" "$HEAD_REF"

echo "--- changed files (three-dot) ---"
git diff --name-only "$BASE...$HEAD_REF"

echo "--- tip-to-head diff (NOT what Nx uses) ---"
git diff --name-only "$BASE" "$HEAD_REF"

echo "--- projects Nx considers affected ---"
npx nx show projects --affected --base="$BASE" --head="$HEAD_REF"

A shell script that computes the merge-base with git, lists the same changed files Nx uses for affected (in both two-step and three-dot form), contrasts them with a naive tip-of-main diff, and then asks Nx for the affected projects using the same explicit base and head.

How is the project graph built and how do files map to projects?

Nx builds the project graph before it can say anything about affected projects. It starts with project discovery. Nx scans the workspace for project.json files and for package.json files that fall within the configured workspaces. Each one becomes a project node whose root is the directory containing that file. Plugins can also infer projects and targets from other configuration files, so the set of nodes is not always obvious from a directory listing.

Edges come from three sources:

  • Declared dependencies. A dependencies entry in a project's package.json that names another workspace package becomes an edge. Nx trusts this without reading any code.
  • Inferred dependencies. Nx parses source files and resolves imports, such as TypeScript path aliases and package names, to the projects that own the target files. This is static analysis, so it misses dynamic require calls, string-built paths and runtime plugin loading.
  • implicitDependencies. These are relationships that static analysis cannot see, for example a service that reads another project's generated schema or an e2e suite that exercises an API over HTTP. You add them by hand because nothing in the code reveals them.

To map a changed file to a project, Nx assigns the file to the project with the deepest matching root. For example, libs/billing/core/src/tax.ts belongs to libs/billing/core, not to a project rooted at libs/billing. Nested projects therefore stay independent.

Files outside every project root follow different rules. A change to the lockfile, the root package.json, the base tsconfig, nx.json, or CI configuration can mark many or all projects as affected. These files feed into every project's inputs, and Nx cannot narrow their blast radius. Nx can parse lockfile changes to identify which external packages changed, but how precise that analysis is depends on your configuration and Nx version. Verify it against nx show projects --affected in your own workspace rather than assuming it.

cat > apps/api-e2e/project.json <<'EOF'
{
  "name": "api-e2e",
  "$schema": "../../node_modules/nx/schemas/project-schema.json",
  "projectType": "application",
  "implicitDependencies": ["api"]
}
EOF

npx nx graph --file=project-graph.json

touch libs/billing/core/src/tax.ts
npx nx show projects --affected --base=main --head=HEAD

git stash -u
touch tsconfig.base.json
npx nx show projects --affected --base=main --head=HEAD

The example adds an implicit dependency to an e2e project, exports the project graph for inspection, and compares the affected set when a file inside a nested project changes with the set when a root-level config file changes.

Worked example: which projects become affected for three different changes

Illustrative example: the graph and results below are hypothetical, not measured from a real workspace.

Assume four projects. app-a depends on data-access. data-access depends on utils. app-b depends on utils directly. Nx assigns each changed file to the project whose root contains it. It then walks the graph in reverse, following "who depends on me" edges, and repeats until no new projects appear.

Changed files Directly owned by Reverse walk adds Affected set
apps/app-a/src/main.ts app-a nothing, since no project depends on an app app-a
libs/data-access/src/client.ts data-access app-a data-access, app-a
libs/utils/src/format.ts utils data-access, app-a, app-b all four
root config treated as a global input none every project whose inputs include it typically all four

The first case is cheap because apps are leaves. The second stops at app-a because app-b never imports data-access. The walk only follows real edges and does not assume sibling projects are affected. The third case reaches everything because utils sits at the bottom of the graph. Root files such as the lockfile or workspace config often behave the same way. Whether they do depends on how your inputs are configured.

Graph shape therefore sets your CI cost more than the size of the diff does. A one-line edit in a widely imported library triggers more work than a large refactor inside an app. Narrow libraries with few dependents keep affected sets small. Splitting a catch-all utils into focused libraries makes most changes affect only part of the graph.

How can Nx affected save engineering time?

The direct saving is fewer tasks per CI run. The indirect savings often matter more to the people waiting on the pipeline.

Less work per pull request. Affected skips projects that the diff cannot reach through the graph. How much that saves depends on graph shape and on how changes are distributed across it, so measure it in your own workspace by comparing the affected list with the full project list over a sample of recent PRs.

Illustrative estimate, using assumed inputs: assume a workspace with 40 projects, a test target that takes an assumed 3 minutes per project, and a typical PR that touches one library with 7 dependents, so 8 projects are affected. Running everything costs 40 × 3 = 120 task-minutes. Running affected costs 8 × 3 = 24 task-minutes. A PR that edits the lockfile or a root config still costs roughly the full 120. These numbers are assumptions chosen to show the arithmetic, not measurements.

Shorter feedback loops. When fewer tasks run, a PR author gets a result sooner and spends less time context-switching while waiting. Because the result is deterministic for a given base, head and graph, an engineer can run nx affected -t test locally with the same SHAs and get the same project list CI used, instead of pushing commits to find out what CI will do.

Fewer unrelated failures to triage. A full run surfaces flaky or broken tests in projects the PR never touched. Those failures still cost someone time to investigate and rerun. Scoping the run to affected projects keeps most failures relevant to the change under review. The trade-off, covered later in this article, is that breakage outside the affected set needs a separate full run to surface.

No hand-maintained CI path filters. Affected derives the dependency relationships from the project graph instead of from filter rules someone has to update when projects are added, renamed or start importing each other. That removes a category of CI maintenance work and a category of silent gaps where a filter missed a transitive dependency.

The savings shrink when the graph is dense. If most projects depend on one broad library, most changes affect most projects, and the main lever becomes splitting that library rather than tuning CI.

Affected vs. caching vs. distributed execution: what are the alternatives?

Affected and caching answer different questions. Affected asks which projects could have changed given the diff between base and head. Caching asks whether a specific task, with this exact hash of inputs, has already run. Inputs and named inputs mostly feed that hash. A project can be affected and still be a cache hit, for example when a change touched a file that its named inputs exclude. The opposite also happens: a project outside the affected set never gets checked against the cache at all. Affected reduces how many projects run. It does not make any single task faster.

Approach What it reduces Engineering cost Main failure mode
Run everything Nothing Lowest setup CI time grows with repo size
Affected Number of projects run Correct base SHA, accurate graph Root config changes affect everything
Computation caching Re-execution of identical tasks Precise inputs, cache storage Loose inputs cause misses; overly narrow inputs cause stale hits
Distributed execution Wall-clock time Agent infrastructure, more compute spend Total compute still scales with work
Hand-written CI path filters Jobs triggered Constant upkeep Misses transitive dependencies

Path filters fail because they encode the dependency graph by hand, and that copy drifts as the code changes. Combining the techniques gives a better estimate of CI duration. Affected sets the upper bound, caching removes repeated work, and distribution spreads what remains across agents. A change to the lockfile still produces a near-full run. Plan capacity for that case and treat it as normal.

Who should use Nx affected?

Nx affected fits teams whose CI cost is driven by the number of projects in a single repository rather than by any one slow task.

  • Teams running an Nx monorepo with many projects. Once a workspace holds enough projects that running every target on every PR becomes slow or expensive, affected is the first lever to pull, because it needs no extra infrastructure beyond correct SHAs and checkout depth.
  • Platform and developer-experience teams that own CI. They choose the base SHA policy, configure checkout depth and maintain implicitDependencies. A mistake at that level changes CI cost and test coverage for every team in the repository, so the people who own the pipeline should understand the mechanics described here.
  • Workspaces with a modular, reasonably narrow graph. Affected pays off most when many projects are leaves or near-leaves and shared libraries are split along ownership lines. Teams willing to keep the graph that way get the most out of it.
  • Teams currently maintaining path filters by hand. Affected replaces those filters with relationships derived from the graph, including transitive ones.

It is a weaker fit for small workspaces with only a few projects, for graphs where nearly everything depends on one shared library, and for systems whose important dependencies are mostly runtime relationships that static analysis cannot see. The last two cases are covered in more detail at the end of this article.

How do you set up Nx affected in CI and debug its output?

Start with the checkout. Many CI runners clone shallowly by default, and a shallow or detached checkout may not contain the merge-base between your branch and its target. When git cannot find that commit, the diff fails or falls back to something broader, and the affected set stops meaning what you think it means. Fetch full history, or at least enough depth to reach the merge-base, and make sure the base branch ref exists locally.

Choosing the base SHA is a policy decision. Using the PR target branch scopes the run to what this PR changes, which keeps runs small but trusts that main is green. Using the last successful commit on main widens the set to everything since the last known-good state. That costs more compute but catches breakage that an earlier merge left behind. Many teams use the target branch for PRs and last-successful for main.

Pass both SHAs explicitly, for example nx affected -t test --base=<sha> --head=<sha>, so the run doesn't depend on whatever the environment defaults to.

To debug, run nx graph --affected to see the affected projects in the graph, or nx show projects --affected with the same SHAs to print the list. Then compare that list against git diff --name-only <base> <head>. Every changed file should map to a project you expected, or to a global input. Do this check during refactors, file moves and deletions, and any edit to project configuration, because those are the changes most likely to remap ownership.

Platform teams running multi-project monorepos gain the most from this check, since a wrong base silently changes CI cost and coverage for every team.

#!/usr/bin/env bash
set -euo pipefail

TARGET_BRANCH="${TARGET_BRANCH:-main}"
LAST_SUCCESSFUL_SHA="${LAST_SUCCESSFUL_SHA:-}"

if [ "$(git rev-parse --is-shallow-repository)" = "true" ]; then
  git fetch --unshallow origin
fi
git fetch origin "+refs/heads/${TARGET_BRANCH}:refs/remotes/origin/${TARGET_BRANCH}"

HEAD_SHA="$(git rev-parse HEAD)"

if [ -n "$LAST_SUCCESSFUL_SHA" ]; then
  BASE_SHA="$LAST_SUCCESSFUL_SHA"
else
  BASE_SHA="$(git merge-base "origin/${TARGET_BRANCH}" "$HEAD_SHA")"
fi
echo "base=${BASE_SHA} head=${HEAD_SHA}"

echo "--- changed files ---"
git diff --name-only "$BASE_SHA" "$HEAD_SHA"
echo "--- affected projects ---"
npx nx show projects --affected --base="$BASE_SHA" --head="$HEAD_SHA"

npx nx affected -t test --base="$BASE_SHA" --head="$HEAD_SHA"

A CI shell step that makes sure the merge-base is reachable, chooses the base SHA by policy, prints changed files next to the affected project list for debugging, and runs nx affected -t test with explicit --base and --head.

When should you avoid relying on Nx affected alone?

Affected is only as complete as the dependency edges Nx can see. Its failures are asymmetric. If Nx over-reports, you pay extra CI minutes. If it under-reports, you get a green build that is wrong, and nothing in the pipeline flags it.

Under-reporting comes from relationships that only exist at runtime:

Relationship Why static analysis misses it Mitigation
Dynamic import with a computed path The specifier is a runtime string, so it cannot be resolved to a project Add implicitDependencies on the target project
Plugin loaded from config The reference sits in JSON or YAML, not in an import statement Declare the plugin project as an implicit dependency
Shared database schema Schema files and consumers have no import link Make consumers depend on the schema project
Services calling each other over HTTP Network contracts are invisible to the graph Model the contract as a shared library, or add implicit edges

Treat implicitDependencies as maintained code, not a one-time patch. Review it when you add services or move schemas. Also schedule a periodic full run, nightly or before releases, so missing edges show up as failures rather than as production incidents.

A different problem appears in highly connected graphs. If many projects import one catch-all shared library, almost any change marks nearly everything as affected. No CLI flag fixes this. The fix is architectural: split broad libraries along real ownership lines and enforce module boundaries with lint rules so the graph stays narrow.

In small workspaces with a handful of projects, running everything may cost about the same as affected. In that case, the extra configuration may not be worth it.

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 how it works, 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.