How does Nx affected detection work in GitHub Actions, and why does it need full git history?
Nx "affected" CI runs tasks only for projects touched by a change. Nx takes two commits, a base and a head, computes the merge base between them, and lists the files that differ. It maps each changed file to the project that owns it, then walks the project graph to add every project that depends on those projects. Only that set gets lint, test or build. A change to a shared library therefore pulls in every app that imports it, while an edit to one service's handler stays local.
All of this depends on git being able to see both commits and the history that connects them. actions/checkout makes a shallow clone by default: one commit, no ancestors. When Nx asks git for the merge base of main and your branch, git has nothing to walk back through. You'll either see a hard failure (an unknown revision or a missing merge base) or a diff computed against the wrong point. The second case is worse because it is silent. Depending on what is missing, the job can mark everything as affected and waste the run, or mark too little and skip tests that should have caught a regression.
Set fetch-depth: 0 on checkout by default. Full history costs real time on very large or long-lived repositories. Partial fetches tuned to your branch patterns can reduce that cost, but they add a new way for the setup to break. Try them only after you have measured checkout time and found it to be a bottleneck.
The principle that governs the rest of this setup: every optimization layer must fail safe toward running more work. If the base cannot be resolved or the cache is in doubt, run more. A slow green build is recoverable. A fast green build that skipped the broken project is not.
name: ci
on:
pull_request:
push:
branches: [main]
jobs:
affected:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
# Full history so git can find the merge base of base and head.
# The default shallow clone has a single commit and no ancestors.
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
# Exports NX_BASE and NX_HEAD for the affected comparison.
- uses: nrwl/nx-set-shas@v4
- name: Run affected, or everything if the base is unusable
run: |
# Fail safe: if the merge base cannot be computed, do not trust
# a partial diff. Run every project instead of guessing.
if git merge-base "$NX_BASE" "$NX_HEAD" > /dev/null 2>&1; then
npx nx affected -t lint test build --base="$NX_BASE" --head="$NX_HEAD"
else
echo "No merge base for $NX_BASE..$NX_HEAD; running all projects"
npx nx run-many -t lint test build
fi
A GitHub Actions job that fetches full history, sets base and head SHAs with nx-set-shas, and falls back to running all projects when git cannot compute a merge base.
What does nx-set-shas do and how does it choose the base SHA?
nx-set-shas computes the two commits Nx compares and exports them as NX_BASE and NX_HEAD. Every later nx affected call in the job reads those variables, so the base-selection logic lives in one step and no script has to work it out again.
The base is chosen per event:
push to main
main: A ── B ── C ── D ── E (HEAD)
^ x x
last green run failed runs
NX_BASE = C NX_HEAD = E affected = changes in C..E
pull_request
main: A ── B ── C ── D
\
feature: F ── G (HEAD)
NX_BASE = merge-base(main, HEAD) = B NX_HEAD = G
For pushes, the base is the commit of the last successful run of the workflow on that branch, not the parent commit. A push that comes after failures still re-verifies everything that has not passed since the last green build. To find that run, the action queries the run-history API. The job therefore needs actions: read in its permissions block. If the token is restricted and lacks that scope, the lookup fails.
For pull requests, the base is the merge base with the target branch. The PR is evaluated only on its own changes, so commits that landed on main after the branch point are not counted.
When no successful run exists, the action falls back to a less precise commit. This happens in a new repository, after a workflow is renamed, or during a long red streak. A fallback to an older commit widens the affected set, which costs time but is safe. A fallback to the immediate parent narrows the set and can skip unverified changes. Decide which fallback you want and configure it on purpose.
Similarly, one broken commit on main keeps the base pinned until main is green again, so every push in between rebuilds a growing range. That is correct behavior, but expect CI time to grow during incidents.
Input names have changed over time. Check the action's README for the current options instead of relying on memorized flags.
+-------------------------------+
| nx-set-shas: which event? |
+-------------------------------+
push to main pull_request
v v
+--------------------------------+ +-----------------------------+
| look up last successful run | | merge-base(target, HEAD) |
| of this workflow on the branch | | ignores later main commits |
| (job needs actions: read) | | |
+--------------------------------+ +-----------------------------+
| | |
run found none found |
v v |
+--------------+ +-----------------------+ |
| base = its | | fallback commit | |
| commit SHA | | older: wider, safe | |
| (stays put | | parent: may skip work | |
| while red) | +-----------------------+ |
+--------------+ | |
| | |
+----------------------+-------------------+
v
+------------------------------+
| export NX_BASE and NX_HEAD |
+------------------------------+
v
+------------------------------+
| every nx affected call reads |
| them; older base = more work |
+------------------------------+
How nx-set-shas picks the base: push events use the last successful run's commit (via a run-history lookup that needs actions: read, with a fallback when no green run exists), pull requests use the merge base, and both paths export NX_BASE and NX_HEAD for every nx affected call.
How do you implement a basic Nx affected workflow in GitHub Actions?
A minimal workflow has five steps, in this order:
- Check out with full history. Set
fetch-depth: 0onactions/checkout. A shallow clone may not contain the base commit, and then the diff fails or covers the wrong range. - Set up Node. Use
actions/setup-nodeand pin the Node version your repository expects. - Install dependencies from the lockfile. Use
npm ci,pnpm install --frozen-lockfile, or your package manager's equivalent. A drifting lockfile can change the project graph, which makes affected results unreliable. - Run
nx-set-shas. It exportsNX_BASEandNX_HEADto later steps. - Run
npx nx affected -t lint test build.
For the permissions block, grant contents: read and actions: read. The action needs actions: read to query previous workflow runs. Without it, the action cannot find the last successful commit and falls back to a less precise base.
You usually don't need --base and --head, because nx affected reads NX_BASE and NX_HEAD from the environment. Passing the flags as well creates two sources of truth. If someone later edits one of them, the step can silently compare the wrong range.
To verify the setup, add a step that echoes NX_BASE and NX_HEAD into the log so anyone can check the compared range. Then run npx nx show projects --affected before the real targets. This dry run lists the selected projects without executing anything, which makes surprises easy to spot in review.
This setup fits Nx monorepos where CI duration or runner cost is a real constraint. A pull request that touches one library runs checks for that library and its dependents only. Developers get results sooner, spend less time switching tasks while they wait, and merge with fewer re-runs.
name: CI
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
actions: read # lets nx-set-shas query previous workflow runs
jobs:
affected:
runs-on: ubuntu-latest
steps:
# Full history so the base commit exists locally
- uses: actions/checkout@v4
with:
fetch-depth: 0
# Pin the Node version the repository expects
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
# Install exactly what the lockfile specifies
- run: npm ci
# Exports NX_BASE and NX_HEAD to later steps
- uses: nrwl/nx-set-shas@v4
# Verification: record the compared range in the log
- run: |
echo "NX_BASE=$NX_BASE"
echo "NX_HEAD=$NX_HEAD"
# Dry run: list selected projects without running any targets
- run: npx nx show projects --affected
# No --base/--head flags: nx affected reads NX_BASE/NX_HEAD from env
- run: npx nx affected -t lint test build
A minimal GitHub Actions workflow that checks out full history, installs from the lockfile, sets NX_BASE and NX_HEAD with nx-set-shas, logs the compared range, previews affected projects, and then runs lint, test and build only on those projects.
How does the full setup work, end to end?
Every run of the workflow above goes through the same chain of steps:
- Trigger. A
pushtomainor apull_requestevent starts the workflow. The event type determines how the base commit is chosen. - History.
actions/checkoutwithfetch-depth: 0makes both the base and head commits, and the history between them, available locally. - Range selection.
nx-set-shaspicks the base. For pushes it uses the commit of the last successful run on the branch. For pull requests it uses the merge base with the target branch. It exports the result asNX_BASEandNX_HEAD. - Change detection.
nx affectedasks git for the files changed between the merge base andNX_HEAD. It maps each file to its owning project, or marks everything affected when a global input such as the lockfile ornx.jsonchanged. - Graph expansion. Nx walks the project graph and adds every project that depends, directly or transitively, on a changed project.
- Task execution and caching. Nx runs the requested targets for that set. Before running each task it computes a hash from the task's declared inputs. If a matching hash exists in the cache, Nx replays the stored output instead of running the task.
- Reporting. A single aggregate job, covered in the branch protection section below, turns the per-job results into one required check.
Each layer narrows the work, and each one has a fail-safe path that widens the work when its inputs are in doubt. If the merge base is missing, run everything. If no green run exists, fall back to an older base. If a cache key misses, run the task.
Who should use Nx affected CI in GitHub Actions?
This setup is aimed at teams that already run an Nx workspace with several projects and use GitHub Actions as their CI system. It pays off most when these conditions hold:
- A full run is slow enough to hurt. If running every target takes long enough that developers switch tasks while they wait, cutting the work per PR has a direct effect on how they work.
- Most PRs touch a small part of the graph. Affected detection saves work only when the typical change leaves most projects untouched. A workspace where nearly every PR edits a shared core library will see little benefit.
- The project graph is trustworthy. Dependencies between projects are declared through imports,
implicitDependenciesornamedInputs, and someone owns keeping them accurate. - Runner minutes cost real money or capacity. Teams on metered or self-hosted runners with limited concurrency get the clearest return.
It is a poor fit for small repositories where a full run is already quick, for workspaces whose graph is known to be incomplete, and for release pipelines. The last section covers these cases in more detail.
The setup also asks something of the people maintaining it. One engineer should understand how nx-set-shas picks the base, how the cache keys are built and how the aggregate required check works. Most failures in affected CI come from someone changing one of those pieces without knowing how it interacts with the others.
How can affected CI save engineering time?
The savings come from three places:
- Less work per run. Projects outside the affected set run no lint, test or build tasks at all. Inside the set, cache hits replay results instead of recomputing them.
- Shorter feedback loops. A PR that finishes sooner means less waiting and less context switching. Failures are also reported for the projects that actually changed, which makes them faster to diagnose.
- Fewer queued runs. When each run uses fewer runner minutes, concurrent PRs spend less time queued behind each other, especially on runner pools with limited concurrency.
The following worked example shows how to reason about the size of the savings. It is an illustrative estimate built from assumed inputs, not a measurement:
- Assumed full run (
run-manyon all targets): 30 minutes of task time on one runner. - Assumed fixed overhead per run (checkout, install, project graph): 4 minutes.
- Assumed typical PR affects about 20% of the task time.
- Assumed volume: 50 CI runs per day across the team.
Under these assumptions, a full run takes roughly 4 + 26 = 30 minutes, and an affected run takes roughly 4 + (0.2 × 26) ≈ 9 minutes. Each run saves about 21 minutes, which comes to roughly 1,000 runner minutes per day at the assumed volume. The fixed 4 minutes does not shrink, so the smaller the affected set, the larger the share of each run that is overhead. That is why install caching matters more as affected detection gets better.
To estimate your own savings, measure your real full-run time, overhead and the average share of tasks affected per PR. Use nx show projects --affected across a sample of recent PRs to get that share. Subtract the ongoing costs before deciding: the periodic full run, the time spent maintaining implicitDependencies, and the occasional investigation when the graph missed an edge.
Should you use static or dynamic matrix jobs for Nx affected CI?
There are three common ways to structure the jobs, and the right choice depends on how many projects a typical pull request affects.
A single job runs nx affected -t lint test build --parallel=3. Nx schedules tasks across processes on one runner, so checkout, install and project graph computation happen once. A static matrix creates one job per target. It is easy to read and shows a separate check for each target, but every job repeats checkout, dependency install and graph computation before doing any real work. A dynamic matrix adds a setup job that runs nx show projects --affected --json, publishes the result as a job output, and passes it to fromJSON in the next job's strategy.matrix.
The dynamic matrix has one sharp edge. If no projects are affected, fromJSON('[]') produces an empty matrix and GitHub Actions fails the workflow. To avoid this, have the setup job also output a boolean such as has-projects, and add an if: condition on the matrix job that checks it. A required check can still end up skipped instead of passing, which section 6 covers.
| Approach | Setup overhead | Runners | Log readability | Best fit |
|---|---|---|---|---|
| Single job | Once | 1 | One long log | Small to medium affected sets |
| Static matrix | Per target | One per target | Clear per target | Few targets, slow install acceptable |
| Dynamic matrix | Setup job plus each project | One per project | Fragmented | Large affected sets with long tasks |
For most pull requests, the single job finishes first. The dynamic matrix only pays off when per-project task time is much larger than the cost of waiting for the setup job and installing dependencies on every runner.
name: CI
on: pull_request
jobs:
setup:
runs-on: ubuntu-latest
outputs:
projects: ${{ steps.affected.outputs.projects }}
has-projects: ${{ steps.affected.outputs.has-projects }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # full history so Nx can diff base..head
- uses: actions/setup-node@v4
with: { node-version: 20, cache: npm }
- run: npm ci
- uses: nrwl/nx-set-shas@v4 # sets NX_BASE / NX_HEAD
- id: affected
run: |
# Compact JSON array of affected project names, e.g. ["api","web"]
projects=$(npx nx show projects --affected --json | jq -c '.')
echo "projects=$projects" >> "$GITHUB_OUTPUT"
# Guard: an empty matrix is an error, so expose a boolean instead
if [ "$(echo "$projects" | jq 'length')" -gt 0 ]; then
echo "has-projects=true" >> "$GITHUB_OUTPUT"
else
echo "has-projects=false" >> "$GITHUB_OUTPUT"
fi
run:
needs: setup
# Skip (rather than fail) when nothing is affected
if: needs.setup.outputs.has-projects == 'true'
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
project: ${{ fromJSON(needs.setup.outputs.projects) }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: 20, cache: npm }
- run: npm ci # repeated on every matrix runner: the per-job cost
- run: npx nx run-many -t lint test build -p ${{ matrix.project }}
A dynamic matrix where a setup job emits the affected project list plus a has-projects flag, so the matrix job is skipped instead of failing when no projects are affected.
How should you cache dependencies and the Nx cache in GitHub Actions safely?
Keep two caches separate. The dependency cache (the package manager store or node_modules) is keyed on the lockfile hash, so it hits exactly whenever dependencies are unchanged. The Nx local cache directory needs a key that changes on every commit, such as one including the SHA, with restore-keys prefixes that fall back to the most recent partial match. Exact hits on that key are rare because each commit produces a new key. The useful case is restoring a nearby snapshot and letting Nx reuse whichever task hashes still match.
GitHub scopes caches to the branch that wrote them. A branch can read its own caches and those from its base branch and the default branch, but not caches from sibling branches. A new branch therefore starts cold unless main has a recent entry. Each repository has a total size limit. Unused entries expire, and the oldest entries are evicted when the repository goes over the limit. A large Nx cache can take longer to upload and download than the work it saves, so measure restore time and task hit rates before you assume the cache helps.
Correctness depends on accurate hashes. Declare env and runtime inputs, such as a build-mode variable or node --version, in namedInputs so a restored artifact never replays a result built under different conditions. Never hand-edit or prune cache contents in CI, because Nx trusts what it finds there.
Fork PRs under pull_request write caches only to their PR scope, which main cannot read. pull_request_target runs with the base repository's context. If that workflow checks out and runs fork code, the fork code can write caches that main later restores. Finally, parallel matrix jobs in one run each restore the same earlier snapshot, so they never share local cache results with each other.
How do you make branch protection work with skipped affected jobs?
Required status checks in GitHub are matched by check name, and that causes two problems for affected-only pipelines.
The first is the stuck PR. If a required job is never created, GitHub waits indefinitely for a check that will never report. This happens when a workflow is filtered out by paths, or when a dynamic matrix job is guarded off because nothing was affected. Matrix jobs make this worse because their check names include the matrix values. When the set of affected projects changes, so do the names, and a required check pinned to test (api) may simply not exist on the next PR.
The second is the false green. A job that is skipped through an if: condition reports as "Skipped", and branch protection treats a skipped required check as passing. If a dependency fails, downstream jobs are skipped by default. A required check attached to one of those jobs can then pass on a PR that actually failed.
The fix is to require one check that always runs and always tells the truth. Add a ci-result job that lists every real job in needs, sets if: always() so it runs regardless of upstream outcomes, and inspects needs.*.result. Fail the job if any result is failure or cancelled. Treat success and skipped as acceptable, because a skip there means "not affected". Make ci-result the only required check, and leave the per-project jobs unrequired.
This adds a job whose only purpose is bookkeeping. You also have to keep its needs list in sync, because any job missing from it is silently ignored. That cost is worth paying, because without this job branch protection cannot reliably block failing PRs or let unaffected ones through.
When should you avoid affected-only CI, and what are the alternatives?
Affected detection fails in two directions. Changes to global inputs, such as the root nx.json, tsconfig.base.json, the lockfile or the workflow file itself, usually mark every project affected. You then pay for a full run while still carrying the affected setup. The more dangerous case is an implicit dependency that was never declared, such as a shared fixture directory, a generated schema or a script read at runtime. The graph does not see the edge, so the dependent project is skipped and the PR goes green.
Avoid affected-only CI in three situations. The first is a small repository where a full run takes a few minutes. The second is a workspace whose project graph you do not trust. The third is a release pipeline, where you want a full validation of exactly what ships.
Alternatives include the following:
- Always
nx run-many. Run every target on every PR. This is the simplest option and the most correct, but it costs the most. - Periodic full run on main. Keep affected runs for PRs, and add a
scheduleorworkflow_dispatchtrigger that runs everything. This catches drift from missing dependencies. - Remote caching. Share task outputs between CI and developers. Because restored artifacts are trusted as if they were built locally, restrict write access to protected branches. Treat a cache that fork PRs can write to as a supply-chain risk.
| Approach | CI cost | Correctness risk | Maintenance effort |
|---|---|---|---|
| Affected only | Low | Medium–high | Medium |
| Always run-many | High | Low | Low |
| Affected + periodic full run | Low–medium | Low–medium | Medium |
| Remote cache | Low | Depends on cache trust | Medium–high |
Verification checklist
- Compare the median full-run time against the time spent maintaining
implicitDependencies. - Confirm that the scheduled full run fails loudly and that someone owns its failures.
- Check that changes to the lockfile and the workflow trigger the expected scope.
- Verify that cache writes are limited to trusted branches.
- Make release workflows bypass affected detection.
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, 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.