What is an Nx local plugin, and why use one for backend conventions?

An Nx local plugin is ordinary TypeScript that lives inside your monorepo, usually under tools/ or libs/, and extends Nx the same way a published plugin does. You register it by adding an entry to the plugins array in nx.json. Nx resolves that entry through the workspace TypeScript path configuration, typically an alias in tsconfig.base.json, and loads the source directly. Nothing goes to a package registry, and you don't need a separate release process. A change to the plugin ships in the same pull request as the code it affects, and it gets reviewed and tested alongside that code.

The problem it solves is drift. In a workspace with dozens of backend services, each project.json usually started as a copy of another one. Over time, one service gains a migrate target, another changes its Docker build context, and a third keeps a test configuration that everyone else replaced months ago. A wiki page describes the "standard" layout, but nothing enforces it. Each copy turns into a small fork that someone has to find and fix by hand.

A local plugin lets you define the convention once, as code. For example, if every service has a Dockerfile and a src/main.ts, the plugin can attach the same build, serve, test and container targets to all of them. Platform teams and backend teams that run many similar services benefit most. A fix to a target definition, such as a corrected cache input or a new lint step, changes in one file and takes effect in every matching project. Without the plugin, the same fix needs a sweep across N project.json files, and that sweep is rarely finished.

How does createNodes inference work in the project graph?

When Nx builds the project graph, it reads the plugins array in nx.json and asks each plugin for its createNodes export. That export pairs a glob pattern with a function. Nx matches the glob against workspace files, such as every service.json or every src/main.ts under apps/, and passes the matched paths to the function along with the plugin's options from nx.json and a context object containing the workspace root and nx.json configuration. The function returns project configuration fragments keyed by project root: targets, tags, inputs, outputs and metadata.

Nx then merges those fragments. Results from multiple plugins are combined in order, and anything written explicitly in a project's project.json or package.json takes precedence over inferred values. This is what makes incremental adoption safe. A team can override one inferred target in a single project while everything else stays inferred.

The function runs during graph construction, and nearly every Nx command needs the graph. That puts it on the hot path. It should read only the files it needs, avoid network calls and process spawning, and return the same output for the same input. Purity matters because Nx caches the computed graph and reuses it until relevant files or plugin options change. Nondeterministic output defeats that cache and can produce confusing task-cache misses. When the Nx daemon is running, it keeps the graph in memory, watches the file system, and recomputes only when something changes. A slow plugin is therefore felt mostly on cold starts and in CI, where the daemon is often disabled.

The plugin API has changed across major Nx versions. This includes the shape of the createNodes export and whether the function receives one file or a batch. Check the documentation for the Nx version you have installed before you write against it.

+-----------------------------+    +-----------------------------+
| nx.json "plugins" array     |    | Workspace files             |
| + plugin options            |    | e.g. apps/*/service.json    |
+--------------+--------------+    +--------------+--------------+
               |                                  |
               v                                  v
+--------------------------------------------------------------+
| Project graph construction (hot path of every Nx command)    |
| 1. load each plugin's createNodes export (glob + fn)         |
| 2. match glob against workspace files                        |
+------------------------------+-------------------------------+
                               | matched paths, options,
                               v context (root, nx.json)
+--------------------------------------------------------------+
| createNodes function (pure, fast, deterministic)             |
| no network, no process spawning, read only needed files      |
+------------------------------+-------------------------------+
                               | fragments keyed by project root:
                               v targets, tags, inputs, outputs
+--------------------------------------------------------------+
| Merge fragments from all plugins, in plugin order            |
| explicit project.json / package.json values win              |
+------------------------------+-------------------------------+
                               |
                               v
+-----------------------------+   +-----------------------------+
| Cached project graph        |<--| Nx daemon (if running):     |
| reused until files or       |   | keeps graph in memory,      |
| plugin options change       |   | watches FS, recomputes      |
+-----------------------------+   +-----------------------------+

How Nx calls a createNodes plugin during project graph construction, merges inferred fragments under explicit project.json values, and caches the graph, with the daemon keeping it warm.

Which backend conventions should the plugin infer?

Start with an audit, not a wishlist. List what your backend services already have in common, and count how many actually follow each pattern. A convention that only some services follow will produce targets that fail on the rest, and engineers will stop trusting inferred targets after the first few false failures. Infer only what is already true. Make new conventions a separate migration effort.

Each target should trace back to a file that exists on disk:

File signal Inferred target Why the signal is reliable
Service config file (for example service.config.json) Project detection, root for other targets Marks a deployable service, not just any folder with code
Dockerfile build-image An image build is only possible if this file exists
Files under migrations/ migrate Nothing to run when the directory is empty or absent
OpenAPI spec codegen or validate-spec The spec is the input, so it also defines cache inputs

Do not infer from names. A project called orders-api might have no spec, and a folder named db might hold fixtures rather than migrations. Name-based guesses produce targets that look plausible and then fail. Also note that createNodes globs match files, not directories. To detect a migrations directory, match the files inside it and derive the directory from their paths.

File-based inference stays accurate longer than scaffolding because a generator runs once. After that, the generated configuration drifts from the code. Inference, by contrast, is recomputed with the project graph, so deleting a Dockerfile removes build-image without anyone editing configuration.

How do you implement a createNodes entry with correct inputs, outputs and caching?

Register the plugin in the plugins array of nx.json with an object entry: plugin points at the local path (for example ./tools/backend-plugin), and options holds settings such as buildTargetName, migrateTargetName and markerFile. Making target names configurable lets a team adopt the plugin without renaming targets that CI scripts already call. Making the marker file configurable lets the glob change without a code change.

The createNodes export pairs a glob with an inference function. Build the glob from the marker file, for example any service.json under apps/. Nx calls the function with each matched file, your options and a context object. Derive the project root from the file's directory and return a projects entry keyed by that root.

For each target, either wrap shell commands in nx:run-commands or reuse an existing executor. Set cwd to {projectRoot} so commands behave the same regardless of where Nx is invoked. Caching depends on what you declare:

  • inputs: use something like production and ^production, so test files and docs don't invalidate builds.
  • outputs: use something like {projectRoot}/dist, so cache hits restore artifacts.
  • dependsOn: set ^build so libraries build before the services that consume them.
  • cache: false: set this on the migrate target, because a migration changes database state that Nx cannot see or restore.

Inferred targets are defaults. A project's project.json can define a target with the same name to override specific options or add to them, and its values take precedence. To confirm the merged result and see which source contributed each property, run nx show project <name> (add --web for the graph view).

The createNodes signature has changed across Nx releases, so check it against the devkit types in your installed version before you copy any example.

// tools/backend-plugin/index.ts (verify createNodesV2 / createNodes naming against your Nx version)
import { CreateNodesV2, createNodesFromFiles } from '@nx/devkit';
import { basename, dirname } from 'path';

export interface BackendPluginOptions {
  buildTargetName?: string;   // keep names CI scripts already call
  migrateTargetName?: string;
  markerFile?: string;        // file name that marks a backend project
}

// The glob is fixed when the module loads. Match broadly, then filter by markerFile.
export const createNodesV2: CreateNodesV2<BackendPluginOptions> = [
  'apps/**/*.json',
  (configFiles, options, context) =>
    createNodesFromFiles((file, opts = {}) => {
      const { buildTargetName = 'build', migrateTargetName = 'migrate', markerFile = 'service.json' } = opts;
      if (basename(file) !== markerFile) return {};
      const projectRoot = dirname(file);
      return {
        projects: {
          [projectRoot]: {
            targets: {
              [buildTargetName]: {
                executor: 'nx:run-commands',
                options: { command: 'npm run build', cwd: '{projectRoot}' },
                inputs: ['production', '^production'], // ignore tests/docs
                outputs: ['{projectRoot}/dist'],        // restored on cache hit
                dependsOn: ['^build'],                  // libraries build first
                cache: true,
              },
              [migrateTargetName]: {
                executor: 'nx:run-commands',
                options: { command: 'npm run migrate', cwd: '{projectRoot}' },
                cache: false, // changes DB state Nx cannot see or restore
              },
            },
          },
        },
      };
    }, configFiles, options, context),
];

A local plugin that infers build and migrate targets for every project containing the configured marker file, declaring cwd, inputs, outputs and dependsOn for caching and turning caching off for migrations; it is registered in nx.json as { "plugin": "./tools/backend-plugin", "options": { ... } }.

How do you add a service generator with the Nx devkit?

The other half of the plugin is a generator that creates new services in the shape createNodes expects. A generator is a function that receives a Tree, which is a virtual file system staged in memory. Nothing reaches disk until the function returns without error, so a failed run leaves the workspace unchanged. Running it with --dry-run shows the planned changes before you commit to them.

Keep the generator to three steps:

  1. generateFiles copies a template directory into the new service folder and substitutes values such as the service name and port. The templates should contain the exact marker files your createNodes glob matches, plus the minimum source needed for the inferred targets to run.
  2. updateJson edits shared configuration. For example, it can add a path alias to the root TypeScript config or register the service in a central manifest.
  3. formatFiles runs last, so generated output matches the workspace's formatter and doesn't create noise in review diffs.

The generator should not write any targets. It produces files, and inference turns those files into build, serve and test targets. This keeps the generator small. It also means a new service and an older one that was migrated by hand end up with identical target definitions, because both come from the same inference code. If you change a convention, you update createNodes once, and every service picks up the change. You don't have to regenerate anything.

A generator only acts at creation time. Once it has run, nothing stops someone from renaming or deleting a marker file. That is why inference, not scaffolding, has to define what a correct service looks like.

import {
  Tree,
  formatFiles,
  generateFiles,
  joinPathFragments,
  names,
  updateJson,
} from '@nx/devkit';

interface ServiceGeneratorSchema {
  name: string;
  port?: number;
}

export default async function serviceGenerator(tree: Tree, options: ServiceGeneratorSchema) {
  const { fileName } = names(options.name); // e.g. 'Billing API' -> 'billing-api'
  const serviceRoot = joinPathFragments('services', fileName);

  // 1. Copy ./files into the new service folder. The templates contain the marker
  //    file the createNodes glob matches (e.g. service.config.json) plus minimal src.
  generateFiles(tree, joinPathFragments(__dirname, 'files'), serviceRoot, {
    name: fileName,
    port: options.port ?? 3000,
    tmpl: '', // strips the __tmpl__ suffix from template file names
  });

  // 2. Edit shared config: add a path alias to the root TypeScript config.
  updateJson(tree, 'tsconfig.base.json', (json) => {
    json.compilerOptions ??= {};
    json.compilerOptions.paths ??= {};
    json.compilerOptions.paths[`@services/${fileName}`] = [`${serviceRoot}/src/index.ts`];
    return json;
  });

  // Deliberately no targets here: createNodes infers build/serve/test from the
  // marker file, so new and hand-migrated services get identical definitions.

  // 3. Format last so the staged Tree matches the workspace formatter.
  await formatFiles(tree);
}

A minimal Nx service generator that writes only templated files and a tsconfig path alias, then formats them, leaving all target definitions to the plugin's createNodes inference.

How do you test, debug and roll out a workspace plugin incrementally?

Unit tests for inference

Test the createNodes function directly, without booting Nx. Import the function from your plugin's createNodes export, pass fake config file paths such as apps/billing/service.json, and supply a stubbed context with workspaceRoot pointing at a temporary directory. Assert on the returned project root, target names, inputs, outputs and cache flags. These tests are fast. They also catch the most common regression: a target whose outputs no longer match where the build writes, which leads to silent cache misses or stale restored artifacts.

Generator tests

Run the service generator against createTreeWithEmptyWorkspace from @nx/devkit/testing. Assert that the marker file exists and that no project.json targets were written. This confirms the generator leaves target definitions to inference.

Smoke tests

Unit tests stub the context, so they don't prove that Nx loads the plugin. Run nx show project billing to see the targets Nx actually resolved, and the file each one came from. Use nx graph to check dependency edges. If changes to the plugin don't show up, the daemon or cache is probably holding an old graph. Run nx reset and check again.

Migration

Enable the plugin and diff its inferred targets against each service's existing project.json. Migrate one service at a time. Delete a duplicate only when the inferred version matches it. Keep an explicit override only where a service is a real exception, and add a comment explaining why. Run the plugin tests in CI on every change. A plugin that throws breaks project graph computation, and that stops every Nx command in the repository.

// tools/service-plugin/src/plugin.spec.ts
import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { CreateNodesContextV2 } from '@nx/devkit';
import { createNodes } from './plugin';

describe('service plugin inference', () => {
  it('infers a cached build target for a service marker file', async () => {
    // Fake workspace on disk so the plugin can read the marker file if it needs to.
    const workspaceRoot = mkdtempSync(join(tmpdir(), 'svc-plugin-'));
    mkdirSync(join(workspaceRoot, 'apps/billing'), { recursive: true });
    writeFileSync(join(workspaceRoot, 'apps/billing/service.json'), '{}');

    // Stubbed context: no daemon, no real nx.json.
    const context = { nxJsonConfiguration: {}, workspaceRoot } as CreateNodesContextV2;

    // createNodes is a [glob, fn] tuple; call the function directly.
    const [, inferTargets] = createNodes;
    const results = await inferTargets(['apps/billing/service.json'], {}, context);

    const [[file, result]] = results;
    expect(file).toBe('apps/billing/service.json');

    const build = result.projects?.['apps/billing']?.targets?.build;
    // Outputs must match where the build really writes, or caching silently breaks.
    expect(build).toMatchObject({
      cache: true,
      inputs: ['production', '^production'],
      outputs: ['{workspaceRoot}/dist/apps/billing'],
    });
  });
});

A Jest test that calls the plugin's createNodes function directly with a fake marker file and a stubbed context, then checks the inferred build target's inputs, outputs and cache flag without starting Nx.

When should you avoid an Nx local plugin, and what are the alternatives?

A local plugin is code you own, and it has ongoing costs. Nx has changed its plugin APIs across major versions, so each upgrade may require changes to your plugin. Inferred targets do not appear in project.json, so engineers who read that file will not find them. Document the marker-file contract next to the plugin, and point people to nx show project <name> to see the resolved targets. Inference runs whenever the project graph is recalculated, so a slow glob or a file read for every project slows down every command. A wrong inputs or outputs entry reaches every service at the same time, which can mean stale cache hits across the whole fleet. Plugins that resolve imports through TypeScript path mappings break when tsconfig layout changes. The clearest warning sign is a growing list of options and per-service flags. At that point you have built a second configuration language, and the services probably differ in ways that need explicit configuration.

Approach Maintenance cost Visibility Drift risk Best fit
Explicit project.json Low per project, high in total Full High Few services, or services that differ a lot
targetDefaults in nx.json Low Medium Low Shared cache settings on targets that already exist
Generator only Low Full Medium (after scaffolding) Consistent starting point, freedom to diverge later
Published plugin Low (upstream owns it) Medium Low Standard tooling that the plugin already supports

Start with targetDefaults and a generator. Add createNodes only when many services follow the same convention and target definitions keep drifting apart.

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 local plugin, 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.