What does nx:run-commands do, and why does it cover most targets?

nx:run-commands is the executor Nx ships for running arbitrary shell commands as a target. You declare the commands in the project's target configuration, and Nx runs them with the same task-graph, caching and dependency handling it gives any other target. There is no TypeScript and no plugin package to maintain. The behaviour comes entirely from a small set of options:

  • commands: one or more shell commands. Each entry can be a plain string or an object, so you can attach settings such as a prefix for its output.
  • cwd: the working directory, usually the project root, so the tools pick up local config files.
  • parallel: whether the commands run concurrently or in sequence. Use sequential runs when a later step depends on an earlier one, such as generating code before compiling.
  • Argument forwarding: extra arguments passed after -- on the command line are appended to the commands. Named arguments can also be interpolated into the command strings.
  • readyWhen: a string to watch for in the output of a long-running process, such as a dev server or a local database. When the string appears, Nx treats the process as ready instead of waiting for it to exit.

Most targets in a backend or platform repo are thin wrappers around a CLI:

  • a compiler or bundler for build
  • a linter
  • a migration tool pointed at a database URL
  • a deploy script that pushes an image or applies manifests

Each of these is a single invocation with a few flags, and run-commands expresses that directly. For teams whose targets look like this, which is most teams, it is the right default. Anyone who can read a shell command can read the configuration.

{
  "name": "api",
  "targets": {
    "build": {
      "executor": "nx:run-commands",
      "outputs": ["{projectRoot}/dist"],
      "options": {
        "commands": ["./scripts/codegen.sh", "tsc -p tsconfig.build.json"],
        "parallel": false,
        "cwd": "apps/api"
      }
    },
    "lint": {
      "executor": "nx:run-commands",
      "options": { "command": "eslint src", "cwd": "apps/api" }
    },
    "migrate": {
      "executor": "nx:run-commands",
      "options": { "command": "./scripts/migrate.sh up", "cwd": "apps/api" }
    },
    "deploy": {
      "executor": "nx:run-commands",
      "options": {
        "command": "./scripts/deploy.sh --env={args.env}",
        "cwd": "apps/api"
      }
    },
    "serve": {
      "executor": "nx:run-commands",
      "options": {
        "commands": [{ "command": "node dist/main.js", "prefix": "api" }],
        "cwd": "apps/api",
        "readyWhen": "Listening on port 3000"
      }
    }
  }
}

A project.json where build, lint, migrate, deploy and serve are all nx:run-commands targets, using sequential commands, cwd, an interpolated {args.env} value, an output prefix and readyWhen, with no plugin code.

What is an Nx custom executor and how does it work?

An executor is a function that Nx calls with two arguments: the target's options, already validated against a schema, and an executor context. The context gives the function what a shell command would otherwise have to rediscover through environment variables or relative paths: the workspace root, the project name, the target name, the active configuration and the project graph. The function does its work and reports back with a success flag. Nx uses that flag to decide whether the task passed, whether dependent tasks can run and whether the result can be cached.

Inside an Nx plugin, an executor has three parts:

  • The implementation file exports the function. It holds all of the executor's logic.
  • The JSON schema declares the options the executor accepts, along with their types, defaults and required fields. Nx checks the target's options against this schema before calling the function. A typo in project.json therefore fails early with a clear error, and the function never receives malformed input.
  • The executors.json entry maps an executor name to its implementation and schema. The plugin's package.json points to this file so that Nx can find it.

When a target runs, the reference resolves like this:

project.json target
  "executor": "my-plugin:deploy"
        │
        ▼
my-plugin/executors.json ──► "deploy" → implementation + schema
        │
        ▼
schema validation (apply defaults, reject invalid options)
        │
        ▼
implementation(options, context)
  context: root, projectName, targetName,
           configurationName, projectGraph
        │
        ▼
{ success: true | false } ──► Nx task runner

Each step has a single job. Because of this, when an executor fails, you can usually tell from the error whether the problem is in resolution, validation or the implementation itself.

┌────────────────────────────────────────┐
│ project.json target "deploy"           │
│   "executor": "my-plugin:deploy"       │
│   "options": { ... }                   │
└───────────────────┬────────────────────┘
                    ▼  resolve plugin-name:executor-name
┌────────────────────────────────────────┐
│ my-plugin/executors.json               │
│   "deploy" → implementation + schema   │
│ (found via package.json "executors")   │
└───────────────────┬────────────────────┘
                    ▼
┌────────────────────────────────────────┐
│ schema validation (schema.json)        │
│   apply defaults, check types,         ├──► invalid: clear error,
│   enforce required fields              │    implementation never runs
└───────────────────┬────────────────────┘
                    ▼  valid options
┌────────────────────────────────────────┐
│ implementation(options, context)       │
│   context: root, projectName,          │
│     targetName, configurationName,     │
│     projectGraph                       │
└───────────────────┬────────────────────┘
                    ▼
┌────────────────────────────────────────┐
│ { success: true | false }              ├──► Nx task runner: pass/fail,
│                                        │    dependent tasks, caching
└────────────────────────────────────────┘

How Nx resolves a target's "my-plugin:deploy" reference through executors.json and schema validation to the implementation function, whose success flag goes back to the task runner.

How does it work when you run a target?

The resolution chain above is one part of a larger sequence. Whether a target uses nx:run-commands or a custom executor, nx run api:deploy goes through the same steps:

  1. Build the project graph. Nx reads the workspace configuration and works out which projects exist and how they depend on each other.
  2. Build the task graph. Nx follows the target's dependsOn entries, so deploy depending on build means api:build (and any upstream builds) are scheduled first.
  3. Compute a hash for each cacheable task. The hash covers the files and environment values declared in inputs, along with the resolved options.
  4. Check the cache. On a hit, Nx restores the declared outputs and replays the terminal output without running anything. On a miss, it continues.
  5. Invoke the executor. For nx:run-commands, that executor spawns the shell commands. For a custom executor, Nx validates options against the schema and calls your function with the options and context.
  6. Record the result. The returned success flag decides whether dependent tasks run. If the task succeeded and is cacheable, Nx stores its outputs under the hash.

Long-running targets such as dev servers work slightly differently. A custom executor can be written as an async generator that yields a result once the process is ready and keeps running afterward, instead of returning a single result at exit. That is the mechanism behind the explicit readiness checks discussed later.

The practical consequence is that switching from run-commands to a custom executor only changes step 5. Scheduling, hashing and caching stay the same, which is why the caching section below says neither approach gets caching right by itself.

How do run-commands and custom executors differ in options, readability and portability?

The difference shows up the first time a target receives bad input. nx:run-commands treats options as strings and interpolates them into shell text. A typo in an option name is usually ignored, and a value containing spaces, quotes or $ gets reinterpreted by the shell. The failure then appears as a confusing shell error, or a command that runs with the wrong arguments. A custom executor declares its options in a schema with types, defaults and required fields. Nx checks that schema before running anything, so the same mistake stops the task with a message that names the option.

Readability works the other way. Anyone can read a command line in project.json and know exactly what will run. An executor hides its behavior behind a name, so understanding it means opening its source.

Portability is where shell strings tend to break. Quoting rules, environment variable syntax ($VAR versus %VAR%) and path separators all differ between POSIX shells and Windows. Code that calls Node APIs avoids those differences.

Long-running processes also differ. readyWhen waits for a substring in the output. That check breaks when the log text changes, and it gives you no control over shutdown. An executor can check readiness explicitly, for example by polling a port. It can also forward signals and clean up child processes.

Concern nx:run-commands Custom executor
Option validation None; strings interpolated into shell Schema: types, defaults, required fields
Bad input fails as Shell error or silent misbehavior Early, named validation error
Readability Command visible in config Behavior hidden behind a name
Cross-OS behavior Depends on shell quoting, env syntax, paths Node APIs avoid shell differences
Readiness readyWhen output match Explicit checks (port, health endpoint)
Cleanup and signals Limited control Handled in code

When should you write an Nx custom executor, and when should you avoid one?

The decision rarely depends on what the target does once. It depends on how often the logic repeats and how much of it a shell expresses poorly.

Signal Points to Why
Same multi-step script copied into many project.json files with small edits Custom executor Fixes land in one place instead of drifting across copies
Branching, retries, polling, or parsing tool output Custom executor Shell conditionals and grep pipelines are hard to test and break silently
Needs the project graph or another project's configuration at runtime Custom executor The executor context exposes this; a shell command would have to reconstruct it
Calls other targets programmatically Custom executor Devkit can run targets and await their results, which beats nesting nx run in a string
Single tool invocation nx:run-commands The command line already is the documentation
Used by one or two projects nx:run-commands Too few call sites to justify the abstraction
Behavior reads more clearly as a command nx:run-commands Reviewers can see exactly what runs
Team won't own TypeScript plugin code nx:run-commands An unowned executor turns into a black box that nobody updates

Avoid the thin wrapper

An executor should encode a decision. For example, it might decide which environment to deploy to, how long to wait for a health check, or which artifacts count as a release. If your schema mirrors a CLI's flags one for one, you have added a build step, a schema file, and a layer of indirection without removing any choices from the caller. In that case, keep the CLI in run-commands and put the shared defaults in target configuration.

Who should use a custom executor, and who should stay on run-commands?

The signals above map onto fairly distinct kinds of teams.

Custom executors fit:

  • Platform or developer-experience teams that own build, release and deploy conventions for many services. They benefit most because a single executor replaces dozens of near-identical target blocks, and they usually have the TypeScript skills and mandate to maintain plugin code.
  • Workspaces with many similar projects, such as a fleet of services that all build an image, push it and roll it out the same way. The more call sites, the more each fix or improvement is worth.
  • Teams whose targets contain real logic: retries against a flaky registry, health-check polling, choosing an environment from the project graph, or orchestrating other targets. These are the cases where shell becomes hard to read and harder to test.
  • Mixed-OS teams where some developers or CI agents run Windows, and shell quoting differences keep causing failures.

nx:run-commands fits:

  • Small workspaces with a handful of projects, where copying a target block is cheaper than owning a plugin.
  • Product teams without a designated tooling owner. If nobody will update the executor through Nx upgrades, it will eventually break every target that uses it.
  • Targets that are a single CLI invocation, whatever the size of the team. The shell command is clearer than any wrapper.

A useful rule: the person or team proposing the executor should be the one who will be paged, or at least asked, when it breaks. If that owner cannot be named, start with the alternatives in the next section.

What are the alternatives to a custom executor in an Nx plugin?

Before writing plugin code, try three options that share configuration without adding a package to maintain. Take a deploy target copied into api, worker and scheduler. Each project's project.json holds the same nx:run-commands block with a long inline shell command, and only the project name and environment change.

Shared script

Move the command into tools/scripts/deploy.sh. Each project's target then becomes a single command option: ./tools/scripts/deploy.sh {projectName}. Nx substitutes {projectName} when it runs the target. The logic now lives in one file that engineers can read, lint and run outside Nx, and a fix lands in every project at once. Because the script is plain shell, there is nothing to compile and no executor schema to version.

targetDefaults

The three target blocks are still identical, so move the whole definition into nx.json under targetDefaults.deploy. That entry sets executor: "nx:run-commands", the command above, and dependsOn: ["build"]. In each project, deploy shrinks to an empty object, or to a single option that overrides the default. A new service gets deployment by declaring the target name. Changing the default is one edit in one file, and Nx owns the merge behaviour, so you write no code for it.

configurations

Inside the same targetDefaults entry, add configurations.staging and configurations.production. Each one sets a different args value, such as --env=staging. Callers then run nx deploy api --configuration=production. The environment names are listed in config where reviewers can see them, rather than inferred from flags inside the script.

// nx.json: one shared definition of the deploy target (Nx accepts comments in this file)
{
  "targetDefaults": {
    "deploy": {
      "executor": "nx:run-commands",
      // Build first so the script always deploys fresh output
      "dependsOn": ["build"],
      "options": {
        // The logic lives in one script; Nx fills in the project name
        "command": "./tools/scripts/deploy.sh {projectName}",
        "args": "--env=staging"
      },
      // Environment variants are listed here, where reviewers can see them
      "configurations": {
        "staging": { "args": "--env=staging" },
        "production": { "args": "--env=production" }
      }
    }
  }
}

// apps/api/project.json: declaring the target name is enough
{
  "name": "api",
  "targets": {
    "deploy": {}
  }
}

// Usage:
//   nx deploy api                            (staging, from default options)
//   nx deploy api --configuration=production

A deploy target moved into nx.json targetDefaults that calls a shared script, with staging and production configurations, so each project.json declares only an empty deploy target.

How do you implement a local Nx custom executor?

Start by generating a local plugin with the Nx plugin package's generators: one creates the plugin project, and another adds an executor to it. The plugin lives in the workspace like any other library, so it is versioned, reviewed, and refactored alongside the projects that use it. You don't need to publish anything.

The generated executor has three parts:

  • A JSON schema. It declares each option's type, default, and whether it is required. Nx validates target options against the schema before your code runs, so a misspelled option fails immediately instead of being ignored.
  • An async function. It receives the resolved options and an executor context (workspace root, project name, configuration), and returns an object with success: true or false.
  • An entry in executors.json. This maps the executor name to its implementation and schema. The plugin's package.json points Nx to that file.

In a project's target configuration, set the executor to plugin-name:executor-name. Options shared by every project, such as a registry URL or region, belong in targetDefaults in nx.json, keyed by the executor. Each project then declares only what differs.

Testing is where the effort pays off. A run-commands target can only be tested by running it, which usually touches real tools and credentials. An executor is a plain async function, so you can call it in a unit test with a hand-built context and mocked dependencies, then assert on the returned result.

To debug, run the target directly with nx run project:target --verbose. This prints full stack traces instead of a one-line failure. Log the options your function received, so you can confirm that defaults, configurations, and command-line overrides merged as you expected.

// executor.ts: the async function registered in executors.json
import type { ExecutorContext } from '@nx/devkit';
import { pushImage } from './push'; // thin wrapper around the real tool, easy to mock

export interface DeployOptions { registry: string; region: string; }

export default async function deployExecutor(options: DeployOptions, context: ExecutorContext) {
  // Visible with --verbose: confirms defaults, configurations and CLI overrides merged as expected
  if (context.isVerbose) console.log('Resolved options:', options);
  try {
    await pushImage(`${options.registry}/${context.projectName}`, options.region);
    return { success: true };
  } catch (err) {
    console.error(err);
    return { success: false };
  }
}

// executor.spec.ts: unit test with a hand-built context, no real tools or credentials
import type { ExecutorContext } from '@nx/devkit';
import deployExecutor from './executor';
import { pushImage } from './push';

jest.mock('./push');
const context = { root: '/workspace', cwd: '/workspace', isVerbose: false, projectName: 'api' } as ExecutorContext;
const options = { registry: 'registry.example.com', region: 'eu-west-1' };

it('pushes the project image and reports success', async () => {
  (pushImage as jest.Mock).mockResolvedValue(undefined);
  expect(await deployExecutor(options, context)).toEqual({ success: true });
  expect(pushImage).toHaveBeenCalledWith('registry.example.com/api', 'eu-west-1');
});

it('reports failure instead of throwing', async () => {
  (pushImage as jest.Mock).mockRejectedValue(new Error('push denied'));
  expect(await deployExecutor(options, context)).toEqual({ success: false });
});

A minimal local executor that returns a success result, with Jest unit tests that call it directly using a hand-built ExecutorContext and a mocked dependency.

How can a custom executor save engineering time?

An executor saves time in specific places, and costs it in others. The savings come from four sources:

  • One fix instead of many. When deploy logic is copied into every project.json, a bug fix or a new flag means editing every copy and reviewing each change. With an executor, the change lands once and every project picks it up on its next run.
  • Earlier, clearer failures. Schema validation rejects a misspelled option or a missing required value before anything runs. With shell interpolation, the same mistake often surfaces later as a confusing error from the underlying tool, or not at all.
  • Testing without real infrastructure. Unit tests against a mocked context catch regressions in seconds, on a laptop or in CI, without credentials. Testing a run-commands target usually means running it for real and inspecting the result.
  • Faster onboarding of new projects. Combined with targetDefaults, a new service gets a working target by declaring its name, instead of someone copying and adapting a long shell block.

Neither approach changes how much time caching saves. That depends on accurate inputs and outputs, which you must declare either way.

To decide whether the savings outweigh the maintenance cost, compare both sides for your own workspace. The following is an illustrative estimate with assumed inputs, not a measurement:

  • Assumed: 12 services share the same deploy logic.
  • Assumed: the logic changes 6 times a year, and each change takes about 10 minutes per copy to edit and review when copied, versus about 60 minutes once for an executor change including tests.
  • Assumed: keeping the executor compiling across Nx upgrades takes about 4 hours a year.

Copied: 6 changes × 12 copies × 10 minutes = 720 minutes, or 12 hours a year. Executor: 6 changes × 60 minutes = 6 hours, plus 4 hours of upgrade work, or 10 hours a year. Under these assumptions the executor saves about 2 hours a year, which is a narrow margin. With 3 services instead of 12, the copied approach costs 3 hours and the executor clearly loses. The arithmetic shows that call-site count and change frequency drive the decision far more than the executor itself does, and that a shared script with targetDefaults often captures most of the "one fix" saving with none of the upgrade cost.

How does a custom executor affect caching, maintenance and development cost?

Neither approach gets caching right on its own. Nx computes the cache key from the target's inputs, ties restored artifacts to outputs, and orders work through dependsOn. A custom executor changes none of that, so you still have to declare every file and variable the target depends on.

Executors make mistakes harder to see. If a function reads process.env.API_URL or loads a config file outside the project, Nx does not hash that value. When it changes, Nx replays an old result that looks valid. With run-commands, $API_URL appears in the command string in project.json, where a reviewer can catch it and add an env input. In an executor, the same read is buried in TypeScript that nobody reviews alongside the target configuration.

Concern run-commands Custom executor
Hidden inputs Visible in the command Buried in code
Nx upgrades Rarely affected Devkit API changes can break it
Build step None Plugin must be transpiled before use
Failure scope One target Every target using the executor

The ongoing cost is real. Someone has to track @nx/devkit changes across major versions and keep the plugin's TypeScript compiling. A broken executor also has a large blast radius: it fails every target that uses it, across every project.

Checklist before converting a target

  • Reuse: Will three or more projects use it?
  • Options: Does it need typed, validated options with defaults?
  • Branching: Does it contain conditionals that are awkward to express in shell?
  • Graph access: Does it need the project graph or other projects' configuration?
  • Ownership: Is a named owner committed to maintaining it through Nx upgrades?

If most answers are no, keep the target on run-commands.

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.