Configuring CI Using GitHub Actions and Nx

Below is an example of an GitHub Actions setup, building and testing only what is affected.

.github/workflows/ci.yml
1name: CI 2on: 3 push: 4 branches: 5 # Change this if your primary branch is not main 6 - main 7 pull_request: 8 9# Needed for nx-set-shas when run on the main branch 10permissions: 11 actions: read 12 contents: read 13 14jobs: 15 main: 16 runs-on: ubuntu-latest 17 steps: 18 - uses: actions/checkout@v4 19 with: 20 fetch-depth: 0 21 # Cache node_modules 22 - uses: actions/setup-node@v3 23 with: 24 node-version: 20 25 cache: 'npm' 26 - run: npx nx-cloud start-ci-run --distribute-on="5 linux-medium-js" --stop-agents-after="build" # this line enables distribution 27 - run: npm ci 28 - uses: nrwl/nx-set-shas@v3 29 # This line is needed for nx affected to work when CI is running on a PR 30 - run: git branch --track main origin/main 31 32 - run: npx nx-cloud record -- nx format:check 33 - run: npx nx affected -t lint test build --parallel=3 34

Get the Commit of the Last Successful Build

GitHub can track the last successful run on the main branch and use this as a reference point for the BASE. The nrwl/nx-set-shas provides a convenient implementation of this functionality which you can drop into your existing CI config. To understand why knowing the last successful build is important for the affected command, check out the in-depth explanation in Actions's docs.