Skip to content
Latchkey

How to Build Only Affected Projects With nx affected in CI

nx affected --target=test walks the project graph from the changed files and runs the target only on affected projects plus everything that depends on them.

Nx computes an affected set from the diff between a base and head SHA, then runs a target across just those projects. Set the base to the PR base (or the last successful commit) so the graph traversal is correct.

Steps

  • Checkout with fetch-depth: 0 so both base and head are available.
  • Set the base and head SHAs (nrwl/nx-set-shas helps on push).
  • Run npx nx affected -t <target> --base=$BASE --head=$HEAD.

Workflow

.github/workflows/ci.yml
jobs:
  affected:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with: { fetch-depth: 0 }
      - uses: actions/setup-node@v4
        with: { node-version: 20 }
      - run: npm ci
      - uses: nrwl/nx-set-shas@v4
      - run: npx nx affected -t lint test build --base=$NX_BASE --head=$NX_HEAD

Gotchas

  • Affected is dependency-aware: it includes projects that depend on the changed one, which is what keeps skipping correct.
  • A wrong base (for example the default main on a stale branch) can under- or over-select projects; pin it with nx-set-shas.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →