What does nx affected compare, and why does the base SHA matter?
This section is for backend and platform engineers who run Nx monorepos in GitHub Actions and want nx affected to build and test the right projects on every pull request and every push to main.
nx affected answers one question: which projects could be impacted by the changes between two points in history? It works in two steps. First, it asks git for the files that changed between a base and a head. When you supply both, Nx diffs those two commits, using their merge base so that unrelated commits on the base branch are excluded. When you omit the head, Nx compares the base against your working tree, which picks up uncommitted changes. Second, it maps each changed file onto the project graph. The file is assigned to the project that owns it, and that project's dependents are pulled in transitively.
You supply the range with the --base and --head flags or the NX_BASE and NX_HEAD environment variables. If you give neither, the base falls back to the default base branch configured in nx.json.
The base is where mistakes cost the most, because Nx never reports that the range was wrong. A base that is too recent drops real changes, so broken projects are skipped and CI passes. A base that is too old pulls in changes from other work, so CI runs far more than it needs to. In both cases you get a plausible project list and a green or red check, with no warning.
A correct base only gets you the correct file list. It does not fix an incomplete project graph. Missing implicit dependencies, root configuration files, lockfiles, or shared tooling that is not declared as a named input can still change behavior without marking the right projects as affected.
npx nx show projects --affected --base=origin/main --head=HEAD
export NX_BASE=origin/main
export NX_HEAD=HEAD
npx nx affected -t test
unset NX_HEAD
npx nx show projects --affected --base=origin/main
unset NX_BASE
echo "Base = HEAD~1 (too recent if the PR has several commits):"
npx nx show projects --affected --base=HEAD~1 --head=HEAD
echo "Base = merge base with main (the full PR range):"
npx nx show projects --affected --base="$(git merge-base origin/main HEAD)" --head=HEAD
git diff --name-only "$(git merge-base origin/main HEAD)" HEAD
Shows the --base/--head flags and NX_BASE/NX_HEAD variables that set the comparison range for nx affected, and how a too-recent base quietly shrinks the affected project list.
Who should use this setup?
This setup is for teams that run an Nx workspace with more than a handful of projects in GitHub Actions, where running every target on every change is slow enough to delay reviews. It applies most directly to:
- Platform and CI owners who maintain the shared workflow files and need affected detection to be correct for both pull requests and pushes to main.
- Application and library teams in a shared monorepo who want PR checks to cover what they changed, plus everything downstream of it, without waiting on unrelated projects.
- Teams that deploy from main, because the push-to-main base decides whether every landed commit has actually been verified.
It is less useful for very small workspaces, where a full run-many finishes quickly and the extra moving parts of base selection are not worth it. It is also a poor fit if your project graph is known to be incomplete, for example when many tasks read undeclared files or environment variables. In that case, fix the inputs first, because affected detection can only be as accurate as the graph it walks.
How does it work end to end?
The pieces in this article fit together into one pipeline:
- Checkout with enough history. The job fetches the full commit graph (
fetch-depth: 0, optionally as a blobless partial clone) so that any base commit and merge base exist locally. - Choose the base and head for the event. On a pull request, the base is the merge base of the PR head and the target branch, and the head is the PR commit. On a push to main, the base is the commit of the last successful run of the workflow on main, and the head is the pushed commit. You can compute these yourself or let
nx-set-shasdo it. - Export them once. The pair is written to
NX_BASEandNX_HEADso every later step reads the same range. - Compute changed files. Nx asks git for the files that differ between base and head.
- Walk the project graph. Each changed file is mapped to its owning project, and dependents are added transitively. Changes to global inputs, such as root config or the lockfile, can mark many or all projects as affected.
- Run targets on the affected set.
nx affected -t lint,testandbuildexecute only for those projects. - Replay cached results where possible. Tasks whose input hash matches a stored result are replayed from the local or remote cache instead of re-executed.
The later sections cover each step in detail: why the default checkout breaks step 1, which SHAs to pick in step 2, how nx-set-shas automates steps 2 and 3, and how to check steps 4 and 5 when results look wrong.
Why does the default actions/checkout break affected detection?
By default, actions/checkout fetches a single commit (fetch-depth: 1). On a pull_request event that commit is usually the synthetic merge commit GitHub creates for the PR, and nothing else. The runner has no parent commits, no merge base, and often no object for the base SHA you pass to Nx. Nx delegates to git to resolve the base, find the merge base with HEAD, and list changed files. Each of those steps needs history the shallow clone does not have.
The reliable fix is fetch-depth: 0, which fetches all history for all branches and tags. The base commit and the merge base are then guaranteed to exist locally, whichever SHA you choose.
A bounded depth, such as the last 50 or 100 commits, works only if every base you will ever compare against falls inside that window. That holds for short-lived PRs on a quiet repository. It fails for long-running branches, for busy main branches, and for any strategy that diffs against the last successful CI run, which can be arbitrarily old.
A fetch that is too shallow fails in one of two ways:
- Outright failure. Git reports an unknown revision or bad object, and the job errors.
- Quiet degradation. The base resolves, but the merge base sits beyond the shallow boundary. The diff is then computed against the wrong commit. Usually far more projects are marked affected, and occasionally the wrong set is. Nothing in the logs flags it.
Full history has a real cost. On large or long-lived repositories, cloning every commit and tree can add noticeable time to every job. Two mitigations help:
- Fetch full history only in the job that computes affected projects, and pass the result to the other jobs.
- Use a partial clone that skips file contents for historical commits while keeping the commit graph intact.
name: ci
on:
pull_request:
push:
branches: [main]
jobs:
affected:
runs-on: ubuntu-latest
outputs:
projects: ${{ steps.nx.outputs.projects }}
steps:
- uses: actions/checkout@v4
with:
# Full commit graph so the base SHA and merge base exist locally.
fetch-depth: 0
# Partial clone: skip historical file contents, keep commits and trees.
filter: blob:none
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm ci
- id: nx
env:
# PRs compare against the target branch; pushes against the previous tip.
BASE: ${{ github.event.pull_request.base.sha || github.event.before }}
run: |
echo "projects=$(npx nx show projects --affected --base="$BASE" --head=HEAD --json)" >> "$GITHUB_OUTPUT"
test:
needs: affected
runs-on: ubuntu-latest
steps:
# Default shallow checkout is fine here: no history needed.
- uses: actions/checkout@v4
- run: echo 'Affected: ${{ needs.affected.outputs.projects }}'
A workflow that fetches full history as a blobless partial clone only in the job that computes affected projects, then passes the list to downstream jobs that keep the cheap single-commit checkout.
Which base SHA should you use for pull requests?
With history available, the next question is which commit to diff against. For pull requests, use the merge-base of the PR head and the target branch, not the target branch's current tip.
Diffing against the tip of main compares two lines of history that have diverged. Every commit merged to main since the branch was cut shows up as a difference, even though the PR didn't touch those files. If a colleague merged a change to a shared library an hour ago, your PR now "affects" everything that depends on it, and the affected set grows with the age of your branch rather than with the size of your change. The merge-base is the last commit both lines share, so the diff contains only what the branch introduced.
On pull_request events, actions/checkout does not check out your branch by default. It checks out a synthetic merge commit that GitHub creates by merging the PR head into the target branch. In that checkout, HEAD and GITHUB_SHA point at the merge commit, not at your last pushed commit. The event payload carries pull_request.head.sha (your commit) and pull_request.base.sha (the target branch tip recorded when the event fired). Choose these values deliberately. Using HEAD without thinking about it means testing a commit that nobody authored.
| Comparison | What it reflects | Stability |
|---|---|---|
| Merge-base → PR head | Exactly what the branch changed | Fixed until you push |
| Merge-base → merge commit | Branch changes as integrated with current main |
Shifts as main moves |
main tip → PR head |
Branch changes plus inverted unrelated main changes |
Shifts as main moves; inflated |
The merge commit catches integration breakage, such as a rename on main that your branch still calls. The cost is results that change on re-runs when the branch itself has not changed.
name: affected
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
# Check out the commit the author pushed, not GitHub's synthetic merge commit.
ref: ${{ github.event.pull_request.head.sha }}
# Full history so git merge-base can find the shared ancestor.
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- name: Compute merge-base
env:
# Pass event values through env vars instead of interpolating them into the script.
BASE_SHA: ${{ github.event.pull_request.base.sha }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
run: |
# The last commit shared by the branch and main. Diffing from here
# excludes unrelated commits merged to main after the branch was cut.
MERGE_BASE=$(git merge-base "$BASE_SHA" "$HEAD_SHA")
echo "NX_BASE=$MERGE_BASE" >> "$GITHUB_ENV"
echo "NX_HEAD=$HEAD_SHA" >> "$GITHUB_ENV"
- name: Test affected projects
# Diff merge-base -> PR head: the result reflects only what this branch changed
# and stays the same on re-runs until someone pushes to the branch.
run: npx nx affected -t test --base="$NX_BASE" --head="$NX_HEAD"
A pull_request workflow that checks out the PR head commit instead of the synthetic merge commit, computes the merge-base from the event payload's base and head SHAs, and passes both to nx affected.
Why is HEAD~1 the wrong base for pushes to main?
On a push to main, the question changes. You are no longer asking "what does this PR change?" but "what has landed on main that CI has not yet verified?" HEAD~1 answers a narrower question: what changed in the latest commit.
That gap shows up as soon as a run does not finish green. Suppose commit A breaks a test in payments and its run fails. Commit B, which touches only docs, lands on top. With HEAD~1 as the base, B's run sees only docs as affected and passes, so main looks healthy while payments is still broken. The same thing happens when a run is cancelled by a newer push or skipped by a path filter. It also happens when a single push contains several commits, because HEAD~1 covers only the last of them.
Using the SHA of the last successful workflow run on main closes the gap. Everything since the last known-good state is rebuilt and retested.
Base for main |
What gets verified | Failure mode |
|---|---|---|
HEAD~1 |
The latest commit only | Commits from failed, cancelled or skipped runs are never re-checked |
| Last successful run | Every commit since the last green run | Larger affected set after a run of failures |
The trade-off is real. After several red builds, the next run may cover many more projects and take noticeably longer. That costs CI minutes. The alternative is deploying code that no pipeline has verified, which is usually the worse outcome.
Nx's computation cache absorbs much of the extra cost. Tasks are keyed by a hash of their inputs, so projects in the wider affected set whose inputs match a previous run replay cached results instead of re-executing. On ephemeral runners, this only helps if the cache is restored between runs or shared remotely. Otherwise every run starts with an empty cache and executes the full affected set.
How does nx-set-shas work, and how do you implement it in a workflow?
nx-set-shas decides the base and head for you and exports them as NX_BASE and NX_HEAD. Nx reads these variables when --base and --head are not passed explicitly, so every later step in the job uses the same pair without extra wiring.
The action branches on the triggering event:
- Pull requests: head is the checked-out commit. Base is the merge base between that commit and the target branch, which is the fork point described earlier.
- Pushes to main: the action queries the GitHub API for the most recent successful run of the same workflow on the main branch. It uses that run's commit as the base, so every commit since the last green build counts as affected. If no successful run exists, as on a new repository or a renamed workflow, it falls back to the parent commit. Recent releases can be configured to fail instead, but check the action's documentation for the inputs your version supports.
The API lookup needs read access to workflow run history. The action uses the job's GITHUB_TOKEN, so the job or workflow must grant actions: read. If you declare a permissions block, it replaces the defaults, and any scope you omit is denied. Check both that block and the repository's default workflow permissions setting. A missing scope usually shows up as a 403 in the action's log.
The reference workflow has four phases:
- Check out the full history with
fetch-depth: 0. - Compute the SHAs with
nx-set-shas. - Run the affected tasks. Run
nx affected -t lint, thentest, thenbuild. Alternatively, run all three in a single invocation. - Leave the SHAs alone. Never recompute or override them mid-job. If each step used a different pair, the lint, test and build results could describe different sets of projects.
name: CI
on:
pull_request:
push:
branches: [main]
permissions:
contents: read # checkout
actions: read # nx-set-shas reads workflow run history for the push base
jobs:
affected:
runs-on: ubuntu-latest
steps:
# 1. Full history so the base commit exists locally.
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
# 2. Compute base/head once. Exports NX_BASE and NX_HEAD for later steps.
- uses: nrwl/nx-set-shas@v4
# 3. No --base/--head flags: Nx reads NX_BASE and NX_HEAD,
# so all three steps evaluate the same set of affected projects.
# 4. Do not recompute or override the SHAs after this point.
- run: npx nx affected -t lint
- run: npx nx affected -t test
- run: npx nx affected -t build
A reference workflow that checks out full history, grants actions: read so nx-set-shas can find the last successful main run, and runs lint, test and build with nx affected against the same NX_BASE and NX_HEAD.
How can you verify the base SHA is correct and debug surprising results?
Before any lint, test or build step runs, print the resolved NX_BASE and NX_HEAD values alongside the short commit subject for each. A SHA alone is hard to judge at a glance. A subject line tells a reviewer immediately whether the base is the merge-base with main, the last green commit, or something unexpected like a commit from three weeks ago.
Next, run nx show projects --affected as its own early step, using the same base and head. This lists the projects Nx considers affected without executing any targets, so it costs seconds. Put git diff --name-only for the identical range next to it. The two outputs should line up: every changed file should map to a listed project, or to a global input such as a root config or lockfile that explains a broad result. If a file changed but its project is missing, the range or the project graph is wrong. If dozens of projects appear for a one-line change, the base is probably too old, or a shared input was touched.
Treat the nx-set-shas output as something to monitor, not something you set once and trust. A renamed workflow file, deleted run history, or a token without permission to read workflow runs can all stop it from finding the last successful run. When that happens, it falls back to a less precise base, and the job still passes. Logging the resolved base on every run turns that silent drift into something visible. You catch it in one log line instead of an afternoon spent tracing why a broken project never ran its tests.
How can it save engineering time?
A correct base saves time in three places.
Shorter CI runs. With the right range, each run executes targets only for the projects a change can reach, instead of the whole workspace. Here is an illustrative estimate with assumed inputs, not a measurement: assume a workspace of 40 projects, where each project's test target takes 2 minutes, and a PR that changes one library with 4 dependents. A full run executes 40 test tasks, about 80 minutes of task time. An affected run with a merge-base base executes 5, about 10 minutes. Parallelism changes the wall-clock time but not the ratio of work. Cache hits reduce the affected run further. If the base were the tip of a busy main instead, unrelated merged changes would inflate the affected set and erase part of that saving.
Fewer false greens to investigate. A base that is too recent, such as HEAD~1 on main, lets a broken project pass unnoticed until someone hits the failure later, often in a deploy or on another team's branch. Tracing that back means working out which commit broke it and why CI never ran the tests. Diffing from the last successful run, and logging the resolved SHAs, removes that class of investigation.
Less time maintaining CI logic. Computing the SHAs once with nx-set-shas, exporting them as NX_BASE and NX_HEAD, and reusing them in every step leaves one place to change and one log line to check. Teams avoid hand-written base logic duplicated across workflows, which tends to diverge as workflows are copied and edited.
These savings depend on the project graph being accurate. If tasks read undeclared inputs, affected runs and cache hits can skip work that should have run, and the time saved in CI is spent later on debugging.
When should you avoid relying on affected alone, and what are the alternatives?
Some situations break the assumptions that affected detection relies on.
- First runs with no successful history. A new repository or a renamed workflow has no green run to anchor to. Fall back to the merge-base with the default branch, or run everything. Failing open to an empty affected set is the worst outcome.
- Force-pushed PR branches. A rewrite can orphan the previous head commit, so any base derived from "the last commit we tested on this branch" may no longer exist. Compute the PR base from the target branch's merge-base, which survives rewrites.
merge_groupevents. Merge queues test a temporary commit built on top of other queued changes. Its base and head come from the event payload, not from a pull request. Reusing PR logic here compares the wrong commits.
In each case, make the fallback explicit and log it. When the base cannot be resolved, widen the scope rather than skip.
Beyond per-event fallbacks, there are three broader options.
| Option | CI cost | Correctness |
|---|---|---|
run-many over all projects |
Highest on every run | Highest; nothing is skipped |
| Nightly full run as a safety net | One full run per day | Catches missed breakage within a day, not per PR |
| Conservative base plus remote caching | Low when the cache hits | Only as good as your declared task inputs |
The third option depends on correct input declarations. Remote caching returns stored results for tasks whose inputs hash identically. If a task reads an environment variable or file it never declared, a stale cache hit reports success for code that would now fail.
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 base sha, 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.