How does nx affected ci decide what to run in GitHub Actions?
nx affected answers one question: which projects could behave differently between two commits? It runs a git diff between a base SHA and a head SHA, maps every changed file to the project that owns it, then walks the project graph to add every project that depends on those projects. Without both commits, there is no diff and no affected set. In that case Nx either fails or falls back to comparing against a branch that may not reflect what was last verified.
Why checkout depth matters
actions/checkout fetches a single commit by default. That keeps checkout fast, but the base SHA is usually not in the clone, so Nx cannot compute the diff. Setting fetch-depth: 0 fetches full history and guarantees the base exists. The cost is checkout time and network transfer, which grow with the repository's history. A shallow fetch with a fixed depth is faster. It breaks when the base is older than the fetched window, for example on a branch that has been open for weeks or after a large merge.
The graph is the ceiling on accuracy
Nx only knows about the dependencies it can see: imports, declared implicit dependencies, and configured inputs. Some dependencies are invisible to it:
- a service that reads a shared JSON file at runtime
- code generated by a step outside Nx
- behavior that changes with an environment variable
If one of these changes, the affected set can be wrong, and a broken project can skip CI while the pipeline still passes.
Flow: commit range (base → head) → changed files → project graph → affected projects (changed + dependents) → CI jobs
name: ci
on:
pull_request:
push:
branches: [main]
jobs:
affected:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
# Full history so the base SHA is guaranteed to exist in the clone.
# A fixed depth (e.g. 50) checks out faster but breaks base resolution
# once a branch has drifted further than that from its base.
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
# Exports NX_BASE and NX_HEAD. On main, the base is the last commit with a
# successful workflow run, not simply the previous commit.
- uses: nrwl/nx-set-shas@v4
# Log the affected set so a reviewer can spot a project that should be in it.
# Dependencies Nx cannot see (runtime file reads, out-of-band codegen,
# env-driven behavior) will not appear here.
- run: npx nx show projects --affected --base=$NX_BASE --head=$NX_HEAD
# Run targets only for changed projects and everything that depends on them.
- run: npx nx affected -t lint test build --base=$NX_BASE --head=$NX_HEAD
A GitHub Actions job that fetches enough history for the base commit and uses nx-set-shas to set NX_BASE and NX_HEAD. It logs the affected project list, then runs lint, test and build only for those projects.
What does nx-set-shas do and how do you configure it correctly?
The base of that range is what nx-set-shas computes. On a pull_request event it uses the PR's base branch, through the merge base, as the base, so the affected set covers everything the PR changes relative to its target. On a push to the main branch it does not use the previous commit. It asks 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. If three pushes in a row fail, the fourth run still compares against the last green commit. Projects touched by the failed pushes stay in scope until a run passes.
The action writes the result to NX_BASE and NX_HEAD in the job environment, and nx affected reads those values automatically. It also exposes them as step outputs for later jobs. The repository must be checked out with full history (fetch-depth: 0), or the base commit may not exist locally.
| Situation | Base used | Effect |
|---|---|---|
| Pull request | PR base branch | Correct |
| Push, prior green run exists | Last successful run's commit | Correct |
Wrong main-branch-name |
No matching run found, falls back to HEAD~1 |
Under-tests |
Missing actions: read permission |
API lookup fails, falls back | Under-tests |
| Workflow file renamed or split | Defaults to the current workflow and finds no prior green run | Under-tests until the first green run |
To query workflow runs, the job needs permissions: actions: read. If your default branch isn't main, set main-branch-name. If a different workflow defines "green", set workflow-id. The fallbacks only emit a warning, so the pipeline passes while testing a narrower range. Set error-on-no-successful-workflow: true if you want the job to fail instead of silently falling back.
name: CI
on:
push:
branches: [develop] # default branch here is 'develop', not 'main'
pull_request:
permissions:
actions: read # lets nx-set-shas query previous workflow runs
contents: read
jobs:
affected:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # full history so the base commit exists locally
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
# Exports NX_BASE / NX_HEAD to the job env and as step outputs
- id: shas
uses: nrwl/nx-set-shas@v4
with:
main-branch-name: develop # must match the real default branch
workflow-id: ci.yml # the workflow whose green runs define the base
error-on-no-successful-workflow: true # fail instead of silently using HEAD~1
- run: echo "base=${{ steps.shas.outputs.base }} head=${{ steps.shas.outputs.head }}"
# nx affected reads NX_BASE and NX_HEAD from the environment
- run: npx nx affected -t lint test build
A workflow that grants actions: read, checks out full history, and configures nx-set-shas with a non-default branch name, an explicit workflow-id and error-on-no-successful-workflow, so nx affected uses the last green commit as its base and the job fails instead of silently falling back to HEAD~1.
How should you cache dependencies and the Nx task cache in GitHub Actions?
Treat caching as two layers with different keys and lifetimes.
Dependencies. Cache the package manager store, not the Nx outputs. setup-node with its cache input handles npm, Yarn or pnpm stores and keys on the lockfile. Use actions/cache directly if you need to cache node_modules itself. The lockfile hash is the correct key because nothing else should invalidate installed packages.
Nx task cache. Persist the local cache directory (check cacheDirectory in nx.json) with actions/cache. Cache entries are immutable, so a fixed key never updates. Use a key that is unique per run, such as nx-<os>-<lockfile hash>-<github.sha>, with restore-keys set to the nx-<os>-<lockfile hash>- prefix. This restores the closest earlier entry and saves a new one.
Hit rates are often lower than expected, for three reasons:
- Branch scoping. A run can read caches from its own ref and the default branch, but not from sibling branches.
- Eviction. Entries that go unused are removed, and once the repository reaches its storage limit, older entries are evicted.
- Restore cost. A multi-gigabyte archive can take longer to download and extract than rebuilding the few affected projects. Watch the restore step's duration.
Poisoning. Do not let untrusted code write entries that trusted branches will read. Workflows triggered by pull_request_target run in the base repository's context, so a fork's code could seed poisoned artifacts there. Use actions/cache/restore on PRs and run actions/cache/save only on pushes to the default branch.
| Aspect | Local actions/cache |
Remote cache |
|---|---|---|
| Granularity | Whole directory archive | Per-task artifacts |
| Sharing | Same ref plus default branch | All runners and developers |
| Matrix jobs | Each job restores the full archive | Each job fetches only the tasks it needs |
| Write control | Workflow conditions | Access tokens (read-only vs read-write) |
name: ci
on:
push:
branches: [main]
pull_request:
jobs:
affected:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # nx-set-shas needs history to find the base commit
# Layer 1: package manager store, keyed on the lockfile by setup-node
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- uses: nrwl/nx-set-shas@v4
# Layer 2: restore the Nx task cache. Unique key per run, prefix fallback
- uses: actions/cache/restore@v4
with:
path: .nx/cache # match cacheDirectory in nx.json if you changed it
key: nx-${{ runner.os }}-${{ hashFiles('package-lock.json') }}-${{ github.sha }}
restore-keys: |
nx-${{ runner.os }}-${{ hashFiles('package-lock.json') }}-
- run: npx nx affected -t lint test build
# Only trusted pushes to main write the cache; PR runs are read-only
- if: github.event_name == 'push' && github.ref == 'refs/heads/main'
uses: actions/cache/save@v4
with:
path: .nx/cache
key: nx-${{ runner.os }}-${{ hashFiles('package-lock.json') }}-${{ github.sha }}
A workflow that caches the npm store through setup-node, restores the Nx task cache on every run using a per-commit key with a prefix fallback, and saves it only on pushes to main so pull request code cannot write entries that trusted branches will read.
How do you build a dynamic GitHub Actions matrix from affected projects?
The setup job checks out the repository with full history, runs nx-set-shas, and then calls nx show projects --affected --json. Add --withTarget=test (or -t test) to keep only affected projects that define the target the matrix will run. Without that filter, a library with no test target gets its own job, which fails or does nothing. Because nx-set-shas exports NX_BASE and NX_HEAD, the command uses the same comparison range as any other affected command in the workflow. Write the JSON array to $GITHUB_OUTPUT as a step output, then map it to a job-level output so downstream jobs can read it.
The matrix job declares needs: setup and sets matrix.project to fromJSON(needs.setup.outputs.projects). If nothing is affected, the array is [], and GitHub Actions fails the job because the matrix has no values. Guard the job with if: needs.setup.outputs.projects != '[]'. The job is then skipped instead of failing.
Choosing fail-fast
fail-fast defaults to true, so the first failing project cancels the rest of the matrix. That saves runner minutes on large matrices. The cost is that developers see one failure per push and find the others only after they fix it. On pull requests, fail-fast: false usually shortens the feedback loop. Keep the default only if runner cost matters more than seeing every failure at once.
One required check
Matrix job names depend on the project list, so you cannot list them in branch protection. Add a final job with needs: [setup, test] and if: always(). It should fail when any result in needs.*.result is failure or cancelled, and treat skipped as success. Mark only this job as required in branch protection.
name: CI
on: pull_request
jobs:
setup:
runs-on: ubuntu-latest
outputs:
# Map the step output to a job output so downstream jobs can read it
projects: ${{ steps.affected.outputs.projects }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # full history so the base commit can be found
- uses: actions/setup-node@v4
with: { node-version: 20, cache: npm }
- run: npm ci
- uses: nrwl/nx-set-shas@v4 # exports NX_BASE and NX_HEAD
- id: affected
# Only affected projects that define a "test" target, as a JSON array
run: echo "projects=$(npx nx show projects --affected --withTarget=test --json)" >> "$GITHUB_OUTPUT"
test:
needs: setup
if: needs.setup.outputs.projects != '[]' # skip instead of failing on an empty matrix
runs-on: ubuntu-latest
strategy:
fail-fast: false # report every failing project in one run
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
- run: npx nx run ${{ matrix.project }}:test
ci-ok: # the only job marked as required in branch protection
needs: [setup, test]
if: always() # run even when test fails or is skipped
runs-on: ubuntu-latest
steps:
# A skipped test job counts as success; failure or cancellation does not
- if: contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled')
run: exit 1
A workflow where a setup job emits affected projects with a test target as JSON, a guarded matrix job runs one job per project with fail-fast disabled, and a single aggregating job serves as the required check.
When should you avoid a per-project matrix and use nx affected --parallel instead?
Every matrix job is a fresh runner. Before it runs anything, it repeats checkout, dependency install and cache restore. A single job running nx affected -t lint test build --parallel=3 pays that setup once. Nx then schedules tasks across the runner's cores in dependency-graph order and reuses outputs between targets on the same disk.
Illustrative estimate. Assume 90 s of setup per job, 12 affected projects, 60 s of work per project, and a 4-core runner.
- Matrix: 12 × (90 + 60) s = 30 billed runner-minutes. Wall-clock is about 2.5 minutes, if 12 runners are free.
- Single job: 90 + (12 × 60 / 4) s = 270 s, about 4.5 minutes of both wall-clock and billed time.
The matrix saves about 2 minutes of waiting at roughly 6× the runner cost. The faster each project's tasks are, the more that fixed setup dominates.
Also consider what happens when everything is affected. A change to the lockfile, a root config file or an implicitDependencies target marks every project as affected, so the matrix fans out across the whole repo. Set max-parallel, or have the setup job fall back to a single --parallel job above a project-count threshold.
| Factor | Single job with --parallel |
Per-project matrix |
|---|---|---|
| Setup cost | Paid once | Paid per project |
| Status checks | One check | One check per project |
| Logs | Interleaved | Isolated per project |
| Failure isolation | One failure can hide others unless you use --nx-bail=false defaults |
Independent results |
| Suits | Small to mid-size teams, many fast projects | Larger orgs, slow suites, per-project ownership |
Choose the matrix when per-project work clearly outweighs setup, for example integration tests that start containers. It also fits when separate owners need their own required checks. In other cases, a single job is cheaper and simpler.
Complete Nx GitHub Actions workflow example
The workflow below has three jobs: setup computes what changed, project fans out over the result, and ci-status reduces everything to one check. The comments in the YAML map to these decisions:
- Top-level
permissions.contents: readcovers checkout.actions: readletsnx-set-shasquery previous workflow runs to find the last successful commit on the main branch. Everything else stays off. fetch-depth: 0insetuponly. The base SHA must exist locally for the affected comparison. Per-project jobs receive an explicit project name and never compute a diff, so they can use a shallow checkout and save clone time.- Lockfile-keyed dependency cache. The key hashes the lockfile, so the cache is invalidated exactly when dependencies change. A clean install then runs against a warm package store.
nx-set-shasbefore anynxcommand. It exportsNX_BASEandNX_HEAD, which every later affected command reads implicitly.- Nx cache restore with a fallback key. The exact key includes the commit SHA. The restore key drops the SHA so a miss still pulls the nearest previous cache instead of starting cold.
- Matrix output as JSON.
setupwrites the affected project list to$GITHUB_OUTPUT. Theprojectjob reads it withfromJSONand setsfail-fast: falseso one broken project does not hide the results of the others. - Empty-matrix guard. If no projects are affected, the
projectjob'sifcondition skips it. Without the guard, an empty matrix fails the workflow. ci-statuswithif: always(). This job inspectsneeds.*.result, treatsskippedas passing, and fails on anything else. Make it the only required check in branch protection so the protection rule does not depend on dynamic matrix job names.
What are the alternatives, and how does this setup affect CI cost and engineering time?
Each option trades runner minutes against setup and maintenance effort.
| Approach | Runner cost scales with | Setup effort | Main risk |
|---|---|---|---|
| Every target on every commit | Monorepo size | Minimal | Slow feedback, wasted minutes |
Single nx affected job |
Size of the change | Low | One large runner becomes the bottleneck |
| Dynamic matrix per project | Size of the change, plus per-job setup | Moderate | Setup overhead outweighs work on small projects |
| Distributed execution or remote cache | Change size, shared across runs and machines | Higher, plus an external cache service | Cache poisoning, added dependency |
The savings come from scaling CI with the diff rather than with the repository.
Illustrative estimate (assumed numbers, not a benchmark). Assume P = 40 projects, t = 3 minutes per project's targets, A = 4 affected projects per PR, and s = 2 minutes of checkout and install per matrix job.
- Full run: P × t = 120 runner minutes.
- Single affected job: A × t + s = 14 minutes.
- Matrix: A × (t + s) = 20 minutes. It costs more minutes than the single job, but it returns results sooner because the jobs run in parallel.
The ongoing costs are real:
- SHA configuration. A wrong base SHA silently shrinks or inflates the affected set.
- Cache tuning. Cache keys must change when the lockfile or toolchain changes.
- Project graph accuracy. Undeclared dependencies, such as runtime config or files read at runtime, cause missed rebuilds.
Verification checklist
- A docs-only PR schedules no project jobs, and the aggregator job passes.
- Changing a shared library triggers every dependent project.
- The logged base SHA matches the last successful run on
main. - Rerunning the same commit shows task cache hits.
nx show projects --affectedrun locally matches the CI matrix.
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.