> ## Documentation Index
> Fetch the complete documentation index at: https://docs.blacksmith.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# Nx Build Caching

> Blacksmith restores Nx task outputs across runs

## Overview

Blacksmith acts as the remote cache for Nx. When a task runs, Nx archives the files it declares as `outputs` and Blacksmith stores the archive under the task's hash. A later job with the same hash restores the archive instead of rerunning the task. Nx caching is off by default. Unlike the other build caches, correctness depends on configuration in your repository that Nx does not verify, so read [Before you enable](#before-you-enable) before turning it on.

## Enable Nx build caching

Nx build caching is off by default. An organization admin can turn it on or off from [**Settings > Caching**](https://app.blacksmith.sh/settings/caching) in the Blacksmith dashboard, under **Build systems**. The switch is **Nx build cache**. The change applies to the next job. Turning it off deletes the organization's Nx cache.

![An admin turning on Nx build cache in Settings > Caching](https://mintcdn.com/blacksmith/MQ-ynRVrOUv23S_z/images/embeds/settings-caching.png?fit=max\&auto=format\&n=MQ-ynRVrOUv23S_z\&q=85\&s=e677f9e566a39b3544a6ffcc7bf8c1a6)

**An admin turning on Nx build cache in Settings > Caching**

Each repository has its own cache. It is shared across branches and pull requests, and split by CPU architecture.

If a job already uses Nx Cloud or `NX_SELF_HOSTED_REMOTE_CACHE_SERVER`, Blacksmith leaves that configuration in place. Remove that setup to use this cache. Jobs and steps that run in a [`container:`](https://docs.github.com/en/actions/using-jobs/running-jobs-in-a-container) use the cache too, unless the container configures Nx Cloud or `NX_SELF_HOSTED_REMOTE_CACHE_SERVER` itself.

Restored tasks show `[remote cache]` in the Nx run summary. The [Cache page](https://app.blacksmith.sh/cache) shows hit rate and storage for each repository on its **Nx** tab.

## Branch protection

Build cache branch protection is available in [**Settings > Caching**](https://app.blacksmith.sh/settings/caching), under **Dependencies**. When enabled, only jobs running on the default branch (`push`, `schedule`, `workflow_dispatch`) or in a merge queue can write to the cache. Every other job gets read-only access. The setting is off by default and applies to every build cache at once.

Fork pull requests get no Nx remote cache at all, regardless of this switch.

## Before you enable

Nx restores exactly what a target declares and never checks the declaration. Complete both steps for every target with `cache: true` before you turn the switch on, then [verify cache behavior](#verify-cache-behavior).

### 1. Declare what each target reads and writes

| Setting | Rule |
| - | - |
| `inputs` | Every file and environment variable the task reads. A file outside `{projectRoot}` needs `"{workspaceRoot}/<path>/**/*"`, or the project that owns it in `implicitDependencies` plus `"^default"`. `dependsOn` hashes nothing. Globs skip gitignored files. `{ "fileset": "<glob>", "includeIgnored": true }` hashes them on Nx 23.3+ and is silently ignored before that. Environment variables go in as `{ "env": "NAME" }`. |
| `outputs` | Every file the task writes, including files written next to the source. A cache hit restores only these. |
| `dependsOn` | Every task whose output this task reads. Without it Nx can run both at once and the reader sees a half-written file. |
| `cache` | `false` for any task that reads external state: a database, the network, the clock. |

```json theme={"system"}
{
  "targets": {
    "build": {
      "cache": true,
      "dependsOn": ["^build", "schema:generate"],
      "inputs": ["default", "{workspaceRoot}/shared/schema/**/*", { "env": "DEPLOY_TARGET" }],
      "outputs": ["{projectRoot}/dist", "{projectRoot}/src/bundle.iife.js.txt"]
    }
  }
}
```

### 2. Check the declarations

```bash theme={"system"}
nx show target inputs <project>:<target>    # Nx 22.6+. Compare with every path the task's script opens.
nx show target outputs <project>:<target>   # Compare with every path the task's script writes.
nx show projects --affected --files=<file the task reads>   # <project> must be in the output.
```

Code-generation targets fail the third check most often: they read sources owned by another project (locale files, schemas, API specs), so the generated output goes stale when those files change.

## Verify cache behavior

Turn on **Nx build cache**, run this workflow from your default branch, and fix declarations until `diff` passes. Then change a file a code-generation target reads and run it again: that task must run, not restore.

```yaml theme={"system"}
name: Validate Nx cache
on: workflow_dispatch
env:
  TARGETS: build test lint # every target with cache: true
  HASH: find . -type f -not -path '*/node_modules/*' -not -path './.git/*' -not -path './.nx/*' | sort | xargs sha256sum

jobs:
  populate:
    runs-on: blacksmith-8vcpu-ubuntu-2404
    steps:
      - uses: actions/checkout@v4
      - run: npm ci && npx nx run-many -t $TARGETS
      - run: eval "$HASH" > /tmp/populate.sha256
      - uses: actions/upload-artifact@v4
        with: { name: populate, path: /tmp/populate.sha256 }

  restore:
    needs: populate
    runs-on: blacksmith-8vcpu-ubuntu-2404
    steps:
      - uses: actions/checkout@v4
      - run: npm ci && npx nx run-many -t $TARGETS | tee /tmp/nx.log
      - run: grep -q 'read the output from the cache' /tmp/nx.log # fails if nothing was restored
      - run: eval "$HASH" > /tmp/restore.sha256
      - uses: actions/download-artifact@v4
        with: { name: populate, path: /tmp }
      - run: diff /tmp/populate.sha256 /tmp/restore.sha256
```

Reading a failed `diff`:

* File only in `populate.sha256`: the task writes it but `outputs` does not list it.
* Same file, different hash: `inputs` is missing something the output depends on, or the generator is not deterministic (timestamps, random identifiers). Exclude those files from `HASH` or fix the generator.

## Troubleshooting

Missing files (`ENOENT`, `Module not found`) or outdated generated types after a `[remote cache]` line can indicate incomplete cache configuration. Temporarily turn off **Nx build cache** while you investigate. Check the affected task's `inputs`, `outputs`, and `dependsOn`, then [verify the corrected configuration](#verify-cache-behavior) before enabling caching again. A changed configuration changes the task hash, so the old entry is not read.

Nx's guides to [configuring inputs](https://nx.dev/docs/guides/tasks--caching/configure-inputs) and [configuring outputs](https://nx.dev/docs/guides/tasks--caching/configure-outputs) cover the full rules.
