What is an Nx custom executor, and when is it the right tool?

An Nx custom executor is a Node function that Nx calls when it runs a target. It receives the target's resolved options and a context object describing the workspace and project. It reports success or failure back to Nx. A JSON schema describes the options, so Nx validates input and fills in defaults before your code runs.

Platform and backend engineers write executors for four practical reasons:

  • Typed options. Teams configure a target through named, documented fields instead of hand-built shell strings.
  • Validation. Mistakes fail before the tool starts.
  • Shared logic. Many projects use one implementation.
  • Process control. You decide how the child process is spawned, what environment it sees, and how its exit code maps to success.

The underlying reason is cache correctness. Caching only works when a target's inputs and outputs are declared accurately. An executor lets you standardise those declarations once, so individual projects don't each have to get them right.

Approach Option typing Reuse across projects Maintenance cost Process control
run-commands target Loose strings and args Copy per project Low at first, grows with drift Shell-level only
Inferred targets from a plugin Derived from tool config files Automatic for matching projects Moderate, lives in plugin code Limited to what the plugin emits
Custom executor Schema-validated One implementation, many targets Highest, it is real code Full

A run-commands target is enough for a single command in a few projects. Inferred targets fit when the tool already has a config file Nx can detect. Reach for an executor only when many projects need the same tool with consistent options and cache rules. Treat it as platform code: the platform team should own and version it, not whichever product team wrote it first.

How does an Nx custom executor fit into a local Nx plugin?

A local plugin is an ordinary package inside the workspace, often under tools/ or libs/, that Nx resolves by its package name. Its package.json contains an executors field. That field either points to a separate executors.json file or holds the map directly. Each entry in the map pairs an executor name with two paths:

  • implementation: the module that exports the executor function.
  • schema: the JSON schema that describes and validates the options.

A project opts in by setting a target's executor to <plugin>:<executor>, for example @acme/backend-tools:migrate-check. The part before the colon is the package name, so Nx must be able to resolve it from the workspace root. That usually happens through a workspace package link or a TypeScript path mapping. If resolution fails, every project using the target fails along with it. This is why platform teams keep the plugin's package name stable.

Nx checks the cache before the executor runs. The flow looks like this:

project.json target → merge options (target defaults, then options, then configuration, then CLI flags) → resolve <plugin>:<executor> via package.json and the executors map → compute hash from the target's inputs → cache hit?

  • Yes: restore the declared outputs, replay the logged terminal output, and skip the executor entirely.
  • No: validate options against the schema, call the implementation, spawn the backend tool, then store the outputs and logs under the hash.

On a hit, your implementation code never runs. Any side effect it performs outside the declared outputs is therefore lost on a cache hit, which section 4 addresses.

# tools/backend-tools/package.json: the package name is the <plugin> half
{
  "name": "@acme/backend-tools",
  "version": "0.0.1",
  "executors": "./executors.json"
}

# tools/backend-tools/executors.json maps executor names to code and schema
{
  "executors": {
    "migrate-check": {
      "implementation": "./src/executors/migrate-check/executor",
      "schema": "./src/executors/migrate-check/schema.json",
      "description": "Runs the backend migration checker"
    }
  }
}

# apps/orders-api/project.json: the target references <plugin>:<executor>
{
  "name": "orders-api",
  "targets": {
    "migrate-check": {
      "executor": "@acme/backend-tools:migrate-check",
      "cache": true,
      "inputs": ["{projectRoot}/migrations/**/*"],
      "outputs": ["{workspaceRoot}/dist/reports/orders-api"],
      "options": {
        "migrationsDir": "apps/orders-api/migrations",
        "reportDir": "dist/reports/orders-api"
      }
    }
  }
}

This example shows a local plugin whose package.json points to an executors.json map, and a project.json target that calls the executor as @acme/backend-tools:migrate-check, with the inputs and outputs Nx uses to compute the hash and restore results on a cache hit.

How do you write the executor schema and implementation?

Schema first, interface second

Start with schema.json. Give every option a type and a description, put safe values in default, and list only the options without a safe default under required. Set additionalProperties to false so a mistyped option in project.json fails validation instead of being silently ignored. Nx validates options against this schema and applies its defaults before your code runs, and editors use the descriptions for completion.

The TypeScript Options interface describes the same shape, and nothing enforces that the two match. Treat the schema as the source of truth. Either generate the interface from it with a JSON Schema-to-TypeScript generator as a build step, or add a unit test that loads the schema and checks its property names and required list against a typed fixture. Either approach makes a renamed option fail CI rather than cause a runtime undefined.

The executor function

The executor receives the resolved options and a context. From the context, read the workspace root, the project name, and that project's configuration. Resolve the project root against the workspace root and pass it to spawn as an explicit cwd. Nx may be invoked from any directory, so relying on process.cwd() gives inconsistent results.

Use stdio: 'inherit' so stdout and stderr stream live and Nx captures them for the cache. Forward SIGINT and SIGTERM to the child so that cancelling the run does not leave orphaned processes. Resolve { success: code === 0 }. A null exit code means the process was killed by a signal, and it must count as failure. If it counts as success, Nx caches the broken run.

Put argument building, config lookup, and path resolution in plain functions. You can unit-test those without Nx, and the executor then only connects them together.

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

// Mirrors schema.json; a unit test checks the two stay in sync.
export interface MigrateOptions { configFile: string; dryRun: boolean; extraArgs: string[]; }

// Tool-specific logic lives in plain functions you can test without Nx.
export function buildArgs(o: MigrateOptions): string[] {
  const args = ['--config', o.configFile];
  if (o.dryRun) args.push('--dry-run');
  return [...args, ...o.extraArgs];
}

export default async function runExecutor(
  options: MigrateOptions,
  context: ExecutorContext,
): Promise<{ success: boolean }> {
  const name = context.projectName;
  const project = name ? context.projectsConfigurations?.projects[name] : undefined;
  if (!project) return { success: false };
  // Explicit cwd: Nx can be invoked from any directory.
  const cwd = path.resolve(context.root, project.root);
  const child = spawn('dbmigrate', buildArgs(options), { cwd, stdio: 'inherit' });
  // Forward cancellation so the child is not orphaned.
  const forward = (sig: NodeJS.Signals) => child.kill(sig);
  process.on('SIGINT', forward);
  process.on('SIGTERM', forward);
  return new Promise((resolve) => {
    const done = (success: boolean) => {
      process.off('SIGINT', forward);
      process.off('SIGTERM', forward);
      resolve({ success });
    };
    child.on('error', () => done(false)); // e.g. binary not found
    // code is null when killed by a signal: that must be a failure.
    child.on('close', (code) => done(code === 0));
  });
}

A thin Nx executor that resolves the project root from the context, spawns a placeholder tool with an explicit cwd and inherited stdio, forwards SIGINT/SIGTERM, and reports success only when the exit code is exactly 0.

How do you make a custom executor target safely cacheable?

Caching is opt-in per target. Set cache: true on the target in project.json, or set it once under targetDefaults keyed by target name so every project using the executor inherits it. Which one you use depends on whether your workspace keeps shared defaults in nx.json or keeps each project self-describing.

Declare outputs with tokens, such as {projectRoot}/generated or {workspaceRoot}/dist/{projectRoot}. On a cache hit, Nx restores only these paths. Any file the tool writes elsewhere is missing after a hit, and nothing warns you.

Inputs determine the cache key, so declare them precisely:

  • Start from a named input such as production. Define it as the project's source globs minus !{projectRoot}/**/*.spec.* and docs, so editing a test doesn't invalidate a codegen run.
  • Add the tool's config files explicitly. They often sit outside the source globs.
  • Add a runtime input that prints the tool's version string. Upgrading the binary should miss the cache.
  • Add env inputs for variables that change the tool's output, such as a target dialect or feature flag.

Put dependsOn: ["codegen"] on build so generated code exists before compilation. When codegen hits the cache, Nx restores its outputs and build hashes them as ordinary files.

Mistake Symptom Fix
Under-declared inputs (missing config file, env var, tool version) Stale output after a change Add file, env, or runtime inputs
Over-broad globs ({projectRoot}/**/*) Cache misses on test or README edits Use production with exclusions
Undeclared outputs Cache hit leaves files missing List every written path in outputs
{
  "namedInputs": {
    "default": ["{projectRoot}/**/*"],
    "production": [
      "default",
      "!{projectRoot}/**/*.spec.*",
      "!{projectRoot}/**/*.md",
      "!{projectRoot}/docs/**/*"
    ]
  },
  "targetDefaults": {
    "codegen": {
      "executor": "@myorg/tools:codegen",
      "cache": true,
      "inputs": [
        "production",
        "{workspaceRoot}/codegen.config.json",
        "{projectRoot}/codegen.local.json",
        { "runtime": "mytool --version" },
        { "env": "CODEGEN_DIALECT" },
        { "env": "CODEGEN_FEATURE_FLAGS" }
      ],
      "outputs": ["{projectRoot}/generated"]
    },
    "build": {
      "cache": true,
      "dependsOn": ["codegen", "^build"],
      "inputs": ["production", "^production"],
      "outputs": ["{workspaceRoot}/dist/{projectRoot}"]
    }
  }
}

An nx.json that caches a custom codegen executor through targetDefaults, with token-based outputs, a production named input excluding tests and docs, config, runtime and env inputs, and a build target that depends on codegen.

Is your backend tool deterministic enough to cache?

Declaring inputs and outputs correctly only helps if the tool produces the same outputs from the same inputs. Nx hashes what you declare and nothing else. Before you set cache: true, check the tool against this list:

Risk Typical symptom Mitigation
Timestamps or absolute paths in generated files Artifacts differ byte-for-byte between runs or machines Disable build-time stamping; use relative paths or path-trimming flags
Nondeterministic ordering Archives or codegen output reorder entries per run Sort file lists; use the tool's reproducible-build options
Network fetches during the build Output changes when an upstream package or schema changes Pin versions with lockfiles; fetch in a separate, uncached step
Global binaries whose version isn't captured Old cache entries replayed after a toolchain upgrade Add a runtime input that prints the tool's version
Global caches or user-level config (~/.m2, GOMODCACHE, settings.xml, GOFLAGS) Laptop and CI produce different artifacts from identical sources Pin these via env inputs or project-local config

The last two rows deserve the most attention. They live outside the workspace, so Nx cannot see them unless you name them explicitly.

A miss costs you time. A stale hit costs you correctness. When Nx restores outputs from a hash that didn't capture a relevant input, you get the wrong artifact, and nothing tells you so. That artifact can be a JAR built against an old dependency, or a Go binary compiled with a different toolchain. If it passes CI and ships, debugging it means first suspecting the cache, and that is rarely anyone's first guess. If you can't make the tool deterministic, leave the target uncached.

How do you verify that the cache actually works?

Treat the cache as a claim you have to prove, using a fixed sequence against a single project. Start from a clean state with nx reset, then:

  1. Run twice, expect a hit. Run nx run api:build two times. The second run should report that it read the output from the cache. If it executes again, something in the inputs changes between runs, such as a timestamp or an absolute path, and later steps will mislead you.
  2. Change a relevant file, expect a miss. Edit a source file the tool actually reads, then rerun. A hit here is the dangerous failure, because it means your inputs are too narrow and Nx will return stale artifacts.
  3. Change an irrelevant file, expect a hit. Edit a README or a test fixture that the tool ignores. A miss means your inputs are too broad. That is safe, but it erases the benefit of caching.
  4. Delete the outputs, expect a restore. Remove the output directory and rerun. Nx should restore the files from cache. If the directory stays empty, outputs doesn't match where the tool really writes.

Remote or shared caches add risks in CI. An artifact built on one agent's toolchain gets served to every other agent. A pull request from an untrusted branch can write poisoned entries. Outputs can also leak secrets that were baked in at build time. Restrict cache writes to trusted pipelines, and include the toolchain version in the inputs.

Finally, add unit tests for option handling. Mock the process-spawn module and assert on the exact command and arguments the executor builds for each combination of options. These tests run in milliseconds and catch option-mapping bugs before those bugs reach the cache.

#!/usr/bin/env bash
# Empirical cache check for one project. Paths are placeholders; adjust to your workspace.
# Assumes a clean git working tree so the edits can be reverted afterwards.
set -euo pipefail
PROJECT=api
SRC=apps/api/src/main.ts      # a file the tool really reads
DOC=apps/api/README.md        # a file the tool ignores
OUT=dist/apps/api             # must match the target's `outputs`

# Nx prints this phrase on a cache hit; check the exact wording for your Nx version.
expect() {  # usage: expect hit|miss "label"
  if nx run "$PROJECT:build" | tee /dev/stderr | grep -q 'read the output from the cache'; then got=hit; else got=miss; fi
  [ "$got" = "$1" ] && echo "PASS: $2 ($got)" || { echo "FAIL: $2 expected $1, got $got"; exit 1; }
}

nx reset                                  # clear the local cache and daemon state

expect miss "first run populates cache"
expect hit  "1. identical rerun"          # a miss means non-deterministic inputs

echo '// cache probe' >> "$SRC"
expect miss "2. relevant file changed"    # a hit means inputs are too narrow (stale artifacts)
git checkout -- "$SRC"
expect hit  "   revert restores old hash"

echo 'cache probe' >> "$DOC"
expect hit  "3. irrelevant file changed"  # a miss means inputs are too broad
git checkout -- "$DOC"

rm -rf "$OUT"
expect hit  "4. outputs deleted"
[ -n "$(ls -A "$OUT" 2>/dev/null)" ] && echo "PASS: outputs restored" \
  || { echo "FAIL: $OUT empty; outputs config does not match tool"; exit 1; }

A shell script that runs the four-step cache check against one project, asserts a hit or a miss at each step, and fails if the outputs are not restored from cache.

When should you avoid a custom executor, and what does it cost to maintain?

Some targets should stay uncached. A migration against a live database produces its real effect in the database, not in files Nx can restore. A cache hit would report success without applying anything. The same applies to anything that depends on network responses, secrets fetched at runtime, or other external state that your declared inputs cannot capture. You can still wrap these tools as executors to get consistent options and logging. Leave caching disabled on those targets.

Large binary outputs, such as JVM archives or Go binaries, need a measurement before you cache them. Restoring a large artifact from a remote cache can take nearly as long as rebuilding it, and you also pay for storage and transfer. Compare restore time against build time in your own CI before you commit to caching.

Illustrative estimate (assumed numbers, not a benchmark). Use this formula:

weekly saving = cache hits × (build time − restore time) − maintenance time

Assume the following inputs:

  • 200 hits per week
  • 90 s build time
  • 20 s restore time

That gives 200 × 70 s ≈ 3.9 hours saved per week. If restore time rises to 80 s, the saving drops to about 33 minutes. That margin can disappear against the maintenance cost.

Maintenance is real. Devkit and plugin APIs change across major Nx versions, so every upgrade means checking executor signatures, context fields, and schema handling.

The payoff comes from three places:

  • Skipped rebuilds: cache hits avoid repeated build work.
  • Shared validated options: misconfigured flags fail at the schema instead of mid-build.
  • Discoverable documentation: the schema documents the target where nx show project and editors can surface it.

If your executor only forwards arguments to one command, use nx:run-commands with explicit inputs and outputs instead. If the tool has a recognizable config file, inferred targets from a plugin may cover it with less code.

Alternatives to consider

Plain package.json scripts

Nx picks up scripts from a project's package.json as targets, and you can attach inputs, outputs, and cache settings through the nx property in the same file or through targetDefaults in nx.json. This suits teams that want build commands to stay runnable with a standard package manager, without requiring Nx. The tradeoff is that options are passed as raw CLI strings. Nothing validates them before the tool runs.

Inferred targets through createNodes

A local plugin can scan for a tool's config file and generate targets automatically, with inputs and outputs derived from that config. Compared with an executor, this addresses discovery rather than execution. Every project that contains the config file gets a correctly cached target, and nobody has to edit project.json. You can combine the two approaches: the inference logic decides where targets exist, and a custom executor or nx:run-commands decides how each one runs.

The tool's own incremental cache

Some backend tools already maintain a fine-grained cache keyed on their own dependency graph. Adding Nx caching on top can duplicate storage and give you two cache keys that disagree. In that case, it can be better to leave the target uncached in Nx and rely on Nx only for orchestration and affected-project detection.

Thin shell wrappers

A versioned script in the repository, called through nx:run-commands, keeps logic in a language every engineer can read and debug. Choose a custom executor only when you need typed options, programmatic access to the project graph, or structured output.

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.
  • 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.