What are the three cache layers in an Nx GitHub Actions pipeline?

An Nx pipeline on GitHub Actions has three separate caches and one decision step. Each one saves a different kind of time, so each needs its own key.

Layer What it stores Time it saves Key should change when
Package manager store Downloaded tarballs Network fetch Lockfile changes
node_modules Installed, linked tree Install and link step Lockfile, OS or Node version changes
Nx task cache Task outputs and terminal logs Build, test and lint Every run, restored by prefix
nx-set-shas (not a cache) Base and head SHAs Skips unaffected projects Not applicable

Slow pipelines rarely suffer from too little caching. The usual causes are caching the wrong layer or using the wrong key. One example is a node_modules key that leaves out the Node version. Another is an Nx cache key that never changes. GitHub does not overwrite an existing cache entry, so a fixed key keeps saving nothing new.

checkout (fetch-depth: 0)
  │  fails silently: shallow clone → nx-set-shas has no history
restore package store / node_modules        [layers 1–2]
  │  fails silently: stale key → wrong tree restored
install (lockfile frozen)                    [layers 1–2]
restore Nx cache                             [layer 3]
  │  fails silently: miss → empty cache, everything rebuilds
nx-set-shas → NX_BASE / NX_HEAD
  │  fails silently: no prior green run → wide base, runs too much
nx affected -t lint test build               [layer 3 read/write]
save Nx cache                                [layer 3]
     fails silently: key already exists → save is skipped

This setup is for backend and platform engineers who run Nx monorepos on GitHub-hosted or self-hosted runners.

┌──────────────────────────┐  [git history for decision step]
│ checkout (fetch-depth:0) │  ! shallow clone: nx-set-shas has no history
└────────────┬─────────────┘
             ▼
┌──────────────────────────┐  [L1 pkg store + L2 node_modules: read]
│ restore pkg store /      │  ! key omits Node/OS: wrong tree restored
│ restore node_modules     │
└────────────┬─────────────┘
             ▼
┌──────────────────────────┐  [L1 + L2: fill on miss]
│ install (frozen lockfile)│
└────────────┬─────────────┘
             ▼
┌──────────────────────────┐  [L3 Nx task cache: read]
│ restore Nx cache (prefix)│  ! miss: empty cache, everything rebuilds
└────────────┬─────────────┘
             ▼
┌──────────────────────────┐  [decision step, not a cache]
│ nx-set-shas              │  ! no prior green run: wide base, runs too much
│  → NX_BASE / NX_HEAD     │
└────────────┬─────────────┘
             ▼
┌──────────────────────────┐  [L3 Nx task cache: read/write]
│ nx affected -t lint      │
│   test build             │
└────────────┬─────────────┘
             ▼
┌──────────────────────────┐  [L3 Nx task cache: write]
│ save Nx cache            │  ! key already exists: save is skipped
└──────────────────────────┘

The Nx pipeline on GitHub Actions from checkout to cache save, showing which cache layer each step touches and how each step can fail without an error.

Who should use this setup?

This setup fits teams that meet most of these conditions:

  • You run an Nx workspace with several projects. The affected calculation and task cache pay off when a typical change touches only some of the projects. In a workspace with one or two projects, almost every change affects everything, and the dependency cache alone gives most of the benefit.
  • CI time is dominated by install, build, test and lint. If most of the wall-clock time goes to integration tests against external services or to deployment, task caching will not change much.
  • You run on GitHub-hosted runners, or on self-hosted runners without persistent disks. These runners start with an empty workspace, so actions/cache is the only way to carry dependencies and task outputs from one run to the next.
  • You do not already have a shared remote task cache. If you do, keep the dependency cache layers from this article and let the remote cache handle task outputs. Saving the Nx cache directory to actions/cache as well mostly duplicates work and uses quota.

It is a poor fit if your build has undeclared side effects you cannot model as Nx inputs, such as reading files outside the workspace or calling network services during the build. In that case, fix the target definitions before you add task caching, because a cache hit will replay results that should have been recomputed.

How does it work end to end?

Each run follows the same sequence. The rest of the article covers each step in detail.

  1. Dependencies are restored, then installed. The package store or node_modules cache is restored using a key derived from the lockfile. The install step then either fills in what is missing (store cache) or is skipped on an exact hit (node_modules cache).
  2. The Nx cache directory is restored. actions/cache copies the most recent matching entry into the directory Nx reads its local cache from. Nx is not aware of this step. To Nx, the directory looks the same as it would on a developer machine that had already run these tasks.
  3. nx-set-shas picks the comparison range. It exports NX_BASE and NX_HEAD. On a push to the main branch, the base is the commit of the last successful run. On a pull request, it is the PR's base.
  4. nx affected selects projects. Nx compares the files changed between base and head with its project graph. It marks the projects that own those files, plus every project that depends on them, as affected. Only those projects' targets are scheduled.
  5. Nx hashes each task and checks the cache. For each scheduled task, Nx computes a hash from the task's declared inputs, such as source files, configuration, dependency versions, environment variables and runtime values, combined with the hashes of the tasks it depends on. If an entry with that hash exists in the cache directory, Nx replays the terminal output and restores the declared outputs instead of running the task. Otherwise it runs the task and stores the result.
  6. The cache directory is saved. actions/cache/save writes the directory under a new key, so the next run can restore the results of this run.

Two mechanisms do separate jobs here. The affected calculation decides which projects are considered at all. The task hash decides whether a considered task can be skipped. A task outside the affected set never runs. A task inside it runs only if its hash is missing from the cache.

How does GitHub Actions caching work, and why does it shape the design?

GitHub Actions caches have four properties that shape every key and step in the workflow.

Entries are immutable. Once a key is saved, it cannot be overwritten. A save against an existing key is skipped, which is the silent failure shown above. A static key like nx-cache-linux is written once and never refreshed, so later runs keep restoring a stale snapshot. Keys must include something that changes when the content should change: a lockfile hash for dependencies, or the commit SHA for task outputs.

restore-keys match by prefix. If the exact key misses, Actions tries each restore key in order and returns the most recently created entry that starts with that prefix. Unique per-commit keys depend on this: the exact key almost never hits, and the prefix fallback supplies the closest recent cache.

Caches are scoped by branch. A run can restore entries created on its own branch or on the default branch. It cannot restore entries from sibling feature branches. Warm the cache on main so that every new branch starts from it.

Storage is capped per repository. When the cap is reached, older entries are evicted. A new Nx cache entry for every run can push out the dependency cache that every job needs.

Cache poisoning is a real risk. If untrusted pull request code runs with cache write access, it can save artifacts that trusted runs later restore. The common way this happens is running PR code under pull_request_target. To limit the risk:

  • Only write caches from trusted events, such as pushes to protected branches.
  • Do not restore build outputs into release jobs. Rebuild them there instead.

Finally, this cache belongs to one repository and is size-limited, so it is only a partial substitute for a shared remote task cache.

Should you cache node_modules or the package manager store?

A common mistake is caching node_modules with actions/cache and then running npm ci anyway. npm ci deletes any existing node_modules before installing, so the restored directory is thrown away and the cache step only adds time. Pick one of two approaches.

Option A: cache the package manager store. Set cache: npm (or pnpm/yarn) on actions/setup-node. This caches the download store, not node_modules, and you still run npm ci on every job. Installs avoid the network but rebuild the tree and run lifecycle scripts each time. If a partial restore-keys match restores an older store, that is harmless. The package manager fetches whatever is missing.

Option B: cache node_modules directly. Key it on ${{ runner.os }}, the Node version, and hashFiles('**/package-lock.json'). Run install only when the step's cache-hit output is not 'true'. The key needs the OS and Node version because native addons are compiled for a specific platform, libc, and Node ABI, and binaries fetched by postinstall are platform-specific too. Leave out restore-keys here. A partial match restores a tree built from a different lockfile.

Concern Store cache (A) node_modules cache (B)
Speed on hit Moderate Fastest
Predictability High Depends on key
Hides lockfile drift No Yes, with loose keys
Lifecycle scripts Always run Skipped on hit
Image/Node change Rebuilt cleanly Stale native binaries

Avoid option B if you depend on postinstall side effects, use many native modules, or can't put the Node version in the key.

env:
  NODE_VERSION: '20'

jobs:
  # Option A: cache the npm download store, always run a clean install
  install-store-cache:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}
          cache: npm   # caches ~/.npm keyed on the lockfile, not node_modules
      - run: npm ci    # rebuilds node_modules and runs lifecycle scripts every time

  # Option B: cache node_modules itself, install only on an exact key miss
  install-node-modules-cache:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}
      - id: nm-cache
        uses: actions/cache@v4
        with:
          path: node_modules
          # OS + Node version pin native addon ABI; lockfile hash pins the tree
          key: nm-${{ runner.os }}-node${{ env.NODE_VERSION }}-${{ hashFiles('**/package-lock.json') }}
          # No restore-keys: a partial match would restore a tree from another lockfile
      - if: steps.nm-cache.outputs.cache-hit != 'true'
        run: npm ci    # on a hit this is skipped, so postinstall scripts do not run

Two GitHub Actions jobs contrasting option A (setup-node's npm store cache plus an unconditional npm ci) with option B (actions/cache on node_modules keyed on OS, Node version, and lockfile hash, installing only when cache-hit is not 'true').

How do you cache the Nx task cache with actions/cache?

Start by finding the directory your workspace actually writes to. Nx's default location has moved between releases, and you can override it with cacheDirectory in nx.json. So don't copy a path from a blog post, including this one. Run a cacheable target locally, check where the entries appear, and point actions/cache at that directory. If the path is wrong, the step still reports success but caches nothing.

Restore the cache before running Nx and save it afterward. Build the key from the runner OS, a hash of the lockfile, and github.sha, for example nx-<os>-<lockhash>-<sha>. Set restore-keys to the same string without the SHA. No run will ever match its own key exactly, so the prefix restores the most recent entry built against the same dependencies, and the save step writes a new entry for the next run.

That freshness has a cost. Each unique key consumes repository cache quota, and GitHub evicts the least recently used entries when you exceed it. Those evicted entries can include your dependency cache. A static or coarse key avoids this, but cache entries are immutable, so a key that never changes keeps restoring the first snapshot forever.

Broad restore-keys raise hit rates. They are only safe because Nx re-hashes every task and ignores stale entries. That protection holds only if each project's inputs are declared accurately.

To keep entries small:

  • Disable caching for targets whose outputs are large but cheap to regenerate.
  • Use a separate key prefix for each job, so a job saves only what it ran.
  • Avoid saving on pull requests from forks.
jobs:
  build:
    runs-on: ubuntu-latest
    env:
      # Confirm this path for YOUR workspace: run a cacheable target locally,
      # see where entries land, and check cacheDirectory in nx.json.
      NX_CACHE_DIR: .nx/cache
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: npm   # dependency cache, separate from the Nx cache
      - run: npm ci

      # Exact key never matches (it contains this run's SHA), so restore-keys
      # falls back to the newest entry built against the same lockfile.
      # The 'build' segment gives each job its own prefix.
      - name: Restore Nx cache
        id: nx-cache
        uses: actions/cache/restore@v4
        with:
          path: ${{ env.NX_CACHE_DIR }}
          key: nx-build-${{ runner.os }}-${{ hashFiles('package-lock.json') }}-${{ github.sha }}
          restore-keys: |
            nx-build-${{ runner.os }}-${{ hashFiles('package-lock.json') }}-

      - run: npx nx run-many -t build

      # Save a fresh entry for the next run, but skip PRs from forks
      # so untrusted branches don't consume quota or seed the cache.
      - name: Save Nx cache
        if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
        uses: actions/cache/save@v4
        with:
          path: ${{ env.NX_CACHE_DIR }}
          key: ${{ steps.nx-cache.outputs.cache-primary-key }}

A GitHub Actions job that restores the Nx local cache by lockfile prefix, runs Nx, and saves a new entry keyed by commit SHA, using a per-job prefix and skipping saves for fork pull requests.

How does nx-set-shas decide what is affected?

The nx-set-shas action computes two commits, NX_BASE and NX_HEAD, and exports them as environment variables for later steps. NX_HEAD is the commit being built. NX_BASE depends on the event type:

  • Push to the main branch: the commit of the last successful run of the workflow on that branch. Everything since the last green build is checked again, so a failed run does not hide changes from later runs.
  • Pull request: the PR's base on the main branch. Only the PR's own changes count as affected.

Both cases need the base commit to exist locally. The checkout step's default shallow fetch does not include it, so set fetch-depth: 0. On large repositories this makes checkout noticeably slower. That is the cost of a correct affected calculation, and it is usually small next to the tasks it lets you skip. Then pass --base=$NX_BASE --head=$NX_HEAD to nx affected.

The action finds "the last successful run" by workflow and branch. Set main-branch-name if your default branch is not main. Set workflow-id if the run that should count comes from a different workflow file. If either is wrong, the action finds no matching run.

When no usable run exists, the action logs a warning and falls back to a default base instead of the last green commit. This happens in three cases:

  • The repository is new.
  • The recorded commit disappeared after a force-push or history rewrite.
  • The workflow or branch name is misconfigured.

To spot this, look for that warning in the nx-set-shas step and compare the printed base SHA with your last green build. If you would rather catch misconfiguration than run with an unexpected base, enable the action's option to fail when no successful workflow is found.

name: CI
on:
  push:
    branches: [main]
  pull_request:

permissions:
  contents: read
  actions: read # nx-set-shas reads past workflow runs to find the last green one

jobs:
  affected:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0 # full history so NX_BASE exists locally; slower on big repos

      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: npm
      - run: npm ci

      - uses: nrwl/nx-set-shas@v4
        with:
          main-branch-name: main   # change if your default branch differs
          workflow-id: ci.yml      # the workflow whose successful runs count as 'green'
          # Fail loudly instead of silently falling back to a broader base:
          error-on-no-successful-workflow: true

      # Print the computed range so you can compare NX_BASE with your last green build
      - run: |
          echo "NX_BASE=$NX_BASE"
          echo "NX_HEAD=$NX_HEAD"

      - run: npx nx affected -t lint test build --base=$NX_BASE --head=$NX_HEAD

A GitHub Actions workflow that checks out full history, configures nx-set-shas with the branch and workflow it should search for the last successful run, prints the computed SHAs for log inspection, and passes them to nx affected.

Why does Nx miss the cache or restore nothing, and how do you fix inputs and outputs?

Restoring a cache directory is the easy part. Whether Nx can use what was restored depends on how each target declares its inputs and outputs, and no actions/cache step can make up for a vague declaration. Fixing these declarations usually saves more CI time than tuning restore keys.

Declare outputs, or a hit restores only logs

On a cache hit, Nx replays the terminal output and copies back the files listed in the target's outputs. If a build target writes to dist/apps/api but declares no outputs, or a different path, the hit replays "Successfully compiled" and leaves dist empty. The next job that packages or deploys the build then fails. Declare outputs per target in project.json, or once in targetDefaults in nx.json, using tokens such as {projectRoot}/dist or {workspaceRoot}/dist/{projectRoot}.

Narrow inputs so unrelated edits don't invalidate builds

By default, any file in a project changes its hash. Define a production entry in namedInputs that starts from default and excludes patterns such as !{projectRoot}/**/*.spec.ts and test configs. Then point build at production and keep test on default. After that, editing a test reruns tests but leaves the build cached.

Include environment and runtime values

If output depends on NODE_ENV, an API base URL, or the Node version, add { "env": "NODE_ENV" } or { "runtime": "node --version" } to the target's inputs. Otherwise Nx treats builds made with different values as identical.

The two failure modes

Constant misses are expensive but safe, because the work still runs. The second failure mode is worse: undeclared inputs produce matching hashes, so Nx replays a result that should have been recomputed. Broad restore-keys make this more likely because they pull in older entries, which gives a wrong hash more stale results to match against.

What does a complete Nx GitHub Actions workflow look like?

The reference workflow runs as a single job, and the order of its steps matters.

  1. Checkout with fetch-depth: 0. actions/checkout fetches only one commit by default. nx-set-shas and nx affected must walk history back to the base commit, and a shallow clone either fails or treats every project as affected.
  2. actions/setup-node, pinned to the Node version your lockfile was generated with.
  3. Dependency cache restore, then install. Key the cache on the lockfile hash. The install must finish before any Nx command runs, because Nx is itself a dependency in node_modules.
  4. Nx cache restore with actions/cache/restore. Point it at your configured cache directory and use a narrow restore-keys prefix.
  5. nrwl/nx-set-shas. This step exports NX_BASE and NX_HEAD. It has to run before any affected command, or those commands fall back to comparing against the default base and can select the wrong project set.
  6. nx affected -t lint test build. Use one invocation so Nx can schedule tasks across targets and share dependency builds between them.
  7. Nx cache save with actions/cache/save, keyed on github.sha. Use if: always() so that results from tasks that succeeded are kept even when another task fails. Nx only stores successful task results, so a failed task does not add a bad cache entry.

Allow only push events on the default branch to save caches. GitHub scopes caches written by a pull request to that PR's merge ref, so no other branch can read them. They also count against the repository quota and push out the default-branch entries that every PR restores from. Pull requests should restore caches and never save them.

How do you verify caching works and measure the time saved?

Reading the logs

Check the restore step for each cache. Cache restored from key: followed by your primary key is an exact hit. If it shows a restore-key prefix instead, it is a partial hit: you got older contents, and the cache-hit output stays false. Cache not found for input keys is a miss. In the post-job step, Cache hit occurred on the primary key ..., not saving cache is expected after an exact hit. A failed reservation usually means another job saved that key first.

Then check Nx. Restored tasks are tagged [local cache] or [existing outputs match the cache, left as is], and the run summary reports how many tasks were read from cache. Re-run the workflow on an unchanged commit. Every task that ran on the first attempt should come from cache on the second. Any task that doesn't is an inputs problem, not a storage problem.

Measuring

Compare the median wall-clock time over several runs before and after the change, not a single run.

Illustrative estimate (assumed numbers, not a benchmark): assume 200 runs/month, 14 → 8 minutes per run. CI minutes saved = runs × (before − after) = 200 × 6 = 1,200 min/month. Developer wait saved ≈ blocking runs × (before − after). Use only the runs someone actually waits on.

When the Actions cache isn't enough

The Actions cache is scoped by branch and limited by a repository quota. Once PRs keep missing on work already done on sibling branches, consider these options:

Option Hit rate across branches Setup effort Security considerations Cost drivers
Shared remote task cache High Moderate Cache poisoning; restrict who can write Storage, egress
Self-hosted runners, persistent disks High per runner High Leftover state between jobs; runner hardening Machines, maintenance
Clean installs, no task cache None None Smallest attack surface CI minutes

What are the alternatives?

The actions/cache approach is one option among several. The alternatives differ in what they skip and what they cost to run.

Run everything on every commit. Use nx run-many -t lint test build without nx-set-shas or a task cache, and cache only dependencies. This is the simplest correct setup. There is no base SHA to get wrong and no stale output to replay. It works well for small workspaces, and its cost grows with the number of projects.

Use nx affected without a task cache. Keep nx-set-shas and nx affected, but drop the Nx cache layer. Unaffected projects are skipped, but every affected task runs from scratch. This avoids cache quota pressure and poisoning concerns for task outputs. It is a reasonable middle ground when your changes usually touch only a few projects, or when you have not yet audited inputs and outputs.

Use a shared remote task cache. Nx can read and write task results from a remote cache instead of a local directory, so hits are shared across branches, jobs and developer machines. This removes the branch scoping and per-repository quota limits of the Actions cache. In exchange, you must operate or pay for the storage and control who can write to it, because a poisoned entry is served to everyone.

Use self-hosted runners with persistent disks. If the Nx cache directory and package store live on a disk that survives between jobs, no restore or save step is needed, and hits are as fast as local reads. The runner then carries state from one job to the next. Plan for cleanup, disk growth and isolation between untrusted and trusted workloads, and remember that hits only occur on the runner that did the work.

Use workflow-level path filters. GitHub Actions can skip whole workflows based on changed paths with paths and paths-ignore on push and pull_request triggers. This is coarser than nx affected, because it knows nothing about the project graph. It still helps for changes that clearly need no CI, such as documentation-only edits, and it combines with the rest of this setup.

Split the work across parallel jobs. Running lint, test and build in separate jobs, or sharding tests, shortens wall-clock time without reducing total CI minutes. Each job then needs its own dependency restore. If you also cache Nx outputs, give each job its own key prefix as described earlier.

When choosing, start from the bottleneck the logs show. If install dominates, fix dependency caching first. If unaffected projects run, fix nx-set-shas and fetch-depth. If affected tasks rerun on unchanged inputs, fix inputs. Move to a remote cache or persistent runners only when branch scoping and quota are the remaining limits.

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 cache, 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.