What is an Nx custom executor, and when should you write one instead of using run-commands?

An Nx executor is a function that Nx calls to run a target. It receives typed options, defined in a JSON schema, and a context object that describes the workspace and the project. Because Nx validates options against the schema and fills in defaults before the function runs, many projects can share one build behavior and each only sets the options that differ.

The main alternatives are nx:run-commands and inferred targets. nx:run-commands runs a shell string and can be cached once you declare its inputs and outputs. Inferred targets are created by plugins that read existing config files, so there is no target to write by hand.

Approach Best fit Main cost
Inferred targets Tools a plugin already understands Limited control over the generated target
nx:run-commands One project or a simple shell string Options aren't validated, and the logic gets copied between projects
Custom executor A platform team standardizing builds across many backend services TypeScript code you must maintain and test

Write a custom executor when a platform team needs the same validated build contract across dozens of services. Don't write one for a single project, a one-line command, or a case inferred targets already handle.

The cost is real. The platform team owns a local plugin written in TypeScript, and that plugin is coupled to the executor API, which can change between Nx major versions. Even so, the executor function is the easy part. Most of the effort goes into declaring inputs and outputs accurately so the cache never serves a stale artifact.

How does an Nx executor turn a build script into a cacheable task?

When you run a target, Nx first resolves its options by merging the target's defaults, the active configuration, and any command-line overrides into one options object. Validation against the executor schema happens at this point, so a malformed option fails before any hashing or work starts.

Next, Nx computes a hash for the task. The hash combines:

  • The resolved options. Changing a flag such as the build mode produces a different hash.
  • Declared file inputs. These are the file sets listed in the target's inputs, often through named inputs.
  • Runtime and environment inputs. These include command output (for example, a toolchain version) and specific environment variables you list explicitly.
  • Dependency information. This covers the hashes of upstream tasks, or their output files if you declare them.

Nx then checks the local cache, and the remote cache if one is configured. On a hit, it restores the files listed in the target's outputs and replays the stored terminal output. Your executor never runs. On a miss, Nx calls the executor function, which spawns your build script and reports success or failure. If the task succeeds, Nx stores the declared outputs and the captured terminal output under that hash.

This design has two consequences. First, Nx hashes only what you declare. If your script reads a shared config file, a generated header, or an environment variable that is not in the inputs, a change to it will not change the hash, and Nx will restore a stale artifact. Second, wrapping a script does not make it faster. On a miss, the script does the same work as before, plus a small amount of hashing and storage overhead. The speedup comes only from hits.

+------------------------------------------+
| 1 Resolve options: defaults + config +   |
|   CLI overrides, validate vs schema      |
+------------------------------------------+
                     |
                     v
+------------------------------------------+   +-------------------------+
| 2 Compute hash:                          |   | Ignored by hash: files  |
|   resolved options + declared inputs +   |   | or env vars the script  |
|   runtime/env inputs + dependency info   |   | reads but `inputs` omits|
+------------------------------------------+   +-------------------------+
                     |
                     v
+------------------------------------------+
| 3 Check local cache, then remote cache   |
+------------------------------------------+
          |                             |
         hit                           miss
          v                             v
+--------------------+  +--------------------------------+
| Restore `outputs`  |  | Executor spawns build script   |
| Replay terminal    |  | (same work as unwrapped run,   |
| output; executor   |  |  plus hash/store overhead)     |
| never runs         |  +--------------------------------+
+--------------------+                  |
                                        v  on success
                        +--------------------------------+
                        | Store outputs + terminal log   |
                        | under the hash                 |
                        +--------------------------------+

Nx resolves and validates options and computes a hash from declared inputs only. A cache hit restores outputs and replays logs without running the executor. A miss runs the wrapped script at full cost and stores the results on success.

How do you generate a local Nx plugin and executor?

Nx ships generators for scaffolding plugins, so you don't need to hand-wire the plumbing. Install the plugin tooling package (@nx/plugin in current releases), generate a local plugin library, then generate an executor inside it. Generator names and options have changed across Nx releases, so confirm the exact commands against the docs for your installed version before running them.

The executor generator produces four pieces, and each one has a specific job:

  • The implementation file exports a default async function. Nx calls it with the resolved options and a context object, and it returns an object with a success boolean. Your build script logic goes here.
  • schema.json describes the options the executor accepts, including types, defaults, required fields, and descriptions. Nx validates a target's options against it before your code runs, so a misspelled option fails immediately instead of being silently ignored.
  • The TypeScript schema interface mirrors schema.json so the implementation is type-checked. Nx does not generate one from the other. When you change one, update the other by hand.
  • executors.json maps each executor name to its implementation and schema. The plugin's package.json points to this file through its executors field, and that is how Nx finds it.

To use the executor, set a project target's executor field to the plugin's package name and the executor name, separated by a colon, such as @myorg/build-tools:backend-build. Nx resolves local plugins through the workspace's TypeScript path mappings, so you don't need to publish the plugin.

// libs/build-tools/src/executors/backend-build/executor.ts
import type { ExecutorContext } from '@nx/devkit';
import { spawnSync } from 'child_process';

// Mirrors schema.json by hand. Nx does not generate one from the other.
export interface BackendBuildExecutorSchema {
  tsConfig: string;   // path relative to the workspace root
  outputPath: string; // where compiled output is written
}

// Nx calls the default export with options that were already validated against schema.json.
export default async function runExecutor(
  options: BackendBuildExecutorSchema,
  context: ExecutorContext
): Promise<{ success: boolean }> {
  console.log(`Building ${context.projectName} with ${options.tsConfig}`);

  // Run from the workspace root so the relative paths in options resolve consistently.
  const result = spawnSync(
    'npx',
    ['tsc', '-p', options.tsConfig, '--outDir', options.outputPath],
    { cwd: context.root, stdio: 'inherit' }
  );

  // Nx reads only this flag to decide whether the target passed.
  return { success: result.status === 0 };
}

// A project references the executor in its project.json like this:
// "targets": {
//   "build": {
//     "executor": "@myorg/build-tools:backend-build",
//     "options": {
//       "tsConfig": "apps/api/tsconfig.app.json",
//       "outputPath": "dist/apps/api"
//     }
//   }
// }

A minimal executor implementation with its hand-maintained schema interface, plus the project.json target that calls it by <plugin-package>:<executor-name>.

Writing the executor function and designing its schema

The executor is a default-exported async function that receives two arguments: the options for this invocation, already merged from project.json and command-line overrides, and an ExecutorContext. The context gives you context.root (the workspace root), context.projectName, and the project graph, which you use to look up the project's root directory. Resolve the script path and working directory from those values rather than from process.cwd(). Nx can invoke the executor from anywhere in the workspace, and a build that silently runs in the wrong directory may still produce output that gets cached.

Spawn the existing script with child_process.spawn, pass an explicit cwd, and set stdio: 'inherit' so stdout and stderr stream through to the Nx terminal output. Nx captures that output with the cache entry and replays it on a cache hit. Wrap the child's close event in a promise and return { success: code === 0 }. Nx caches only successful runs, so a nonzero exit code must map to success: false.

Designing schema.json

Nx validates the options against schema.json and applies defaults before your function runs. A typo such as target: "prodution" fails immediately with a clear message instead of halfway through a build. Give each property a type and a description, list mandatory fields under required, and use enum for closed sets such as build profiles. The descriptions also document the target for other teams.

Keep the options few and declarative, such as profile, outputPath, and entry. Each option should describe what the build produces. Avoid free-form extraArgs strings. They turn the schema into an escape hatch and hide cache-relevant configuration from anyone reviewing the target.

import { spawn } from 'child_process';
import * as path from 'path';
import type { ExecutorContext } from '@nx/devkit';

// Mirrors schema.json: few, declarative, cache-relevant options
export interface BackendBuildOptions {
  entry: string; // required in schema.json
  outputPath: string; // required in schema.json
  profile: 'development' | 'production'; // enum with a default in schema.json
}

export default async function runExecutor(
  options: BackendBuildOptions,
  context: ExecutorContext
): Promise<{ success: boolean }> {
  // Resolve every path from the context, never from process.cwd()
  const projectRoot = context.projectGraph.nodes[context.projectName!].data.root;
  const cwd = path.join(context.root, projectRoot);
  const script = path.join(context.root, 'tools/scripts/build-backend.mjs');

  const args = [
    script,
    '--entry', options.entry,
    '--out', path.join(context.root, options.outputPath),
    '--profile', options.profile,
  ];

  // stdio 'inherit' streams output to Nx, which stores it with the cache entry
  const child = spawn(process.execPath, args, { cwd, stdio: 'inherit' });

  const code = await new Promise<number | null>((resolve) => {
    child.on('error', () => resolve(null)); // e.g. script could not be started
    child.on('close', (exitCode) => resolve(exitCode));
  });

  // Only exit code 0 counts as success; Nx caches successful runs only
  return { success: code === 0 };
}

An Nx executor that resolves the project directory from the executor context, spawns an existing build script with an explicit cwd and inherited stdio, and maps its exit code to the success result.

How do you declare inputs and outputs so Nx caches backend builds correctly?

Caching is opt-in. Set cache: true on the target, or in targetDefaults in nx.json so every project's build inherits it. Nx then hashes the target's declared inputs and restores its declared outputs on a hit. Anything you leave out of either list is a correctness bug waiting to happen.

Backend scripts tend to read more than their source files. Audit each script for these hidden inputs:

Hidden input Example How to declare it
Toolchain version Go, JDK, or Python interpreter Runtime input, such as { "runtime": "go version" }
Lockfile outside the project Root go.sum or poetry.lock File glob with {workspaceRoot}/...
Build flags and architecture GOARCH, CGO_ENABLED, JAVA_OPTS Env input, such as { "env": "GOARCH" }
Sibling directories ../proto/*.proto Explicit glob, or a dependency on that project
Generated code OpenAPI or protobuf output ^-prefixed named input plus dependsOn

Define a named input such as production in nx.json that excludes tests and docs. Reference it as ^production so changes in dependencies invalidate the hash.

Outputs must cover everything that downstream steps read. That includes binaries or JARs under {projectRoot}/dist, generated clients, and coverage reports. If CI uploads coverage but the coverage file isn't listed in outputs, a cache hit restores the build without the report.

Keep side effects out of cached targets. A Docker push or registry publish should live in its own target with caching off. Otherwise a cache hit silently skips the push.

Finally, set dependsOn: ["^build"] so codegen and shared libraries build first. Their outputs then exist on disk before the dependent target runs, and their hashes feed into the dependent target's hash.

{
  "namedInputs": {
    "default": ["{projectRoot}/**/*"],
    "production": [
      "default",
      "!{projectRoot}/**/*_test.go",
      "!{projectRoot}/docs/**/*"
    ]
  },
  "targetDefaults": {
    "build": {
      "cache": true,
      "dependsOn": ["^build"],
      "inputs": [
        "production",
        "^production",
        "{workspaceRoot}/go.mod",
        "{workspaceRoot}/go.sum",
        "{workspaceRoot}/proto/**/*.proto",
        { "runtime": "go version" },
        { "env": "GOARCH" },
        { "env": "CGO_ENABLED" }
      ],
      "outputs": [
        "{projectRoot}/dist",
        "{projectRoot}/gen",
        "{workspaceRoot}/coverage/{projectRoot}"
      ]
    },
    "docker-push": {
      "cache": false,
      "dependsOn": ["build"]
    }
  }
}

An nx.json that caches Go builds, hashing root lockfiles, sibling protos, the Go version and arch env vars, restoring binaries, generated code and coverage, with the Docker push kept in a separate uncached target.

How can you verify that an Nx cache is not returning stale artifacts?

Caching is only useful if you trust it, so treat verification as a routine you rerun whenever you change inputs, outputs, or the executor itself.

A four-step cache check

  1. Repeat run. Run the target twice with no changes. The second run should report a local cache hit. If it doesn't, something nondeterministic is entering the hash, such as a timestamp or an environment variable you didn't intend to include.
  2. Relevant change. Edit a source file the build actually compiles and rerun. You should see a miss. A hit here means your inputs are too narrow, and that is the dangerous case because it ships stale binaries.
  3. Irrelevant change. Edit a README or a test fixture that you excluded. You should get a hit. A miss means your inputs are too broad, which costs time but not correctness.
  4. Restore check. Delete the output directory and rerun without changing anything. Nx should restore the artifacts from cache. If the directory stays empty, your outputs paths don't match where the script actually writes.

When a result surprises you, look at what went into the hash. Depending on your Nx version, the task graph view in nx graph or the project details command shows the resolved inputs and hash details for each task. Use --skip-nx-cache to force a clean comparison run.

Testing the executor

Unit-test the executor function by mocking the process spawn. Assert that options map to the expected arguments, and that non-zero exit codes and spawn errors produce { success: false }. Also keep a small fixture project in the workspace and run the real target against it in CI, so that schema defaults and path resolution get exercised end to end.

What are the trade-offs and risks of caching backend builds with Nx?

Caching moves risk around rather than removing it, and the two input mistakes are not equally bad:

Mistake Symptom Cost
Under-declared inputs Cache hit after a relevant change A stale artifact ships with no warning
Over-declared inputs Misses on irrelevant changes Wasted rebuilds plus extra hashing time

A false hit is worse than having no cache, because nobody thinks to question a green build. Start conservative, with the whole project and shared config as inputs. Narrow them only after the stale-artifact checks pass.

Non-determinism has to be fixed in the script itself. Embedded timestamps, git SHAs, random build IDs and absolute paths make identical inputs produce different outputs, which breaks any output comparison. Inject those values at deploy time instead.

Toolchains installed on the machine, such as a JDK, Go or system compilers, do not affect the hash. If you need them to, add a runtime input that prints their version.

A remote cache widens the blast radius. One bad entry reaches every developer and pipeline, and you have to decide who is allowed to write artifacts. Treat this as a security decision and follow Nx's own documentation on access control.

Large outputs such as fat JARs or image layers can cost more to upload and restore than to rebuild. Cache the compile step and leave packaging uncached.

The time saved depends on how often inputs stay unchanged across branches and CI runs. Illustrative estimate, using assumed inputs:

  • an 8-minute build
  • 200 CI runs per week
  • a 60% hit rate
  • 30 seconds to restore a hit

That gives 120 hits × 7.5 minutes saved, or about 15 hours of CI time per week.

Alternatives to consider

run-commands with explicit inputs and outputs

If the executor only shells out to a script, you may not need custom code. A run-commands target with well-defined inputs, outputs, and named input sets in nx.json is cached in exactly the same way. Nx hashes the target configuration and the declared inputs, not the executor's internals. You lose schema validation, typed options, and shared defaults across projects. You avoid maintaining a plugin. This works well when only one or two projects use the script.

Inferred tasks from a plugin

A plugin can create targets automatically by detecting files such as a build config in each project, instead of you declaring them in every project.json. This fits when many projects follow the same convention. The cost is indirection: engineers must run nx show project to see what a target actually does.

The toolchain's own incremental build

Many compilers and build tools keep a local incremental cache. That cache works below the task level, so it can reuse partial work after a small change. Nx can only replay a whole task. The two approaches complement each other, but the native cache usually doesn't carry over between CI machines.

CI-level directory caching

Caching dependency or build directories in your CI system, keyed on a lockfile hash, is coarse-grained. It is also simple. It suits expensive, rarely changing steps like dependency installation better than per-project builds.

Container image layer caching

If the deliverable is an image, ordering layers carefully gives you reuse without a separate cache. However, any change to an earlier layer invalidates every layer after it.

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.