How do Nx targets resolve to an executor?

In Nx, a target never runs a command directly. Every target in project.json (or inferred by a plugin) names an executor, and Nx hands the target's options to that executor. The executor field is a string of the form package:name. Nx resolves the package, reads the executors manifest that the package's package.json points to, and loads the implementation registered under that name.

nx:run-commands is one of these executors, and it ships with Nx itself. Its job is generic: it spawns one or more shell processes, passes through arguments and environment, and reports success or failure from the exit codes. When you write a target with only a command property and no executor, Nx treats it as shorthand for nx:run-commands. That shorthand is why go build ./... or ./gradlew assemble can sit in a target and simply work.

So the real comparison is not "executor vs. no executor." It is a built-in, generic executor versus one you write.

  • nx:run-commands suits engineers who already have working build scripts, such as a Makefile for a Go service, a poetry build step for a Python package, or a Gradle or Maven invocation for a JVM module. The script stays the source of truth, and Nx only orchestrates it.
  • A custom executor suits platform teams who want one typed, validated interface reused across many projects. With it, the build logic lives in TypeScript inside the workspace instead of being copied across shell strings in dozens of targets.
{
  "name": "orders-service",
  "projectType": "application",
  "sourceRoot": "apps/orders-service",
  "targets": {
    "build": {
      "command": "go build -o dist/orders-service ./...",
      "options": {
        "cwd": "apps/orders-service"
      }
    },
    "test": {
      "executor": "nx:run-commands",
      "options": {
        "command": "go test ./...",
        "cwd": "apps/orders-service"
      }
    },
    "package": {
      "executor": "@myorg/backend-tools:go-package",
      "options": {
        "main": "./cmd/server",
        "outputPath": "dist/apps/orders-service",
        "goos": "linux",
        "goarch": "amd64"
      }
    }
  }
}

A project.json with three targets: build uses the command shorthand for nx:run-commands, test names nx:run-commands explicitly, and package points to a custom executor (placeholder package name) that takes typed options instead of a shell string.

How do you wrap a backend build script with nx run-commands?

For a single service, though, nx:run-commands is usually enough. Take a Go API in apps/orders-api. Its build target sets cwd to apps/orders-api so go finds the module's go.mod. Without it, commands run from the workspace root. The commands array then lists go generate ./... followed by go build -o dist/orders-api ./cmd/server.

Set parallel: false here. Nx runs the array concurrently by default, and the build depends on generated code. Use parallel mode only for commands that are truly independent, such as go vet and a lint pass. Even then, output from the commands interleaves, and the exit code tells you only that something failed. You still have to read the logs to find which command it was.

For per-invocation flags, interpolate named arguments with {args.tags}. Leave forwardAllArgs on only if every command can accept whatever extra flags a caller appends.

Pass CGO_ENABLED=0 and GOOS=linux through the env option rather than inline. Inline VAR=value cmd is POSIX syntax that fails under cmd.exe. Single quotes have the same problem, because cmd.exe does not treat them as quoting characters. Each command string is also JSON-escaped before a shell parses it, so quoting mistakes compound. If a command needs more than one layer of quoting, move it into a script file.

Dev servers and watchers such as air or uvicorn --reload belong in a separate serve target with cache: false, since a process that never exits has no output to cache. Make sure Ctrl+C actually reaches the server. If a shell wrapper launches it, use exec so the server replaces the shell and receives SIGINT or SIGTERM directly. Otherwise the server can be orphaned, still holding its port.

{
  "name": "orders-api",
  "targets": {
    "build": {
      "executor": "nx:run-commands",
      "outputs": ["{projectRoot}/dist"],
      "options": {
        "cwd": "apps/orders-api",
        "parallel": false,
        "forwardAllArgs": false,
        "env": {
          "CGO_ENABLED": "0",
          "GOOS": "linux"
        },
        "commands": [
          "go generate ./...",
          "go build -tags={args.tags} -o dist/orders-api ./cmd/server"
        ]
      }
    },
    "check": {
      "executor": "nx:run-commands",
      "options": {
        "cwd": "apps/orders-api",
        "parallel": true,
        "commands": ["go vet ./...", "go test ./..."]
      }
    },
    "serve": {
      "executor": "nx:run-commands",
      "cache": false,
      "options": {
        "cwd": "apps/orders-api",
        "command": "air"
      }
    }
  }
}

A project.json for a Go service: a sequential cached build with env vars and a named {args.tags} argument, a parallel check target for independent commands, and an uncached serve target for the long-running watcher.

How do you make run-commands targets cacheable and correctly ordered?

A run-commands target is not cacheable just because Nx runs it, and neither is a custom executor. Caching is a property of the target configuration. You mark the target cache: true (or set it in targetDefaults) and then tell Nx what goes into the computation and what comes out.

Inputs determine the cache key. Use source globs scoped with {projectRoot}, named inputs such as a production set that excludes tests, and non-file inputs:

  • env entries for variables that change output, such as GOOS or CGO_ENABLED.
  • runtime entries that run a command like go version or rustc --version, so a toolchain upgrade invalidates old artifacts.

If an input is missing, Nx returns a cache hit for an artifact built under different conditions. That is a stale hit, and it is worse than a miss.

Outputs are the paths Nx archives and restores, for example {projectRoot}/dist or {workspaceRoot}/bin/{projectName}. If an output is undeclared, Nx replays the logs on a cache hit but restores no files. Downstream steps then fail or silently use whatever is already on disk.

Determinism matters for both approaches. Embedded build timestamps, dependency fetches during the build, and unlisted environment variables all produce outputs that the cache key does not describe. Pin or strip them.

Ordering belongs in dependsOn. Point it at a codegen or schema-compilation target, or use ^build for shared libraries. Chaining steps with && in one command hides those steps from Nx. It cannot cache them separately, run them in parallel across projects, or skip them when they are unchanged. Separate targets give each step its own cache entry and an accurate project graph.

// apps/api/project.json (Nx reads project.json as JSON with comments)
{
  "name": "api",
  "targets": {
    "codegen": {
      "executor": "nx:run-commands",
      "cache": true,
      // Only the schema affects generated code
      "inputs": ["{projectRoot}/schema/**/*.proto", { "runtime": "protoc --version" }],
      "outputs": ["{projectRoot}/gen"],
      "options": { "command": "protoc --go_out=gen schema/*.proto", "cwd": "apps/api" }
    },
    "build": {
      "executor": "nx:run-commands",
      "cache": true,
      // Ordering lives in the graph: shared libs (^build) and codegen run first
      "dependsOn": ["^build", "codegen"],
      "inputs": [
        "production",                   // named input from nx.json, excludes tests
        "^production",                  // sources of dependency projects
        { "env": "GOOS" },              // env vars that change the binary
        { "env": "CGO_ENABLED" },
        { "runtime": "go version" }     // toolchain upgrade invalidates the cache
      ],
      // Declared so a cache hit restores the binary, not just the logs
      "outputs": ["{workspaceRoot}/bin/{projectName}"],
      "options": {
        // -trimpath and empty buildid strip machine-specific data from the binary
        "command": "go build -trimpath -ldflags=-buildid= -o ../../bin/api ./cmd/api",
        "cwd": "apps/api"
      }
    }
  }
}

A cacheable run-commands build with file, env and runtime inputs, declared outputs, and dependsOn ordering for codegen and shared-library builds.

What does an nx custom executor look like and how does it work?

A custom executor lives in a local plugin, usually a small package inside the workspace that Nx resolves like any other dependency. It has three parts.

executors.json is the registry. It maps each executor name to an implementation file and a schema file. The plugin's package.json points to it through its executors field. A target then refers to the executor as plugin-name:executor-name, the same way it would refer to a published executor.

schema.json is a JSON Schema that describes the executor's options. It declares types, required fields and default values. Nx validates the options merged from project.json, the active configuration and command-line overrides against this schema before your code runs. A misspelled option or a wrong type therefore fails early with a clear message, instead of surfacing as an obscure error deep inside a shell script. The defaults also give every project one documented baseline.

The implementation is an async function, exported as the module's default. It receives two arguments: the validated options, and an executor context. The context carries the workspace root, the name of the project being run, the target and configuration names, and the project configurations. From these, the function can look up the current project's root and sourceRoot without hard-coding any paths. The function returns an object with a boolean success. Nx uses that value to decide the exit status and whether to continue with dependent tasks.

The example that follows is a minimal TypeScript implementation. It resolves the project's root from the context, builds an output path from an option, and reports success.

// tools/build-plugin/src/executors/package-api/executor.ts
import { ExecutorContext, logger } from '@nx/devkit';
import * as path from 'path';

// Mirrors schema.json; Nx has already validated these and applied defaults.
export interface PackageApiOptions {
  outputDir: string; // e.g. "dist/apps" (default declared in schema.json)
  verbose?: boolean;
}

export default async function packageApiExecutor(
  options: PackageApiOptions,
  context: ExecutorContext
): Promise<{ success: boolean }> {
  const projectName = context.projectName;
  if (!projectName) {
    logger.error('Executor must run against a project.');
    return { success: false };
  }

  // Look up this project's config instead of hard-coding paths.
  const project = context.projectsConfigurations?.projects[projectName];
  if (!project) {
    logger.error(`No configuration found for project "${projectName}".`);
    return { success: false };
  }

  const projectRoot = path.join(context.root, project.root);
  const sourceRoot = project.sourceRoot ?? project.root;
  const outputPath = path.join(context.root, options.outputDir, projectName);

  if (options.verbose) {
    logger.info(`target=${context.targetName} config=${context.configurationName ?? 'default'}`);
    logger.info(`root=${projectRoot} src=${sourceRoot} out=${outputPath}`);
  }

  // The real build step would go here (compile, bundle, copy assets...).
  return { success: true }; // Nx uses this to set the exit status.
}

A minimal custom executor that receives validated options and the executor context, resolves the current project's root and sourceRoot from the context's project configurations, builds an output path from an option, and returns a success result.

When should you use a custom executor instead of run-commands, and when should you avoid it?

Choose based on where the logic should live and who will maintain it.

Criterion Prefer run-commands Prefer a custom executor
Projects using the step One or two Many services running the same step
Option complexity A few flags passed into a command Nested, conditional or defaulted options
Project graph data Not needed Needs project roots, dependencies or task context
Ownership and maintenance Service team owns its own script Platform team owns a shared build contract
Testability The script is tested on its own The logic needs unit tests against a mocked context
Readability during incidents The exact command is visible in project.json On-call engineers can read the executor source
Language familiarity The team does not write TypeScript The team already maintains TypeScript tooling

An executor gives you:

  • Typed, validated options. A schema rejects a misspelled option before anything runs.
  • Discoverability. The CLI and editor tooling can read the schema and show the available options.
  • Context access. The executor can read project configuration, the project graph and target metadata.
  • One implementation. A fix lands once and applies to every service that uses it.
  • Structured results. It reports success or failure directly, so you don't have to interpret exit codes and stderr.

The costs are also real. The executor is code you own. It must be compiled from TypeScript before Nx can load it. It needs tests, and it may need changes when Nx major versions alter plugin or executor APIs. In a Go, Rust, Python or JVM team, it adds a language that perhaps one person knows well. It also adds indirection: during an incident, nx show project lists an executor name, not the command that actually runs.

Rule of thumb: copy-pasted run-commands targets become a maintenance problem when one change has to be applied to three or more copies, or when the copies have already drifted apart. Below that point, duplication costs less than an abstraction.

What are the alternatives to writing a custom executor?

Before writing executor code, try the two mechanisms Nx already provides for removing repetition from configuration.

targetDefaults

targetDefaults in nx.json lets you declare inputs, outputs, dependsOn, cache, and default options once per target name. If every backend service defines a build target, the shared parts move to one place, and each project.json keeps only the command that actually differs. This addresses the most common drift: one service gets an updated input glob or dependsOn entry and the others don't. It requires no code to version, test, or publish.

Inference-based plugins

An inference plugin looks for a marker file, such as a build script or toolchain config, and generates targets for every project that contains it. Adding a service then means adding the file, not copying target definitions. A plugin is still code you own, but it only produces configuration. The execution path stays as run-commands or the underlying tool, which is easier to debug than a custom runtime.

Why executors often come too early

An executor fixes an interface: its option schema, how it reports success, and how it handles errors. If you write one while the build steps are still changing, you will keep revising that interface, and every consuming project changes with it. Wait until the configuration has stabilized and the remaining duplication is in behavior, not just settings.

Moving to an executor does not remove toolchain management either. If the executor calls an external compiler or SDK, that tool's version still has to be pinned and listed as a cache input. If it isn't, Nx can return a cached artifact that was built with a different tool version.

How do you migrate from run-commands to a custom executor without breaking CI?

Keep the target name fixed for the whole migration and change only what sits behind it. CI pipelines, nx affected invocations, and developer habits all refer to project:target, so none of them notice the switch.

Stage 1: run-commands as the baseline

Start with the existing script wrapped in nx:run-commands. Run it with nx run api:build --verbose to see the exact command, working directory, and full error output. This version is the behavioral reference for later stages, so record what it produces: artifact paths, exit codes on failure, and any environment variables it reads.

Stage 2: consolidate into targetDefaults

Move inputs, outputs, cache, and dependsOn into targetDefaults in nx.json. Then inspect the merged result with nx show project api --json and confirm the effective configuration still matches what each project had before. This catches silent drift, such as a project-level override replacing a default you expected to merge. You fix caching rules in one place instead of across many project.json files.

Stage 3: promote to a local executor

Point the same target at the new executor. Unit-test the executor function directly by passing it an options object and a minimal fake context, then asserting on the returned success value and on the arguments sent to a mocked process spawner. These tests run in milliseconds and need no workspace. For the actual shell commands, add a small integration test that runs the target against a fixture project and compares the artifacts with the Stage 1 reference. Merge only when the two match, so CI never sees a behavioral change.

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.