What is an Nx custom executor and when is it worth writing one?

An Nx custom executor is a small Node module inside an nx plugin that runs a target. It exports a function that receives typed options and a context object describing the workspace and project, and it reports success or failure back to Nx. The plugin registers the executor in an executors.json file and pairs it with an executor schema, a JSON Schema file that Nx uses to validate and default the options before your code runs.

Teams write executors to get three things that loose scripts don't provide reliably:

  • Validated options: a typo in project.json fails fast with a clear message instead of halfway through a migration.
  • Consistent caching: the target is defined once, so every project gets the same cache inputs and outputs.
  • Reuse: one implementation serves dozens of services.

This is mainly a tool for backend and platform engineers who own shared tasks such as schema generation, database migrations, or container builds.

Use this decision test. Write an executor only when all three apply: the task needs typed options, several projects reuse it, and its inputs and outputs are cacheable.

Approach Best for Weakness
Custom executor Shared, parameterised tasks Plugin code to own and test
nx:run-commands Wrapping a shell command quickly Options are untyped strings
Inferred targets Tool config files Nx plugins detect Less control over unusual flags
package.json scripts One-off or single-project tasks No validation, so each project drifts

One-off or single-project tasks should stay as scripts. An executor only pays back its maintenance cost when several projects share the task.

How does an executor work inside a local Nx plugin?

An executor is a function plus a contract, and Nx keeps those in separate files so options can be checked before your code runs.

The implementation module exports a default async function that takes options and context and resolves to an object with a success boolean. The schema.json describes the allowed options: types, defaults, required fields, and whether extra properties are permitted. A TypeScript interface mirrors that schema so the function body is typed. Nx does not generate one from the other, so they can drift. Section 3 covers how to keep them aligned.

The executors.json manifest maps each executor name to its implementation path, schema path, and a description. The plugin's package.json points to the manifest through its executors field. In project.json, a target sets executor to <plugin-package-name>:<executor-name> and supplies options, plus optional named configurations.

When you run a target, Nx follows these steps:

  1. It reads the target and resolves the package name to the plugin.
  2. It finds the manifest through package.json and locates the entry for the executor name.
  3. It loads the schema, merges any configuration overrides and CLI flags into the options, applies defaults, and validates the result.
  4. It calls your function with the validated options and a context. The context carries the workspace root, project name, target name, and project configurations.

Invalid options fail before your code executes.

Nx loads executors as JavaScript. A local plugin written in TypeScript must be either built first or transpiled on the fly through the workspace's TypeScript path mappings. If the manifest points at output that doesn't exist, or the path alias doesn't match the package name, Nx reports that it cannot find the executor. This happens even though the source code is correct.

// tools/my-plugin/src/executors/migrate/executor.ts
import type { ExecutorContext } from '@nx/devkit';
import { join } from 'path';

// Hand-written mirror of schema.json; Nx does not keep these in sync for you.
export interface MigrateExecutorOptions {
  dir: string;      // schema.json: type string, required
  dryRun?: boolean; // schema.json: type boolean, default false
}

export default async function runExecutor(
  options: MigrateExecutorOptions,
  context: ExecutorContext,
): Promise<{ success: boolean }> {
  // Nx has already merged configuration + CLI overrides, applied defaults,
  // and validated against schema.json before this line runs.
  const target = join(context.root, options.dir);
  console.log(`[${context.projectName}:${context.targetName}] ${target} dryRun=${options.dryRun}`);
  return { success: true };
}

/* Wiring, abridged:
 * tools/my-plugin/package.json
 *   { "name": "@acme/my-plugin", "executors": "./executors.json" }
 * tools/my-plugin/executors.json
 *   { "executors": { "migrate": {
 *       "implementation": "./src/executors/migrate/executor",
 *       "schema": "./src/executors/migrate/schema.json",
 *       "description": "Apply database migrations" } } }
 * apps/api/project.json
 *   "targets": { "migrate": {
 *     "executor": "@acme/my-plugin:migrate",
 *     "options": { "dir": "apps/api/migrations" },
 *     "configurations": { "check": { "dryRun": true } } } }
 * Run with the "check" configuration:  nx run api:migrate:check
 * The TS path alias must be exactly "@acme/my-plugin", or the plugin must be built,
 * otherwise Nx reports that it cannot find the executor.
 */

A typed executor implementation alongside the package.json, executors.json and project.json entries that let Nx resolve "@acme/my-plugin:migrate" to this function.

How do you design a strict executor schema?

Start from the contract, not the implementation. The schema.json file is a JSON Schema document, and Nx validates the merged options from project.json, configurations, and command-line overrides against it before your executor function runs. A typo in a target's options or a missing required value fails at that point, with an error naming the property, instead of surfacing later as an obscure failure from the underlying tool.

Required, optional, and defaults

Put a property in required only when no sensible value exists, such as an entry file or a migrations directory. Give every optional property a default so the executor never has to guess. For properties with a fixed set of values, such as a log level or a target environment, use enum instead of a free string. Write a description for every property, because editor tooling reads the schema and shows those descriptions as hints while someone edits project.json.

Keep the schema and the type in sync

Mirror the schema in a TypeScript interface, such as MigrateExecutorOptions, and type the executor's options parameter with it. Nothing links the two files automatically, so either generate the interface from the schema or add a test that loads the schema and compares its property names to the type's keys. Set additionalProperties to false so unknown keys are rejected and are not silently passed through.

The wrapping trade-off

When an executor wraps a CLI, every upstream flag you don't model is unreachable. You have two choices. You can add each new flag to the schema, which keeps validation strict but costs a change per flag. Or you can add an args array escape hatch, which is quick but unvalidated. If you add the escape hatch, document it as unsupported and promote any flag that people use often into a real property.

{
  "title": "Migrate executor",
  "description": "Runs database migrations through the wrapped migration CLI.",
  "type": "object",
  "properties": {
    "migrationsDir": {
      "type": "string",
      "description": "Directory containing migration files, relative to the workspace root."
    },
    "environment": {
      "type": "string",
      "enum": ["development", "staging", "production"],
      "default": "development",
      "description": "Target environment. Selects which connection settings the CLI loads."
    },
    "logLevel": {
      "type": "string",
      "enum": ["error", "warn", "info", "debug"],
      "default": "info",
      "description": "Verbosity passed through to the migration CLI."
    },
    "dryRun": {
      "type": "boolean",
      "default": false,
      "description": "Print the migrations that would run without applying them."
    },
    "args": {
      "type": "array",
      "items": { "type": "string" },
      "default": [],
      "description": "UNSUPPORTED escape hatch: extra flags appended verbatim to the CLI call. Not validated. Request a typed option instead."
    }
  },
  "required": ["migrationsDir"],
  "additionalProperties": false
}

A strict executor schema.json with one required property, defaults and enums for every optional property, descriptions that editor tooling can show as hints, additionalProperties set to false so unknown keys are rejected, and a clearly labeled, unvalidated args escape hatch.

How do you implement an executor that runs backend tooling?

The executor itself is an async function that receives the validated options and an ExecutorContext, and resolves to an object with a success boolean. Nx uses that boolean to decide whether the task failed, so returning { success: false } matters more than throwing.

Resolve paths from the context

Nx can invoke the executor from any directory, so process.cwd() is not a reliable anchor. Take the workspace root from context.root. Look up the project's root in the project configuration that the context exposes for context.projectName. Then join the user-supplied paths, such as a migrations directory or a generator config, against those roots. If a required path doesn't exist, fail early with a message that names the option and the resolved absolute path. "Option migrationsDir resolved to /repo/apps/api/db/migrations, which does not exist" is fixable without reading your source.

Spawn the tool deliberately

Use Node's child_process.spawn with the binary and an explicit argument array, and don't set shell: true. Concatenated shell strings break on paths with spaces and allow option values to inject commands. Set cwd to the resolved project root. Stream output with stdio: 'inherit', or pipe and forward it, so that long migrations show progress. Resolve success: false on a non-zero exit code or a spawn error event, such as a missing binary.

Build the child's environment on purpose. Start from process.env, then add only the variables the tool needs, such as a database URL taken from a named option. That way, anything that affects the output is visible in configuration.

Use logger from @nx/devkit for your own messages, not console. This keeps output consistent with the rest of the run.

import { ExecutorContext, logger } from '@nx/devkit';
import { spawn } from 'node:child_process';
import { existsSync } from 'node:fs';
import { join } from 'node:path';

export interface MigrateOptions {
  bin: string;           // e.g. 'migrate-cli' (placeholder tool on PATH)
  migrationsDir: string; // relative to the project root, e.g. 'db/migrations'
  databaseUrl: string;   // e.g. 'postgres://app:changeme@localhost:5432/app_dev'
}

export default async function migrateExecutor(
  options: MigrateOptions,
  context: ExecutorContext,
): Promise<{ success: boolean }> {
  // Anchor every path to the context, never process.cwd().
  const project = context.projectName
    ? context.projectsConfigurations?.projects[context.projectName]
    : undefined;
  if (!project) {
    logger.error('No project configuration found for this target.');
    return { success: false };
  }
  const projectRoot = join(context.root, project.root);
  const migrationsDir = join(projectRoot, options.migrationsDir);
  if (!existsSync(migrationsDir)) {
    logger.error(`Option 'migrationsDir' resolved to ${migrationsDir}, which does not exist.`);
    return { success: false };
  }

  logger.info(`Running ${options.bin} against ${migrationsDir}`);
  return new Promise((resolve) => {
    // Argument array, no shell: paths with spaces are safe and options cannot inject commands.
    // 'up' and '--dir' stand in for whatever arguments your migration CLI expects.
    const child = spawn(options.bin, ['up', '--dir', migrationsDir], {
      cwd: projectRoot,
      stdio: 'inherit', // stream progress straight to the terminal
      env: { ...process.env, DATABASE_URL: options.databaseUrl }, // only what the tool needs
    });
    child.on('error', (err) => { logger.error(`Failed to start ${options.bin}: ${err.message}`); resolve({ success: false }); });
    child.on('close', (code) => resolve({ success: code === 0 }));
  });
}

An Nx executor that resolves paths from ExecutorContext, fails early with a clear misconfiguration message, and spawns a migration CLI with an explicit argument array, inherited output, a deliberately built environment, and its exit code mapped to the success boolean.

How do you integrate a custom executor with the Nx task runner and caching?

The executor only knows how to run a task. The task runner decides when to run it and whether it can skip it, based on what you declare in targetDefaults in nx.json or in the project's own target configuration. Set inputs to the files and named inputs that can change the result. Set outputs to every path the executor writes. Set dependsOn to the targets that must finish first, such as ^build for upstream projects. If an output path is missing, a cache hit will restore an incomplete artifact.

Caching can lie

Nx hashes only what you declare. Three gaps cause stale hits:

  • Undeclared environment variables. If the executor reads DATABASE_URL or a feature flag, add an env input for it.
  • Files outside the project root. Shared config files or a root-level schema file are not included unless you list them.
  • Remote state. A live database schema or an external API cannot be hashed at all.

A wrong cache hit is worse than a cache miss. A miss costs time. A wrong hit ships a build that looks green and is not.

Side effects are not cacheable

Set cache: false for migrations, deploys, and publishing. Make these tasks idempotent so a retry or a concurrent run does no harm. This matters most with a remote cache. Without cache: false, one developer's "successful migration" could be replayed as a hit on a CI agent whose database was never touched.

Orchestrate through the graph

Do not call runExecutor on other targets from inside your executor. That chain is invisible to the task graph. It runs serially, gets cached as a single opaque unit, and is hidden from nx graph. Express ordering with dependsOn instead, and let the task runner parallelize and cache each step on its own.

{
  "namedInputs": {
    "default": ["{projectRoot}/**/*", "sharedGlobals"],
    "sharedGlobals": ["{workspaceRoot}/tsconfig.base.json"],
    "production": ["default", "!{projectRoot}/**/*.spec.ts"]
  },
  "targetDefaults": {
    "build": {
      "dependsOn": ["^build"],
      "inputs": ["production", "^production", { "env": "FEATURE_FLAGS" }],
      "outputs": ["{workspaceRoot}/dist/{projectRoot}"],
      "cache": true
    },
    "generate-client": {
      "executor": "@acme/tools:generate-client",
      "inputs": [
        "{workspaceRoot}/schema/openapi.yaml",
        { "env": "API_VERSION" }
      ],
      "outputs": ["{projectRoot}/src/generated"],
      "cache": true
    },
    "migrate": {
      "executor": "@acme/tools:migrate",
      "dependsOn": ["build"],
      "cache": false
    },
    "deploy": {
      "executor": "@acme/tools:deploy",
      "dependsOn": ["build", "migrate"],
      "cache": false
    }
  }
}

An nx.json sketch in which cacheable targets declare every input, including a root-level schema file and the environment variables they read, plus every output path; migrate and deploy set cache: false, and all ordering is expressed through dependsOn rather than executors calling one another.

How do you handle long-running tasks like watch modes and dev servers?

A one-shot executor returns a promise that resolves once with { success }, and Nx treats that resolution as the end of the task. That model doesn't fit a dev server or a compiler in watch mode, because those processes don't finish. For these, write the executor as an async generator function. Nx consumes the iterator and treats each yielded { success: boolean } as a status update. The task only ends when the iterator completes.

A typical watch executor spawns the tool, parses its output for "rebuild finished" or "rebuild failed" markers, and yields a result for each cycle. A failed rebuild should yield { success: false } and keep going. Ending the iterator on the first type error would kill the watcher the developer is relying on. To keep a server alive after its first successful yield, await a promise that settles only when the child process exits.

Cleanup is where most homegrown executors go wrong. When a developer hits Ctrl+C or a parent process sends SIGTERM, the spawned server can survive as an orphan and keep holding its port. That orphan is why the next run fails with "address already in use." To prevent this:

  • Register handlers for SIGINT and SIGTERM that kill the child.
  • Put the kill logic in a finally block so it also runs when the consumer stops iterating early.
  • Resolve the pending promise when the child exits, so the generator can return cleanly.

Long-running targets should not be cached. Their output describes a live process, not a reproducible artifact, so set cache: false on these targets.

How should you test and maintain a custom executor over time?

Unit tests first, then a smoke test

An executor is an async function (or async generator) that takes options and an ExecutorContext. That makes it straightforward to unit test: build a minimal context object with a root, projectName, and the project configuration it reads, then mock the child-process module so no real tooling runs. Assert on the command, arguments, and working directory it would have spawned, and on how it maps a non-zero exit code to { success: false }.

Unit tests can't confirm that executors.json points at the right file or that Nx resolves your schema defaults the way you expect. For that, keep a small fixture project in the repo and run the target through the nx CLI in CI. If a schema path is wrong or a required option is missing, this test fails before a real project hits the problem.

Maintenance cost is real

An executor is code you own. The executor API and plugin conventions have changed across Nx releases, so pin the Nx version and read the migration notes before upgrading, rather than assuming your plugin carries over unchanged.

Debugging compiled output is painful. Keep a single, explicit build step for the plugin and emit source maps, so stack traces point at your TypeScript instead of transpiled JavaScript.

The investment pays off when many projects share a validated task, cached the same way and behaving identically everywhere. For a task only one project runs, a plain nx:run-commands target is cheaper. Wait until a second or third consumer appears before abstracting.

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.