How does Nx caching decide whether a target is a cache hit?

Before Nx runs a cacheable target, it computes a hash from everything the target says it depends on. If that hash matches a previous run, Nx skips execution entirely. It restores the files listed in the target's outputs and replays the terminal output that was captured the first time. Any process reading the log sees the same output it would see from a real run.

The hash is built from:

  • Source files matched by the target's inputs, usually through named inputs such as default or production defined in nx.json.
  • Environment variables declared as env inputs.
  • Runtime values declared as runtime inputs. Each one is a command whose output is hashed, for example a toolchain version check.
  • Dependency outputs, when the target depends on build artifacts of upstream projects.
  • Target configuration, meaning the executor name and its resolved options. For run-commands, the command string itself is part of this, so editing the command invalidates the cache.

Nx does not observe what your build actually reads. It does not trace file access or inspect the process environment. Suppose your backend build reads a config file outside the project root, a GOFLAGS variable, or the installed JDK version, and none of those are declared. Nx will return a cache hit after they change, and you get a stale artifact with no warning. The same applies to outputs: a directory the build writes but outputs doesn't list will not be restored on a hit.

This holds whether the target uses run-commands or an Nx custom executor. A custom executor gives you a cleaner interface and typed options. It does not let Nx see dependencies you haven't declared.

 DECLARED INPUTS (visible to Nx)         UNDECLARED (invisible to Nx)
+--------------------------------+       +------------------------------+
| source files (named inputs)    |       | config file outside project  |
| env inputs                     |       | GOFLAGS (not in env inputs)  |
| runtime inputs (cmd output)    |       | installed JDK version        |
| dependency outputs             |       | dirs written, not in outputs |
| target config (executor+opts)  |       +------------------------------+
+--------------------------------+                      |
               |                                        X  not hashed
               v
      +------------------+
      |  compute hash    |
      +------------------+
               |
               v
      +------------------+   no   +--------------------------+
      | hash in cache?   |------->| run executor             |
      +------------------+        | (run-commands or custom) |
               | yes              | store outputs + terminal |
               v                  +--------------------------+
      +------------------------------+
      | skip execution               |
      | restore declared outputs     |
      | replay terminal output       |
      +------------------------------+

Nx hashes only the declared inputs to decide hit or miss, so changes to undeclared files, variables, or toolchain versions still produce a cache hit, whether the target uses run-commands or a custom executor.

How do you make a backend build script cacheable with run-commands?

The cheapest way to get caching is to leave your build script alone and let Nx call it. Add a build target to the project's project.json with executor set to nx:run-commands and the command option set to whatever you already run, such as ./scripts/build.sh or go build -o dist/server ./cmd/server. Set cwd to the project root so relative paths behave the way they do when someone runs the script by hand. Then add "cache": true, an inputs array, and an outputs array such as {projectRoot}/dist.

Declaring outputs is the step people skip, and skipping it fails without any warning. Suppose you omit outputs, run the build, delete dist/, and run it again. Nx computes the same hash, finds the entry, replays the logged terminal output, and reports success. But no directory was recorded, so nothing is restored. dist/ stays empty, and the deploy step that runs next fails, or ships a stale binary left over from an earlier checkout. Every time you add a cached target, check that a cache hit restores its files.

Once one project works, move cache, inputs, and outputs into targetDefaults in nx.json under the build key. Each service then needs only its command, and a change to the input rules happens in one place.

This approach saves engineering time because there is nothing extra to maintain. The script stays the source of truth, there is no plugin package to version or test, and engineers can still run the script directly when they are debugging.

# Shared cache settings for every project's build target (minimal nx.json).
cat > nx.json <<'EOF'
{
  "targetDefaults": {
    "build": {
      "cache": true,
      "inputs": ["{projectRoot}/**/*", "!{projectRoot}/dist/**/*"],
      "outputs": ["{projectRoot}/dist"]
    }
  }
}
EOF

# Each service only says which existing command to run.
# cwd makes relative paths behave like a manual run from the project root.
cat > apps/api/project.json <<'EOF'
{
  "name": "api",
  "targets": {
    "build": {
      "executor": "nx:run-commands",
      "options": {
        "command": "go build -o dist/server ./cmd/server",
        "cwd": "apps/api"
      }
    }
  }
}
EOF

# Check that a cache hit restores files, not just terminal output.
npx nx build api          # first run: executes and stores dist/
rm -rf apps/api/dist      # simulate a clean checkout
npx nx build api          # second run: should be a cache hit

# If outputs were missing, this check would fail even though Nx reported success.
test -f apps/api/dist/server && echo "restored from cache" || echo "cache hit restored nothing"

Wraps an existing Go build with nx:run-commands, places cache, inputs and outputs in targetDefaults, and checks that a cache hit actually restores dist/.

Which inputs should a backend build target declare?

A backend target's cache key should include everything that can change the artifact, which covers more than the source files. Start with a production named input that takes the project's files and excludes *_test.go, tests/**, docs/** and Markdown. A README edit should not trigger a rebuild. Then add the files that pin dependencies: go.mod and go.sum, pyproject.toml and poetry.lock, or build.gradle.kts, settings.gradle.kts, gradle.properties and gradle/wrapper/gradle-wrapper.properties. The wrapper properties file matters because it pins the Gradle version.

Use ^production so that a change to an upstream library invalidates every project that depends on it. If a dependent consumes compiled output, such as a JAR, a wheel or generated code, rather than sources, the dependentTasksOutputFiles input type can hash those artifacts directly.

Input category Example If omitted
Lockfiles go.sum, poetry.lock Old dependencies are served from cache
Toolchain {runtime: "go version"} A compiler upgrade is ignored
Environment {env: "GOARCH"}, CGO_ENABLED The cached binary targets the wrong platform
Upstream libraries ^production Dependents link against stale code

Over-broad inputs only waste CI minutes, and you can see the waste in cache-miss rates. Under-broad inputs fail silently: the cache returns a confident hit with the wrong binary. When you are unsure whether to include something, include it.

Non-hermetic builds need explicit handling:

  • Dependency downloads at build time. Builds that fetch dependencies while running, such as unpinned pip install or Gradle dynamic versions, cannot be keyed reliably. Pin these versions or vendor the dependencies.
  • System toolchains. Hash them with runtime inputs.
  • Host OS and architecture. Add these as inputs so that a cache entry produced on an ARM laptop never satisfies an x86 CI job.
{
  "name": "orders-service",
  "projectType": "application",
  "namedInputs": {
    "default": ["{projectRoot}/**/*"],
    "production": [
      "default",
      "!{projectRoot}/**/*_test.go",
      "!{projectRoot}/tests/**/*",
      "!{projectRoot}/docs/**/*",
      "!{projectRoot}/**/*.md"
    ]
  },
  "targets": {
    "build": {
      "executor": "@myorg/go-tools:build",
      "cache": true,
      "inputs": [
        "production",
        "^production",
        "{projectRoot}/go.mod",
        "{projectRoot}/go.sum",
        { "runtime": "go version" },
        { "runtime": "uname -sm" },
        { "env": "GOOS" },
        { "env": "GOARCH" },
        { "env": "CGO_ENABLED" }
      ],
      "outputs": ["{workspaceRoot}/dist/{projectRoot}"]
    }
  }
}

A project.json for a Go service whose cached build target keys on non-test sources, upstream production inputs, go.mod and go.sum, the Go toolchain version, the host OS and architecture, and the env vars that change the binary.

When should you write an Nx custom executor instead of using run-commands?

Start with run-commands plus targetDefaults. For most backend builds, a short command, declared inputs and outputs, and a shared default cover what you need. Nx maintains the executor, and anyone who can read a shell command can read the target.

Write a custom executor when the command string starts working against you:

  • The command is long and fragile. Chained &&, quoting that breaks between shells, and environment juggling are hard to review inside JSON.
  • The configuration repeats across dozens of projects. targetDefaults can share options, but if each project still needs its own slightly different command, the copies drift apart.
  • Options need validation and types. An executor's schema rejects a misspelled option before anything runs. A shell string passes bad values through without complaint.
  • The logic is conditional. Branching on configuration, detecting the toolchain, or deciding to skip a step is clearer in TypeScript than in shell.
  • Exit codes and output need structure. For example, you may need to map a compiler's warning exit code to success, or parse its output into a readable error.
Concern run-commands + targetDefaults Custom executor
Maintenance Edit JSON and shell strings Own TypeScript code and a schema
Testing Mostly by running the target Unit tests with a stubbed context
Upgrade burden Nx maintains it You track devkit API changes
Onboarding Readable without context Readers must find and read the plugin

An executor does not make a target cacheable. Caching still depends on the target configuration: cache: true, accurate inputs, and declared outputs. A carefully written executor with wrong inputs will still restore stale artifacts.

What goes into an Nx custom executor inside a local Nx plugin?

An executor is a small set of files that each do one job. Keeping them separate is what lets Nx validate options before your code runs and resolve the executor by name from any project.

The implementation function

The implementation is a default-exported async function. It receives two arguments:

  • The resolved options for the target.
  • An executor context that describes where it is running. The context includes the workspace root, the project name, the target name, and the project configurations.

The context is what lets one executor serve many backend services. You derive paths from the project's root instead of hardcoding them. The function reports the result by returning an object with a success boolean. Nx uses that value to decide the exit status. Nx caches only successful runs, so a missing or wrong return value has real consequences.

schema.json

schema.json is a JSON Schema for the options. It does three things:

  • It declares which properties exist.
  • It marks some of them as required.
  • It supplies defaults.

Nx validates a target's options against this schema and applies the defaults before calling your function. A typo in project.json therefore fails fast with a clear message, rather than producing a silently wrong build.

executors.json and package wiring

executors.json registers each executor by name. Each entry points to the implementation file and its schema. The plugin's package.json declares an executors field that points at executors.json.

A target then references the executor as <package-name>:<executor-name>. For this to resolve, the package name must be reachable from the workspace, for example through a workspace package or a TypeScript path mapping.

Function signatures, context fields, and file conventions have changed across Nx releases. Check all three against the documentation for your installed Nx version.

// tools/backend-plugin/src/executors/build/executor.ts
// Registered in executors.json as "build"; validated by ./schema.json first.
import { ExecutorContext } from '@nx/devkit';
import { execSync } from 'child_process';
import * as path from 'path';

// Mirrors schema.json. Defaults are already applied by Nx before this runs.
export interface BuildExecutorOptions {
  command: string;    // e.g. "go build -o $OUT_DIR/server ./cmd/server"
  outputPath: string; // e.g. "dist/services/orders"
}

export default async function buildExecutor(
  options: BuildExecutorOptions,
  context: ExecutorContext
): Promise<{ success: boolean }> {
  const projectName = context.projectName;
  if (!projectName) return { success: false };

  // Derive paths from the project config so one executor serves every service.
  const projectRoot =
    context.projectsConfigurations?.projects[projectName]?.root;
  if (!projectRoot) return { success: false };

  const cwd = path.join(context.root, projectRoot);
  const outDir = path.join(context.root, options.outputPath);

  try {
    execSync(options.command, {
      cwd,
      stdio: 'inherit',
      env: { ...process.env, OUT_DIR: outDir },
    });
    return { success: true }; // Only successful runs are cached.
  } catch {
    return { success: false }; // Nx reports failure and skips caching.
  }
}

A minimal executor implementation that reads typed options and resolves the project's root from the executor context, then reports success or failure back to Nx; check the ExecutorContext fields against the @nx/devkit version you have installed.

Implementing the executor to wrap a backend build script

The executor spawns the build as a child process and returns its result. Use Node's child_process.spawn with stdio: 'inherit'. Output then streams to the terminal as it is produced, and Nx records it for replay on a cache hit. Buffering the output until exit hides progress on long builds and can truncate large logs.

Resolve with { success: true } only when the exit code is exactly 0. Treat all of these as failures:

  • a non-zero code
  • a null code, which means the process was killed by a signal
  • an error event, for example when the binary is missing

If the executor reports success on any of these, Nx caches a broken build and replays it as a pass.

Do not use process.cwd() for paths. It depends on where the developer ran the command. Take the workspace root from the context, and look up the project root from the project configuration the context exposes. Join the two to get the script path and the cwd you pass to spawn.

Keeping the executor deterministic

Leave cache, inputs, and outputs out of the executor. Set them on the target or in targetDefaults. That keeps caching policy visible in configuration, and changing it does not require a plugin release.

The executor must also uphold the contract those settings describe:

  • Write only to declared output paths. Nx restores only the paths listed in outputs. Anything written elsewhere is missing after a cache hit.
  • Keep run-specific values out of artifacts. Timestamps, absolute paths, and random values make two builds of the same inputs differ. Downstream targets then see changed inputs and miss the cache.
  • Read only declared inputs. Do not read environment variables or files that are not listed in inputs. If you do, a change to them alters the output without changing the hash, and Nx serves a stale artifact.

How do you verify the cache is correct, and when should you avoid caching a target?

A verification routine

Treat a new cached target as untrusted until it passes four checks:

  1. Run it twice. The second run should report a cache hit. If it doesn't, something nondeterministic, such as a timestamp or absolute path, is entering the hash.
  2. Change an undeclared file. Edit a file the build reads but inputs does not list, then run again. A cache hit here means a missing input: the artifact is stale, and Nx has no way to know.
  3. Delete the output directory. Run again and confirm the files come back from the cache intact. If they don't, outputs is wrong or incomplete.
  4. Inspect the computed inputs. Use the project-details or hash-inspection tooling your Nx version provides instead of guessing which files and variables Nx actually hashed. The commands have changed between releases.

When to skip or limit caching

Some toolchains already cache their own work. The Go build cache, the Gradle build cache and incremental compilers keep their own state. Layering Nx on top can store the same artifacts twice. It can also restore outputs that don't match the tool's internal bookkeeping, which leads to confusing partial rebuilds.

Large binary outputs can cost more to archive, upload and extract than to rebuild. Time a cold build against a restore before you commit to caching them.

Remote caching shares one bad artifact with every developer and CI job. Restrict who can write to the cache, and treat write access as you would deploy access.

As an optional next step, a plugin can infer this target for every project that contains a go.mod file. The inference APIs differ across Nx versions, so check the documentation for the version you run.

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 custom executor, 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.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

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.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • 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.