What is nx affected and what problem does it solve?

nx affected is the Nx mechanism for running a target such as lint, test or build only against the projects a change can actually influence. It works in two steps. First, it computes the set of files that differ between a base commit and a head commit. Second, it maps those files onto the workspace's project graph to find the projects that own them, then walks the dependency edges to add every project that depends on them. The task runs against that set and nothing else.

This leads to the central point of this article: the output is only as correct as the base and head SHAs you supply. Nx does not know what "changed" means for your branch or pipeline. It diffs whatever two references it is given. If the base is wrong, a project can be silently skipped or needlessly rebuilt.

Who should use nx affected?

The people who benefit most are backend and platform engineers running CI for monorepos where a full lint, test and build cycle takes long enough to slow down every merge. Skipping unaffected projects shortens feedback loops for developers. It also cuts compute spend, because runners stop rebuilding code nobody touched.

The savings depend on how finely the code is split into projects. A workspace with a few large projects gains little, since almost any edit marks a large share of the code as affected. Smaller, well-bounded projects give nx affected sharper boundaries, so it can skip more of the workspace on each change.

It is a good fit when these conditions hold:

  • The repository is a monorepo with many Nx projects. Most changes touch a small part of it.
  • Running every target on every change is slow enough to matter. Developers wait on CI, or runner queues back up.
  • Dependencies mostly appear as imports or package manifest entries. Nx can then infer the graph without much manual declaration.
  • Someone owns the CI configuration. The base SHA, fetch depth and fallback behavior all need deliberate setup.

It adds little for a workspace with one or two projects, where the affected set is almost always everything. It also adds little where a full run is already fast. It is risky in codebases with many runtime couplings between projects that nobody has declared. In that case, the graph understates what a change can break, and affected selection will skip projects that should have run.

How does nx affected work? From SHAs to project list

The pipeline has five steps, and each step narrows or widens the result in a predictable way.

1. Resolve the range

--base is the reference point and --head is the end of the range. If you omit --base, Nx uses defaultBase from nx.json. If you omit --head, Nx compares against your working tree instead of a commit, so uncommitted and untracked changes count. That default suits local runs, where you want to know what your current edits affect. It is a poor fit for CI, where the range should be fixed and reproducible.

2. Find the merge base

Nx does not diff base against head directly. It computes git merge-base of the two and diffs from that commit. Suppose your branch forked from main last week and main has since moved ahead by forty commits. A direct diff would include every file those commits touched, even though your branch never changed them. Diffing from the fork point limits the set to what your branch actually changed.

3. Compute changed files

Git produces the list of files that differ across the range.

4. Map files to projects

Each file is assigned to the project whose root directory contains it. Those projects are marked as touched. Files outside any project root are handled by separate rules, which section 5 covers.

5. Walk dependents

Nx traverses the project graph in reverse from each touched project and adds every project that depends on it, directly or transitively. The touched projects plus their dependents form the affected list.

   --base / defaultBase (nx.json)        --head / working tree if omitted
      |                                     |
      +------------------+------------------+
                         v
     +--------------------------------------+
     | 1. Resolve range: base .. head       |
     +--------------------------------------+
                         v
     +--------------------------------------+
     | 2. git merge-base base head          |
     |    (fork point; skips newer main)    |
     +--------------------------------------+
                         v
     +--------------------------------------+
     | 3. git diff: fork point .. head      |
     |    (no --head: + uncommitted files)  |
     +--------------------------------------+
                         v
     +--------------------------------------+
     | 4. Map each file to the project      |
     |    whose root contains => touched    |
     +--------------------------------------+
                         v
     +--------------------------------------+
     | 5. Reverse walk of project graph     |
     |    + direct & transitive dependents  |
     +--------------------------------------+
          affected = touched + dependents

Nx resolves the base/head range, diffs from the merge base, maps changed files to the projects that contain them, then walks the project graph in reverse to add dependents.

How is the project graph built, and how do you correct it?

Nx builds the project graph from two kinds of evidence. Language plugins parse source files and resolve imports: a TypeScript import that resolves to another project's root, through a path alias or a workspace package name, becomes an edge. Package manifests add edges when one workspace package lists another in its dependencies. Both are static. Nx sees only what is written in files it knows how to read.

Declaring what analysis cannot see

Some couplings never appear as imports. A service might read another project's config file at runtime. Code might be generated from a schema that lives in a separate project. A build script might shell out to a sibling project's CLI. For these cases, add implicitDependencies to the project's configuration and name the projects it relies on. Nx treats these entries as real edges, so a change upstream marks the dependent as affected. You can also negate an inferred edge with a ! prefix when you know it is spurious. Use that sparingly, because a wrong negation silently drops projects from CI.

Global and unowned files

Files outside every project root have no owner, and some root files are shared by everything. A change to nx.json, the root package.json, the lockfile, or a shared base tsconfig can mark many projects as affected, or all of them. Nx narrows some of these cases. For manifest and lockfile changes, it works out which external dependencies changed and marks only the projects that use them. That works at the package level, not the import level, so it is coarser than source analysis. Check how your Nx version treats unowned files before you rely on it.

cat > apps/api/project.json <<'EOF'
{
  "name": "api",
  "projectType": "application",
  "implicitDependencies": [
    "config-shared",
    "schema",
    "migrate",
    "!ui-legacy"
  ]
}
EOF
nx show project api --json

nx graph

nx affected -t build --base=origin/main --head=HEAD

nx show projects --affected --base=origin/main --head=HEAD

The script adds implicitDependencies, including one negated edge, to a project's configuration, then uses the Nx CLI to inspect the result and see which projects are affected between two SHAs.

How should you choose base and head SHAs in CI?

For a pull request, set base to the target branch and head to the PR commit. Nx diffs from the merge-base of the two, so the result covers what the PR changed, not what landed on the target branch after the PR branched off.

For builds on main, set base to the last commit that passed CI. HEAD~1 only looks at one commit. If a push contains several commits, or the previous build failed, changes slip through untested. A small CI step can store the SHA of each green build, or query your CI system's API for it, and pass that value as base. If nothing is found, fall back to a full run.

Shallow clones are the most common cause of failure. Many CI checkouts fetch a single commit by default, so the base ref or the merge-base is missing and the diff is wrong or errors out. To fix this:

  • Fetch full history with git fetch --unshallow, or fetch enough depth to reach the merge-base.
  • Fetch the target branch explicitly with git fetch origin main.
  • Check that the ref exists with git rev-parse --verify origin/main and that git merge-base origin/main HEAD returns a SHA.

Then run nx affected --target=test --base=origin/main --head=HEAD. Pass both flags explicitly rather than relying on defaults.

Strategy Correctness Maintenance cost
HEAD~1 Misses multi-commit pushes and changes from failed builds None
Last successful SHA Covers everything since the last green build Needs storage or a CI API lookup, plus a fallback
Target branch (PRs) Accurate for the PR's own changes Low; needs the target ref fetched
#!/usr/bin/env bash
set -euo pipefail

TARGET_BRANCH="${TARGET_BRANCH:-main}"

if [ "$(git rev-parse --is-shallow-repository)" = "true" ]; then
  git fetch --unshallow origin
fi
git fetch origin "$TARGET_BRANCH"

if [ "${CI_EVENT:-}" = "pull_request" ]; then
  # PR: diff against the target branch. Nx uses the merge-base.
  BASE="origin/$TARGET_BRANCH"
  git rev-parse --verify "$BASE" >/dev/null
  git merge-base "$BASE" HEAD >/dev/null || { echo "no merge-base with $BASE" >&2; exit 1; }
else
  # Main: diff against the last green build, read from storage or the CI API.
  BASE="${LAST_GREEN_SHA:-}"
  if [ -z "$BASE" ] || ! git cat-file -e "${BASE}^{commit}" 2>/dev/null; then
    # No usable last-green SHA: run everything instead of guessing.
    echo "No valid last successful SHA; running all projects" >&2
    npx nx run-many --target=test
    exit 0
  fi
fi

npx nx affected --target=test --base="$BASE" --head=HEAD

A CI shell step that unshallows the clone, checks that the base ref and merge-base exist, chooses the target branch for PRs or the last green SHA for main, and falls back to a full run when no base is available.

Why does nx affected pick unexpected projects, and how do you debug it?

Start by making the comparison reproducible. Have the CI job echo the resolved base and head SHAs before any Nx command runs. Most "Nx picked the wrong projects" reports turn out to be "Nx compared different commits than we assumed."

With those two SHAs, check out the same commit locally and run nx show projects --affected --base=<sha> --head=<sha>. If the list matches CI, the selection logic is behaving and the question is why those projects depend on the changed files. nx graph --affected with the same flags answers that visually. It highlights the touched projects and the dependency edges that pulled in the rest, so you can see whether a project was hit directly or through a dependency.

To test a theory without making commits, pass --files with a comma-separated list instead of --base/--head. For example, check whether editing one shared config file really fans out to every project.

Symptom Likely cause What to check
Everything affected A changed file is a global input (root config, nx.json, files in shared named inputs) Which changed files sit outside any project root
Nothing affected Base equals head, e.g. on main comparing against origin/main after the merge The printed SHAs; use the last successful SHA instead
Error or full run in CI only Shallow clone, so the base commit isn't in history Fetch depth; fetch the base ref explicitly
Local differs from CI Without --head, Nx includes uncommitted and untracked local files Run locally with an explicit --head on a clean tree
#!/usr/bin/env bash
set -euo pipefail

BASE="${BASE:?set BASE to the base SHA printed by CI}"
HEAD="${HEAD:?set HEAD to the head SHA printed by CI}"

echo "base=$(git rev-parse "$BASE") head=$(git rev-parse "$HEAD")"
echo "shallow clone: $(git rev-parse --is-shallow-repository)"

if ! git cat-file -e "${BASE}^{commit}" 2>/dev/null; then
  echo "base commit missing; fetch it, e.g. git fetch origin $BASE" >&2
  exit 1
fi

if [ "$(git rev-parse "$BASE")" = "$(git rev-parse "$HEAD")" ]; then
  echo "base == head: nothing can be affected" >&2
fi

git diff --name-only "$BASE" "$HEAD"

npx nx show projects --affected --base="$BASE" --head="$HEAD"

npx nx graph --affected --base="$BASE" --head="$HEAD"

npx nx show projects --affected --files=nx.json,libs/shared/config/src/index.ts

A local script that takes the base and head SHAs from a CI log, checks for a missing base or identical SHAs, then reruns nx show projects and nx graph with the same --base/--head and tries a hypothetical --files change set.

When should you avoid relying on nx affected alone?

Affected selection is a statement about files, not behavior. Nx sees that a file in a project changed and marks every dependent project as affected, even if the change was a comment or a README edit. With a widely shared library, a trivial edit can trigger a near-full run. This costs time but is safe.

The dangerous direction is the false negative: a project that is broken but not selected. That happens whenever a dependency exists that the project graph cannot see:

  • Runtime file reads: a service loads a JSON schema or template from another project's directory by path, not by import.
  • Environment-driven behavior: config or feature flags supplied by CI variables change what code does without changing any file.
  • Code generation: generated clients or types are built from a spec owned by another project, and the link is never declared.
  • Cross-project shell scripts: a build script in one project copies or invokes files from another.

You can declare these with implicit dependencies or inputs, but only for the ones you know about.

Checkout depth also has a cost. Full history guarantees that the base commit is present but slows clones in large repositories. Shallow clones are faster but require you to fetch the base ref explicitly.

Changes to root config files or the lockfile can mark many or all projects as affected. You might be tempted to exclude them from inputs to keep runs incremental, but that hides real breakage.

Tracking the last successful SHA adds CI state that can go stale or be lost, and someone has to own it.

Run the full target set on a schedule, such as nightly, to catch gaps in the graph and environment drift that affected selection will never flag.

What are the alternatives to nx affected, and how does it relate to caching?

Affected selection and computation caching answer different questions. Affected decides which projects are considered at all, based on what changed between base and head. The cache decides whether a selected task actually re-executes. It does this by hashing the task's inputs: source files, configuration, relevant environment, and the inputs of its dependencies. Tightening inputs, for example by excluding docs or spec files from a build target, raises cache hit rates inside the affected set. It does not change which projects affected selects, because selection comes from the project graph and the changed files, not from task hashes.

Approach Development cost CI time Correctness risk Maintenance
Run everything None Highest, grows with repo Lowest None
CI path filters Low at first Low High: rules miss transitive dependencies Rules drift as the graph changes
Cache only Low Moderate: every task is hashed and restored Low, if inputs are complete Tuning inputs
Affected + cache Moderate Lowest Low to moderate: depends on graph accuracy Base SHA ownership plus inputs

Worked example (illustrative estimate). Assume 40 projects, a 3-minute test target each, and a change that affects 7 projects. Also assume a cache restore costs about 10 seconds per task.

  • Run everything: about 120 agent-minutes.
  • Cache only: 21 minutes for the 7 misses, plus roughly 5.5 minutes restoring 33 hits, for about 26.5 minutes.
  • Affected only: 21 minutes.
  • Affected + cache: If a previous run on the same commit cached 4 of the 7 tasks, this drops to roughly 9.7 minutes.

How can nx affected save engineering time?

The time savings come from doing less work per change. They also come from the engineering effort that less work frees up.

Shorter waits on every pull request. CI duration scales with the number of tasks that run. When a PR touches one library and its few dependents, only those tasks run. Developers get a pass or fail result sooner and spend less time switching to other work while they wait. The worked example above shows how the gap can open up under assumed inputs. Your own ratio depends on project count, task duration and how far a typical change fans out.

Less runner contention. Fewer tasks per pipeline means fewer agent-minutes per PR. Queued jobs start sooner when many PRs are open at once, and you need less CI capacity.

Fewer unrelated failures to triage. A full run executes every test suite, including flaky tests in projects the change never touched. When only affected projects run, a red build is more likely to relate to the change itself. That cuts the time engineers spend rerunning jobs or investigating failures they did not cause.

Smaller failure surface when something breaks. The affected list, together with nx graph --affected, shows which projects were selected and through which edges. That narrows the search when a dependent project fails.

Compounding with the cache. Affected selection removes unrelated projects. The cache then skips selected tasks whose inputs have not changed, such as reruns on the same commit. Used together, they avoid the most redundant work.

These savings have offsetting costs:

  • Setting up the base SHA logic, fetch depth and fallback.
  • Declaring implicit dependencies.
  • Maintaining a scheduled full run.
  • Debugging the occasional surprising selection.

These are mostly one-time or low-frequency costs, while the savings recur on every change. The tradeoff is clearest in large workspaces with fine-grained projects and least compelling in small ones.

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