How does nx affected decide what changed?

nx affected answers one question: given two commits, which projects could behave differently? It runs a target such as build, test, or lint only for those projects and skips the rest. To get there it does three things.

  1. Diff two commits. Nx compares a base commit with a head commit using git. You pass them as --base and --head. If you omit them, Nx falls back to the default base branch configured in the workspace and to the current working tree. Whatever git reports as changed between the two points is the input to everything that follows.
  2. Map files to projects. Each changed file is matched to the project that owns it. Files outside any project, such as root configuration or dependency manifests, are handled by workspace-level rules. Depending on how inputs are configured, those rules can mark many projects as touched, or all of them.
  3. Walk the project graph. Nx then adds every project that depends on a touched project, directly or transitively. If a shared library changes, every service importing it is selected, even though none of the services' own files changed.

The base SHA decides correctness

The diff only sees what lies between base and head. If the base is too recent, real changes fall outside the range and the projects they affect never get built or tested. CI passes even though the code was never verified. If the base is too old, the run is still correct but rebuilds more than it needs to. A wrong base can therefore cause missed failures, not only slower pipelines.

Who benefits most

The payoff grows with the number of projects and the depth of the dependency graph. Backend and platform engineers who maintain the shared CI pipeline for a large monorepo gain the most, because a wrong base on one branch affects every team that relies on that pipeline.

  --base <sha>             --head <sha>
       |                        |
       +-----------+------------+
                   v
   +--------------------------------+
   | 1. git diff base..head         |
   |    -> list of changed files    |
   +--------------------------------+
                   |
                   v
   +--------------------------------+    +--------------------------+
   | 2. map files to projects       |<---| workspace-level rules    |
   |    libs/shared/* -> shared-lib |    | (root config, manifests) |
   +--------------------------------+    | can touch many or all    |
                   |                     +--------------------------+
                   v
   +--------------------------------+
   | 3. walk project graph          |
   |    add direct + transitive     |
   |    dependents                  |
   +--------------------------------+
                   |
                   v
   shared-lib --+--> api-service   (no own files changed)
                +--> worker        (no own files changed)
                   |
                   v
   +--------------------------------+
   | run build / test / lint only   |
   | for selected projects          |
   +--------------------------------+

nx affected diffs the base and head commits, maps changed files to owning projects (plus workspace-level rules), then adds every dependent project from the graph before running the target, so anything outside the base..head range is never seen.

Why do HEAD~1 and main-vs-main fail as a base SHA?

Getting the base SHA wrong in that shared pipeline rarely produces an error. It produces a quietly incomplete project list, which is worse.

HEAD~1 looks reasonable because it means "the commit before this one." On a push to main, that is only the full change set if the push contains exactly one commit. Rebase merges and direct pushes can land several commits at once, and HEAD~1 covers only the last of them. The second gap is failed runs. If commit A breaks the build and commit B fixes something unrelated, B's run compares against A. Projects that A changed are never rebuilt, so the failure is hidden rather than resolved. On pull requests, HEAD~1 ignores every earlier commit on the branch.

origin/main works on a pull request because the branch diverges from main. On a push to main, the checked-out commit is origin/main, so the diff is empty and nothing is affected. The merge base fails on main for the same reason: the merge base of main with itself is the current commit.

The base that is correct on main is the last commit whose workflow run succeeded. That diff covers every change since the pipeline was last known to be green, however many pushes or failures came in between.

Base choice Pull request Push to main Failure mode
HEAD~1 Wrong Wrong Misses multi-commit pushes and changes from failed runs
origin/main Correct Wrong Empty diff on main
Merge base with main Correct Wrong Resolves to HEAD on main, so the diff is empty
Last successful run on main Not applicable Correct Needs workflow history and enough fetched git history

The standard default for actions/checkout is a shallow clone, so older SHAs may not exist locally. Any base other than the immediate parent needs a deeper fetch.

What does nx-set-shas do on pull requests and pushes to main?

On a pull request, the action computes the merge base between the PR head and the target branch. This is the commit where the branch diverged from main. Diffing from there captures every change the PR introduces and nothing that landed on main afterward. A rebase moves the merge base forward with it.

On a push to main, the action queries the GitHub API for the most recent successful run of the current workflow on that branch and uses that run's commit as the base. Every commit since the last green build is therefore treated as unverified. If three pushes fail in a row, the fourth run still diffs against the last green commit, so projects broken in between are not skipped.

In both cases the action exports NX_BASE and NX_HEAD, which nx affected reads automatically. The resolved SHAs are also available as step outputs.

Reading run history requires the job's token to have actions: read. If a workflow restricts permissions and omits this scope, the API lookup fails.

The lookup is scoped to a specific workflow, not to "any green check on the commit." Renaming the workflow file creates a new workflow with no history. Splitting one workflow into several means a success in the lint workflow does not count as a base for the build workflow. Treat workflow file names as part of the CI contract.

When no successful run exists yet, such as in a new repository, a new branch, or a renamed workflow, the action has no trustworthy base. It falls back to an approximation and emits a warning instead of failing. The safe default is either to run every target in that case or to configure the action to fail so a human picks an explicit base.

How do you set up an Nx affected workflow in GitHub Actions?

A minimal workflow has five steps in a fixed order. The order matters because each one depends on the output of the one before it.

Triggers and checkout

Trigger the workflow on pull_request and on push with branches: [main]. These are the two events nx-set-shas handles differently. On a PR it uses the merge base with the target branch. On main it uses the last successful run.

Set fetch-depth: 0 on actions/checkout. The default fetches one commit, which leaves Git with only HEAD. In a clone that shallow, the commit nx-set-shas wants as a base is usually missing. A merge base cannot be computed, and the last green SHA on main is not present locally. Depending on the situation, the step either errors on an unknown revision or falls back to an approximation. The fallback is worse, because the job stays green while comparing against the wrong commit. Full history removes the problem.

Install, resolve SHAs, run targets

Install dependencies with your lockfile-respecting command, such as npm ci, so the Nx version matches local development.

Next, run nrwl/nx-set-shas. It exports NX_BASE and NX_HEAD as environment variables for later steps. On pushes it queries the GitHub API for workflow runs, so the job token needs read access to Actions.

Add a step that echoes $NX_BASE and $NX_HEAD. When an affected list looks wrong, this log line is the first thing you will check.

Finally, run nx affected -t lint test build. Nx reads NX_BASE and NX_HEAD from the environment, so you don't need to pass explicit --base and --head flags.

name: CI

on:
  pull_request:
  push:
    branches: [main]

permissions:
  # nx-set-shas reads past workflow runs on push to find the last green SHA
  actions: read
  contents: read

jobs:
  affected:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          # Full history so the merge base / last successful SHA exists locally
          fetch-depth: 0

      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: npm

      # Lockfile-exact install keeps the Nx version identical to local dev
      - run: npm ci

      # Exports NX_BASE and NX_HEAD for all later steps
      - uses: nrwl/nx-set-shas@v4

      # First thing to check when the affected list looks wrong
      - run: |
          echo "NX_BASE=$NX_BASE"
          echo "NX_HEAD=$NX_HEAD"

      # Nx reads NX_BASE/NX_HEAD from the environment; no --base/--head needed
      - run: npx nx affected -t lint test build

A minimal GitHub Actions workflow that checks out full history, installs dependencies, resolves base and head SHAs with nx-set-shas, logs them, and runs nx affected for lint, test and build.

How can you verify the affected project list is correct?

Before you trust the result, reproduce it outside CI. Copy the NX_BASE and NX_HEAD values from the workflow log, check out the same commit locally, and run nx show projects --affected --base=<NX_BASE> --head=<NX_HEAD>. If your local list differs from what CI built, the cause is usually a shallow clone or a stale local cache, not Nx's graph logic. Settle that first.

Then test the graph with changes whose outcomes you already know. On a throwaway branch, edit a leaf application that nothing depends on. Only that project should appear. Next, edit a widely shared library. Every consumer should appear, both direct and transitive. If a consumer is missing, an import is probably bypassing your path aliases, or a dependency only exists at runtime and Nx's static analysis cannot see it.

Some changes are invisible to the graph by default:

  • CI configuration. Files under .github/workflows belong to no project, so editing them can produce an empty affected list.
  • Root tooling files. Shared config, scripts and generators that live outside project roots have the same problem.
  • Environment-driven behavior. A build that reads an environment variable can change output without any file changing.

You close these gaps explicitly. Add root files to a sharedGlobals named input in nx.json and reference it from default, so a change there invalidates every project. Declare implicitDependencies in project.json for runtime links that Nx cannot detect from imports. Add { "env": "VAR_NAME" } entries to a target's inputs so that both caching and affected detection account for that variable.

#!/usr/bin/env bash
set -euo pipefail
# SHAs copied from the CI log lines that print NX_BASE / NX_HEAD (placeholders)
NX_BASE="3f2a9c1e7b4d5a6f8e9c0b1a2d3e4f5a6b7c8d9e"
NX_HEAD="9e8d7c6b5a4f3e2d1c0b9a8f7e6d5c4b3a2f1e0d"

# 1. Reproduce CI. Full history is required or the base commit is unreachable.
git fetch origin
if [ "$(git rev-parse --is-shallow-repository)" = "true" ]; then git fetch --unshallow; fi
git cat-file -e "${NX_BASE}^{commit}"   # exits non-zero if the base SHA is missing
git checkout --detach "$NX_HEAD"
npx nx reset                             # discard cached graph and daemon state
npx nx show projects --affected --base="$NX_BASE" --head="$NX_HEAD" | sort > /tmp/affected-local.txt
echo "Compare with the project list CI built:"; cat /tmp/affected-local.txt

# 2. Known-change probes on a throwaway branch. Commit each probe so the
#    base/head range is exact and nothing uncommitted leaks into the result.
git checkout -b verify-affected-probe

probe() {  # $1 = file to touch, $2 = file listing the expected projects
  echo "// affected probe" >> "$1"
  git commit -qam "probe: $1"
  npx nx show projects --affected --base=HEAD~1 --head=HEAD | sort > /tmp/actual.txt
  # Any diff output means the graph disagrees with your expectations
  diff -u <(sort "$2") /tmp/actual.txt && echo "OK: $1"
  git reset -q --hard HEAD~1
}

# Leaf app with no dependents: expect exactly one project
printf 'marketing-site\n' > /tmp/expected-leaf.txt
probe apps/marketing-site/src/main.ts /tmp/expected-leaf.txt

# Shared library: expect the library plus every direct and transitive consumer
printf 'shared-ui\nadmin-portal\ncheckout\nfeature-cart\n' > /tmp/expected-shared.txt
probe libs/shared/ui/src/index.ts /tmp/expected-shared.txt

git checkout -q --detach "$NX_HEAD" && git branch -D verify-affected-probe

A script that reproduces the CI affected list locally from the logged NX_BASE and NX_HEAD SHAs, then commits probe edits to a leaf app and a shared library and diffs the affected output against a hand-written list of expected projects.

When should you avoid relying on affected builds on main?

Even with a correct project graph, the base is only as trustworthy as your record of "successful" runs on main. Several situations break that assumption.

  • A red main widens scope on every push. nx-set-shas looks for the last successful workflow run, so while main is broken, each new push diffs against an increasingly old commit. Runs get slower until someone fixes the failure. If no successful run exists at all, the action falls back or errors depending on its configuration, which may not be what you expect.
  • False greens advance the base past untested code. A job that skips targets through an if: condition, or swallows failures with continue-on-error, still reports success. The next run treats that commit as verified and never revisits it.
  • Concurrency settings can cancel runs you wanted. A concurrency group with cancel-in-progress on main is safe for correctness, because cancelled runs do not count as successful. It can still drop runs you needed, such as a deploy. Overlapping runs may also compute against the same base and duplicate work.
  • API and token dependency. The action queries the GitHub API, so the token needs permission to read workflow runs. Restricted tokens, fork contexts or API outages can therefore change the result.
  • Stale cache replay. Even when the affected list is correct, a target whose inputs omit something it reads (a tool version, a generated file) restores an old result.
Situation Affected on main Full run
Routine merges, healthy main Good fit Wasteful
Release or tag build Risky Preferred
After CI config or toolchain changes Unreliable Preferred
Nightly safety net Not applicable Recommended

Schedule a periodic full run-many with caching disabled, and require one before releases. This catches anything that affected runs and cached results have hidden.

What are the alternatives, and how does this affect CI cost and engineering time?

Each alternative trades correctness against cost differently:

Approach How it selects work Main weakness
Always run everything Every project, every push Simplest to keep correct, but every run is the slowest run
Path filters on workflow triggers File globs decide whether a workflow starts Globs don't know the project graph, so dependents of a shared library get missed unless someone maintains the globs by hand
Manually tracked last-green tag or branch A script moves a ref after success and diffs against it You end up rebuilding nx-set-shas, including races when pushes land concurrently
Caching without affected run-many with cache hits skipping unchanged tasks Every task is still scheduled and checked against the cache, and correctness depends on accurate task inputs

Affected lowers average CI time, not worst-case time. A change to a widely shared library still pulls in most of the graph, so size runner capacity and job timeouts for a full run.

Illustrative estimate (assumed numbers, not a benchmark). Expected run time = Σ (share of changes × fraction of graph affected) × full run time.

Assume a 40-minute full run with this change mix:

  • 70% of changes touch leaf apps, affecting 10% of the graph.
  • 20% touch mid-level libraries, affecting 40%.
  • 10% touch core libraries, affecting 90%.

The expected run is (0.7×0.1 + 0.2×0.4 + 0.1×0.9) × 40 = 9.6 minutes.

Shift the core-library share to 50% and leaf apps to 30%, and the result becomes 22.4 minutes. The savings depend on where your changes land, not on Nx itself.

The engineering-time ledger has two sides:

  • Gain: faster feedback on most pull requests.
  • Cost: keeping namedInputs, implicit dependencies, and checkout depth correct, and occasionally debugging a project that should have run but didn't.

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 github actions 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.