How does Nx affected work in GitHub Actions?
nx affected answers one question: which projects could have been changed by the commits in a given range? It answers in three steps.
- Diff the range. Nx asks git for the files that changed between a base commit and a head commit. In a pull request, base is usually where the branch diverged from main. Head is the commit being built.
- Map files to projects. Every file belongs to a project root in the project graph, so each changed path becomes an owning project. Some workspace-level files, such as root configuration, can mark many or all projects as affected.
- Add dependents. Nx walks the graph in reverse and adds every project that depends on a changed one. If
libs/authchanges, theapiandworkerapps that import it are affected too, even though none of their files changed.
Commit range (base → head) → changed files (
libs/auth/src/token.ts) → project graph (auth←api,auth←worker) → affected set {auth,api,worker}
Running nx affected -t test then runs the test target only for that set.
This matters to backend and platform engineers who run Nx monorepos in GitHub Actions. As a repo grows, rebuilding and retesting every project on every push gets slow and expensive. With affected, a change to one service tests that service and its consumers and skips the rest.
The weak point is that Nx trusts the range it is given. It does not check whether the base commit is a sensible one. If the base is too recent, CI skips projects it should have tested. If the base is too old, CI runs nearly everything and the speedup disappears. Whatever sets the base and head SHAs controls what your pipeline actually verifies.
+----------------------------------------------------------------+
| 1. COMMIT RANGE |
| base (merge-base with main) ------------> head (PR commit) |
+----------------------------------------------------------------+
|
| diff files between base and head
v
+----------------------------------------------------------------+
| 2. CHANGED FILES |
| libs/auth/src/token.ts |
+----------------------------------------------------------------+
|
| map each path to its owning project
v
+----------------------------------------------------------------+
| 3. PROJECT GRAPH (walk edges in reverse to find dependents) |
| |
| +-----+ depends on +------+ |
| | api |--------------->| | |
| +-----+ | auth | <-- owns changed file |
| +--------+ | | |
| | worker |------------>| | |
| +--------+ +------+ |
+----------------------------------------------------------------+
|
v
+----------------------------------------------------------------+
| 4. AFFECTED SET { auth, api, worker } |
| nx affected -t test -> runs test for these 3 projects only|
+----------------------------------------------------------------+
Nx affected diffs the base-to-head range, maps each changed file to its owning project, then walks the project graph in reverse to add dependents, so a change in libs/auth affects auth, api and worker.
Why is HEAD~1 the wrong base SHA for pushes to main?
…CI actually tests, and HEAD~1 is the most common way to get that wrong on main.
HEAD~1 assumes every push adds exactly one commit. That holds for squash merges, but not for rebase merges or direct pushes, where a single push can land several commits. With HEAD~1 as the base, Nx diffs only the last of them, and projects touched by the earlier commits are never considered.
The more dangerous gap is failure. Suppose push A breaks billing-api and its run fails. Push B changes only web-app. With HEAD~1, run B tests web-app, passes, and main shows green while billing-api stays broken. No later run covers it unless someone touches billing-api again.
The fix is to use the commit of the last successful CI run on the branch as the base. Every change since the last green run counts as untested. Failed or cancelled runs widen the next diff instead of dropping changes.
A plain merge-base is correct for pull requests, where you want the PR's changes relative to its target branch. On a push to main, though, the merge-base of HEAD and main is HEAD itself, so the diff is empty.
| Base strategy | Catches | Misses |
|---|---|---|
HEAD~1 |
Single-commit pushes, squash merges | Multi-commit pushes; changes from earlier failed runs |
| Merge-base with target | All PR changes vs. target branch | Everything on pushes to main (empty diff) |
| Last successful run | All changes since the last green run, including failed runs | Nothing in the diff; uses a larger base after failures, which costs more CI time |
What does nx-set-shas do?
The action is a step that runs before your Nx commands and writes two environment variables, NX_BASE and NX_HEAD, for later steps to read. Its value comes from how it picks the base.
On pushes to the main branch, it calls the GitHub API to find the most recent successful run of the same workflow on that branch. It uses that run's commit as NX_BASE and the current commit as NX_HEAD. If the last two pushes failed, the diff still covers everything since the last green run, so fixes and the changes that broke the build are verified together.
On pull requests, the base comes from the target branch: the point where the PR diverged from it. The PR is compared against what it will merge into, not against its own previous commit.
When no successful run exists, such as a new repository, a renamed workflow, or a branch whose runs have all failed, the action falls back to a default, typically the previous commit. That fallback can quietly under-test, so choose the behavior on purpose. Depending on the version, you can fail the job instead or supply your own fallback SHA.
Two configuration details trip teams up:
- The job's token needs
actions: readpermission to query workflow runs. With restrictive default permissions, the lookup fails. - If your default branch isn't
main, set the main branch name input. Otherwise the push-to-main logic never runs.
Input names and defaults have changed across releases. Check the action's README for the version you pin.
How do you set up a minimal Nx affected CI workflow?
The workflow has five steps, and each one prevents a specific failure.
Triggers and permissions
Trigger on push to main and on pull_request. Pull requests compare against the merge base with the target branch. Pushes to main compare against the last commit that passed CI. Set permissions to contents: read and actions: read. Checkout needs contents: read. nx-set-shas needs actions: read because it queries the GitHub API for previous workflow runs to find the last successful one. Without that permission, the lookup fails or comes back empty.
Checkout with full history
actions/checkout defaults to a shallow clone containing only the triggering commit. Set fetch-depth: 0 to fetch full history. Nx runs git diff between the base and head SHAs, and both commits must exist locally.
Node and a locked install
Set up Node, then run npm ci instead of npm install. npm ci installs exactly what the lockfile specifies. CI then runs the same Nx version and plugins as your local machine, so project graph computation matches.
Compute SHAs, then run affected
Run nx-set-shas after checkout. It exports NX_BASE and NX_HEAD for the steps that follow. Then run npx nx affected -t lint test build.
The shallow-clone failure
If you forget fetch-depth: 0, one of two things happens:
- Loud failure: git reports a bad revision or missing object because the base SHA was never fetched.
- Silent failure: the base resolves to a commit that is not the one you intended. CI goes green but tests the wrong set of projects.
The silent case is worse because nothing fails. Read the base SHA in the logs on your first few runs and confirm it is the commit you expect.
name: CI
on:
push:
branches: [main] # base = last successful CI run on main
pull_request: # base = merge base with the target branch
permissions:
contents: read # actions/checkout needs this
actions: read # nx-set-shas queries previous workflow runs
jobs:
main:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # full history so the base SHA exists locally for git diff
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
# Install exactly what the lockfile pins, so CI uses your local Nx version and plugins
- run: npm ci
# Exports NX_BASE and NX_HEAD for the steps that follow
- uses: nrwl/nx-set-shas@v4
# Print the SHAs on early runs to catch a silent wrong-base fallback
- run: |
echo "NX_BASE=$NX_BASE"
echo "NX_HEAD=$NX_HEAD"
# Without fetch-depth: 0 this can fail with a bad revision or missing object error
- run: npx nx affected -t lint test build
A minimal GitHub Actions workflow that checks out full history, installs from the lockfile, computes base and head SHAs with nx-set-shas, logs them for verification, and runs lint, test and build on affected projects.
How are NX_BASE and NX_HEAD consumed, and how do you debug them?
the commit you expect. Making that check routine requires knowing where Nx reads the values from.
nx affected and nx show projects --affected read NX_BASE and NX_HEAD from the environment. Explicit --base and --head flags take precedence over the variables. If one step in a workflow passes --base=origin/main and another relies on the environment, the two steps can test different project sets.
A debugging step
Add a step right after nx-set-shas that echoes $NX_BASE and $NX_HEAD, then runs git log --oneline $NX_BASE..$NX_HEAD. If that range lists commits you did not expect, or fails because a SHA is unknown, the problem is the git history and not Nx. An unknown SHA usually means a shallow checkout. Set fetch-depth: 0.
Pull request specifics
Nx computes the merge base of base and head and diffs from that point, not from the tip of the base branch. This matters when a branch is behind main. A raw diff against main's tip would count every change merged to main since the branch was created as part of the PR. Diffing from the merge base excludes those changes.
The pull_request event complicates this. By default it checks out a synthetic merge commit of the PR into the current base branch, so HEAD is not your branch tip. With main's tip as base, the merge base is main's tip, and the diff shows only the PR's changes applied on top of current main.
Reproducing and verifying locally
To reproduce a CI result, copy both SHAs from the log and run nx show projects --affected --base=<sha> --head=<sha> locally. Run nx graph --affected with the same flags to see why each project was included.
Then open two throwaway PRs to verify the setup:
- One that touches a leaf library. Only that library and its direct consumers should run.
- One that touches a widely shared library. Most of the workspace should light up.
If either result looks wrong, check the base SHA before you look at the project graph.
name: CI
on:
pull_request:
jobs:
affected:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # full history so the base SHA and merge base are reachable
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
# Exports NX_BASE and NX_HEAD to $GITHUB_ENV for later steps
- uses: nrwl/nx-set-shas@v4
- name: Debug affected range
run: |
echo "NX_BASE=$NX_BASE"
echo "NX_HEAD=$NX_HEAD"
# On pull_request, HEAD is the synthetic merge commit, not the branch tip
git log -1 --format='HEAD is %H (%s)' HEAD
echo "merge base: $(git merge-base "$NX_BASE" "$NX_HEAD")"
# Fails here if a SHA is missing (shallow clone), which points at git, not Nx
git log --oneline "$NX_BASE..$NX_HEAD"
# Same project set later steps will use; copy the SHAs above to reproduce locally:
# npx nx show projects --affected --base=<NX_BASE> --head=<NX_HEAD>
# npx nx graph --affected --base=<NX_BASE> --head=<NX_HEAD>
npx nx show projects --affected
# No --base/--head here, so it reads NX_BASE/NX_HEAD from the environment.
# Passing --base=origin/main would override them and could test a different set.
- run: npx nx affected -t lint test build
A pull_request workflow that sets NX_BASE and NX_HEAD with nx-set-shas, prints the commit range, merge base, and affected projects for debugging, and leaves out --base/--head so the affected run uses the same environment values.
When should you avoid relying on Nx affected alone?
Affected is only as accurate as the project graph, and the graph only knows what you've told it. Several kinds of change sit outside it:
- Things outside the graph. A new Node or JDK version in the CI image, a changed environment variable, a schema change in an external service, or a script that reads a file Nx never sees will not mark anything affected. Model the ones you can as
implicitDependenciesor as entries innamedInputs. The catch is that global inputs cut the other way. If a file like the root lockfile or a shared tsconfig is in every project's inputs, touching it marks the whole workspace affected, and you are back to a full run. - History rewrites. Force-pushes, squash merges and rebases can make the recorded last-successful SHA unreachable from the current branch. Nx then cannot compute a diff against it, and you get either an error or a fallback base that may not match what you expected.
- Long red streaks. The base only advances on success. When main has been broken for a day, every run diffs against the last green commit, so the affected set grows exactly when the team is waiting on a fix.
- The action itself. nx-set-shas calls the GitHub API, so it inherits rate limits and depends on the token having permission to read workflow runs. It looks up runs by workflow, so renaming the workflow file silently resets the history. Pin the action to a specific release or commit, and treat upgrades as deliberate changes.
The practical safety net is a scheduled full run, nightly or before releases, that ignores affected entirely. It catches whatever the graph missed while the per-commit runs stay fast.
# .github/workflows/ci.yml
# Keep this file name stable: nx-set-shas finds the last green run by workflow.
name: CI
on:
push:
branches: [main]
pull_request:
schedule:
- cron: '0 3 * * *' # nightly full run as a safety net
workflow_dispatch: # manual full run, e.g. before a release
permissions:
contents: read
actions: read # nx-set-shas reads workflow runs via the GitHub API
jobs:
main:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # full history so the base SHA is reachable
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
# Per-commit runs: compute NX_BASE/NX_HEAD, then run only affected projects.
# Pin to an exact release tag or commit SHA, and upgrade deliberately.
- if: github.event_name == 'push' || github.event_name == 'pull_request'
uses: nrwl/nx-set-shas@v4
- if: github.event_name == 'push' || github.event_name == 'pull_request'
run: npx nx affected -t lint test build
# Scheduled or manual runs: ignore affected and run everything,
# catching changes the project graph cannot see.
- if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'
run: npx nx run-many -t lint test build
A GitHub Actions workflow that runs nx affected on pushes and pull requests, and runs every project on a nightly schedule or a manual trigger so that changes outside the project graph still get tested.
What are the alternatives, and how do they affect CI cost?
Comparing the options
The scheduled full run is one option. The table compares it with the others, as everyday strategies or as additions to nx-set-shas.
| Approach | CI compute | Engineering time | Main risk |
|---|---|---|---|
| Full run of all targets | Highest, grows with repo size | Lowest; nothing to configure | Slow feedback, so developers start batching changes |
Plain merge-base, no nx-set-shas |
Low on PRs | Low | On pushes to main, misses commits from earlier failed runs |
| Shallow or targeted fetch of the base commit | Saves checkout time on large histories | Moderate; you must keep the fetch and the SHA logic in sync | Base commit or merge-base missing, so the affected calculation fails or is wrong |
| Remote or distributed cache | Cuts repeated work | Moderate (setup, access control) | Mistaken for a fix to base-SHA problems |
Illustrative estimate (assumed numbers, not a benchmark).
Assumed inputs:
- 40 projects
- 3 minutes per project
- 6 projects affected per change on average
- 200 runs a month
- 50% cache hit rate
Formula: minutes per month ≈ runs × projects executed × minutes per project × (1 − hit rate).
| Approach | Calculation | Minutes per month |
|---|---|---|
| Full runs | 200 × 40 × 3 × 0.5 | 12,000 |
| Affected | 200 × 6 × 3 × 0.5 | 1,800 |
Substitute your own values. The gap is only real if the base SHA is correct.
Caching and base SHAs solve different problems
Caching and base-SHA selection do different jobs:
- The base SHA decides which projects Nx considers.
- The cache decides whether a considered task can be replayed instead of executed. It never adds a project that the base SHA excluded.
If a broken change passed CI, check the base and head SHAs before you check the cache. If CI is slow, check how many projects were affected before you tune the cache. Treating one as the other wastes debugging time on the wrong layer.
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.