What is an Nx createNodes plugin and how do inferred tasks work?
Project Crystal is Nx's name for inferred tasks: targets that Nx derives from the tool configuration already in your repository instead of requiring you to declare them by hand in project.json. If a directory contains a config file a plugin recognizes, that directory becomes a project with targets, and nobody had to write the target definition.
A plugin's createNodes export provides two things: a glob pattern and a function. While Nx builds the project graph, it scans the workspace for files matching each registered plugin's glob. Plugins are registered in the plugins array of nx.json. Nx then calls the function with the matched paths and the plugin's options. The function reads those files and returns project definitions keyed by project root, each with its targets, inputs, outputs, and metadata. Nx merges these results into the graph. Explicit configuration in project.json or package.json is applied on top, so a team can override any inferred value without forking the plugin.
Treat the function as a pure mapping from config files on disk to project and target definitions. The reason is performance. The Nx daemon keeps the project graph in memory and recomputes it when files change. It also caches plugin results, keyed on the contents of the matched files and the plugin options. If your function depends only on those inputs, Nx can skip it on most runs and reuse the earlier output. If it reads environment variables, the clock, or files outside the match, the cache will return stale results, and nothing will tell you.
+----------------------+ +--------------------------------------+
| nx.json plugins[] | | Workspace files on disk |
| (plugin + options) | | e.g. vite.config.ts, jest.config.ts |
+---------+------------+ +---------+----------------------------+
v v
+--------------------------------------------------------------------+
| Nx daemon: holds project graph in memory, recomputes on file change|
| 1. Scan workspace with each plugin's createNodes glob |
| | |
| v |
| 2. Cache lookup: key = matched file contents + plugin options |
| hit | miss | |
| | v |
| | +-------------------------------+ |
| | | createNodes function (pure) | |
| | | paths + options -> projects | |
| | | keyed by root: targets, | |
| | | inputs, outputs, metadata | |
| | +---------------+---------------+ |
| | | store in cache |
| v v |
| 3. Merge inferred projects and targets into graph |
| | |
| v |
| 4. Apply project.json / package.json on top (explicit wins) |
+---------+----------------------------------------------------------+
v
+-----------------+
| Project graph |
+-----------------+
Inside the Nx daemon, matched config files and plugin options are checked against the cache, the pure createNodes function runs only on a miss, and its inferred projects are merged into the project graph before explicit project.json or package.json configuration is applied on top.
Who should write one, and when should you avoid it?
The strongest case for a plugin is a platform team that owns dozens of services sharing one tool or manifest format. If every service has a service.yaml and needs the same build, test, and deploy targets, a plugin replaces many nearly identical project.json files with one piece of logic. Changing a convention then becomes a single edit instead of a sweep across the repo.
Illustrative estimate. The assumptions are 40 services, 4 target-convention changes a year, and 10 minutes to update each project by hand. That comes to about 27 hours a year (40 × 4 × 10 minutes). The plugin is assumed to cost 1 hour per convention change plus 3 hours for each of 2 Nx upgrades, or about 10 hours a year. Apply the same per-project numbers to 5 services and manual upkeep drops to about 3 hours, while the plugin still costs around 10. At that size, explicit targets are cheaper.
Avoid a plugin in the following cases:
- The repo is small. With a handful of projects, explicit targets are easier to read and change.
- Upgrades are a burden for your team. A local plugin depends on Nx's plugin API, so someone has to retest it after each Nx upgrade.
- Discoverability matters to your team. Inferred targets don't appear in any project file. Engineers have to know a plugin exists before they can tell where a target comes from.
- You would be parsing a tool's config yourself. If the tool supports
extends, includes, or variable interpolation and your parser doesn't, the plugin's inputs and outputs will drift from what the tool actually does. Let the tool interpret its own config wherever you can.
What does the createNodes export look like?
The export is a tuple with two elements: a glob pattern and a function. Nx evaluates the glob against workspace files and passes every match to your function. Because the glob is evaluated before your code runs, it is the main lever for performance. A precise pattern such as **/service.yaml keeps Nx from calling your plugin for files it will only discard. Any filtering you do inside the function happens after that work has already been paid for.
The function receives three arguments:
- The matched config file paths. These are relative to the workspace root. In the batched variant, your function receives all matches at once, so expensive setup such as loading a schema or spawning a tool happens once rather than once per file. The original variant called the function once per file.
- The plugin options. These are whatever the user put under this plugin's entry in
nx.json. Use them for target names and similar choices instead of hardcoding values, so teams can avoid collisions with other plugins. - A context object. It includes the workspace root, which you need to turn relative paths into absolute ones before reading files.
The return value maps project roots to partial project configurations, typically targets and sometimes metadata. Nx merges these with configuration from other plugins and from project.json. That is why you return only what you infer, not a complete project definition.
The API has changed over time. The batched form was introduced alongside the per-file form, and the exact return wrapping differs between them. Check the signature and types shipped with your installed Nx version rather than relying on examples written for another release.
import { dirname, join } from 'node:path';
import { existsSync } from 'node:fs';
import type { CreateNodesV2 } from '@nx/devkit';
// Options users set under this plugin's entry in nx.json.
export interface ServicePluginOptions {
deployTargetName?: string;
}
export const createNodesV2: CreateNodesV2<ServicePluginOptions> = [
// Precise glob: Nx only calls us for files we actually handle.
'**/service.yaml',
// Batched form: all matches arrive at once, so shared setup runs once.
async (configFiles, options, context) => {
const targetName = options?.deployTargetName ?? 'deploy';
return configFiles.map((configFile) => {
// Paths are relative to the workspace root.
const projectRoot = dirname(configFile);
const absPath = join(context.workspaceRoot, configFile);
const hasDockerfile = existsSync(
join(context.workspaceRoot, projectRoot, 'Dockerfile')
);
// Return only what we infer; Nx merges it with project.json
// and other plugins. Each result is tied to its source file.
return [
configFile,
{
projects: {
[projectRoot]: {
targets: {
[targetName]: {
command: `./scripts/deploy.sh ${absPath}`,
cache: false,
metadata: { description: hasDockerfile ? 'Image deploy' : 'Plain deploy' },
},
},
},
},
},
] as const;
});
},
];
A batched createNodesV2 plugin that matches service.yaml files, reads target names from plugin options, and returns partial project configs keyed by project root; confirm the types against your installed Nx version.
How do you build a minimal createNodes plugin for a service manifest?
Take a hypothetical service.json file that each backend service keeps at its root. It declares the service name, its entry point, and the port it listens on. The plugin's job is to turn every such file into a project with serve and build targets, so that nobody has to write a project.json.
- Glob for the manifest. Set the glob to
**/service.json. Keep the pattern narrow. Nx evaluates it across the whole workspace, and a broad pattern like**/*.jsonsends many unrelated files through your code. - Read and parse it. Read each matched file relative to the workspace root. If the file fails to parse, throw an error that names the path, so the failure points at the file rather than at your plugin.
- Derive the project root. Use the directory that contains the manifest. Don't use a path declared inside the file. Using the file's location ties the project's identity to the filesystem, and that gives stable results across machines.
- Return targets. Build a target configuration keyed by that project root. Its commands reference fields from the parsed manifest.
To register the plugin, add an object to the plugins array in nx.json. The object has a plugin field pointing to your module and an options field.
Expose the target names as options, for example serveTargetName and buildTargetName, with sensible defaults. This is what makes gradual adoption possible:
- A team that already has a hand-written
buildtarget can setbuildTargetNametoservice-build. Both targets then coexist while the team migrates, with no silent merge into the existing definition. - Nx includes plugin options in its cache of inferred results, so changing a target name triggers a fresh computation rather than serving stale output.
// Register in nx.json:
// { "plugins": [{ "plugin": "./tools/service-plugin", "options": { "buildTargetName": "service-build" } }] }
import { CreateNodesV2, CreateNodesContextV2, createNodesFromFiles } from '@nx/devkit';
import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
export interface ServicePluginOptions { serveTargetName?: string; buildTargetName?: string; }
interface ServiceManifest { name: string; entry: string; port: number; }
// Narrow glob: only service.json files are passed to the plugin.
export const createNodesV2: CreateNodesV2<ServicePluginOptions> = [
'**/service.json',
(configFiles, options, context) =>
createNodesFromFiles(createNodesForManifest, configFiles, options, context),
];
function createNodesForManifest(configFile: string, options: ServicePluginOptions | undefined, context: CreateNodesContextV2) {
// Configurable target names let teams avoid collisions with existing targets.
const serveTargetName = options?.serveTargetName ?? 'serve';
const buildTargetName = options?.buildTargetName ?? 'build';
// The project root comes from the file's location, not from its contents.
const projectRoot = dirname(configFile);
let manifest: ServiceManifest;
try {
manifest = JSON.parse(readFileSync(join(context.workspaceRoot, configFile), 'utf-8'));
} catch (e) {
// Name the file so the error points at the manifest rather than at the plugin.
throw new Error(`Invalid service manifest at ${configFile}: ${(e as Error).message}`);
}
return {
projects: {
[projectRoot]: {
name: manifest.name,
targets: {
[buildTargetName]: { command: `esbuild ${manifest.entry} --bundle --platform=node --outfile=dist/main.js`, options: { cwd: projectRoot } },
[serveTargetName]: { command: `node ${manifest.entry}`, options: { cwd: projectRoot, env: { PORT: String(manifest.port) } } },
},
},
},
};
}
A minimal createNodesV2 plugin that globs for service.json, parses it with a path-specific error, uses the manifest's directory as the project root, and returns build and serve targets whose names can be changed through plugin options in nx.json.
How should inferred targets define inputs, outputs, and caching?
Every field on an inferred target changes either what Nx hashes, what it restores, or what it schedules. Get one wrong and nothing errors. Nx simply restores the wrong artifacts or rebuilds when it doesn't need to. A stale cache hit is worse than having no cache at all, because the team stops trusting green builds.
| Field | What it controls | Most common mistake |
|---|---|---|
command / executor |
What runs. A command is shorthand for the run-commands executor; its string is part of the task hash. |
Embedding absolute paths or timestamps, so the hash differs across machines. |
options.cwd |
Where the process runs. It resolves from the workspace root, so pass the project root path. | Leaving it unset, so the tool reads config from the workspace root instead of the service. |
inputs |
Which files, environment variables and runtime values feed the hash. | Omitting the manifest, a shared config file or ^production. Changes then produce cache hits with old results. |
outputs |
Which paths Nx stores and restores on a hit. | Listing a parent directory, or missing a generated file, so a restore produces a partial tree. |
dependsOn |
Which tasks must finish first, for example ^build for upstream projects. |
Leaving it out. The task then reads stale upstream artifacts that are not reflected in its hash. |
cache |
Whether Nx caches the task at all. | Enabling it for deploys or tasks with side effects. |
Affected detection works from file ownership and graph edges. Inputs only decide whether an affected task can be skipped. Prefer narrow, named inputs over {projectRoot}/**/* so that edits to tests or docs don't invalidate a production build.
// tools/nx-tsc-plugin.ts: infers build and deploy targets for every tsconfig.build.json
import { dirname } from 'node:path';
import { CreateNodesV2, createNodesFromFiles } from '@nx/devkit';
export const createNodesV2: CreateNodesV2 = [
'**/tsconfig.build.json',
(configFiles, options, context) =>
createNodesFromFiles(
(configFile) => {
const projectRoot = dirname(configFile);
return {
projects: {
[projectRoot]: {
targets: {
build: {
// Relative path only: the command string is hashed, so keep it identical on every machine
command: 'tsc -p tsconfig.build.json',
// run-commands resolves cwd from the workspace root, so pass the project root
options: { cwd: projectRoot },
// 'production' is a namedInput in nx.json that excludes tests and docs.
// '^production' hashes upstream sources, and the tsc version is hashed too.
inputs: ['production', '^production', { externalDependencies: ['typescript'] }],
// Exactly what tsc emits; Nx restores this path on a cache hit
outputs: ['{projectRoot}/dist'],
// Upstream projects build first so their dist exists before this task reads it
dependsOn: ['^build'],
cache: true,
},
deploy: {
command: 'node scripts/deploy.mjs',
options: { cwd: projectRoot },
dependsOn: ['build'],
// Side effects: a cache hit here would silently skip a real deploy
cache: false,
},
},
},
},
};
},
configFiles,
options,
context,
),
];
A minimal createNodesV2 plugin that infers a cached build target with explicit cwd, narrow named inputs, an exact outputs path and an upstream dependsOn, plus an uncached deploy target.
How do you keep the plugin fast, deterministic, and correctly scoped?
Performance comes first
Nx runs your plugin whenever it computes the project graph. That happens on most commands and on every relevant file change while the daemon is running. A slow plugin makes every invocation slow.
- Keep the glob narrow. Match the exact manifest filename, such as
**/service.yaml, not a broad pattern that sends every YAML file through your parser. - Make no network calls. A registry lookup or remote config fetch adds latency to graph computation. It also makes the graph depend on something the repo doesn't contain.
- Memoize expensive parsing. Hash the contents of each manifest and anything it references. Then cache the derived configuration under that hash, and skip parsing when the hash hasn't changed.
Determinism
The same commit should produce the same graph on a laptop and in CI. These are the usual causes of drift:
- Environment variables such as
CIorNODE_ENV. - Timestamps.
- Unordered filesystem reads. Sort any directory listing before you use it to build targets or inputs.
A graph that differs between machines produces cache misses that are hard to explain. It can also produce targets that exist in one environment and not the other.
Precedence and scope
Nx applies plugins in the order they appear in the plugins array in nx.json. When two plugins infer the same target name, the later plugin's configuration is merged on top of the earlier one. Explicit targets in project.json are applied last. They can override an inferred target, or extend it with only the fields you need to change.
include and exclude on a plugin entry limit which matched files it processes. Use them to scope a plugin to one part of the repo, such as services/**.
Overlapping globs across plugins are risky. Two plugins can produce duplicate targets, or one can silently overwrite the other. The outcome depends on plugin order and directory layout, so moving a folder during a refactor can change which targets exist.
How do you debug and test a createNodes plugin?
That kind of drift is why the first check after any plugin change should be the resolved project, not the plugin source. Run nx show project <name> to see the targets Nx actually computed for one project. Add --web for an interactive view that marks each inferred target with the plugin and config file that created it. Add --json when you want output you can diff. If a target is missing, duplicated, or has the wrong inputs, this view tells you whether your plugin produced it, another plugin overwrote it, or project.json overrode it.
If your edits don't show up, the cause is usually stale state rather than your logic. The Nx daemon keeps the project graph in memory, and computed graph data is cached on disk. Run nx reset to stop the daemon and clear the cache, then rerun the command. While iterating on the plugin, set NX_DAEMON=false so every invocation recomputes the graph from scratch. This costs speed but removes a whole category of confusion.
For tests, skip the workspace entirely. The createNodes export is a glob paired with a plain function, so you can import the function and call it directly. Pass it a list of fixture manifest paths, your plugin options, and a stub context containing a workspaceRoot that points at a fixtures directory. Then assert on the returned project and target configuration: target names, inputs, outputs, and cache flags. These tests run in milliseconds. They also catch nondeterminism: call the function twice and compare the results.
What are the alternatives to a custom createNodes plugin?
A plugin is not the only way to give projects consistent targets. Three alternatives cover most of the same ground, and each trades visibility against how much work it takes to keep many projects in line.
| Approach | Visibility | Setup cost | Maintenance burden | Time saved as projects grow |
|---|---|---|---|---|
Explicit project.json targets |
Highest: every target is written in the project | Lowest | Grows with each project, and copies drift apart | Little: each new project repeats the work |
targetDefaults in nx.json |
Medium: the target is declared per project, but defaults live elsewhere | Low | One place to change shared inputs, outputs, and cache |
Moderate: defaults are shared, but targets are still declared by hand |
| Existing official plugin | Medium: inspect with nx show project |
Low: install and register | Maintained upstream, so you track its updates | High, if your tooling matches what it expects |
| Custom createNodes plugin | Medium: inspect with nx show project |
Highest: code, tests, and review | You own the code for good | Highest when many projects share a file convention |
How they differ in practice:
targetDefaultskeeps cache settings consistent across projects. It cannot create a target from a file on disk, so someone still has to add the target to each project.- An official plugin gives you inference without code to maintain. It only covers tools it already understands, not your in-house manifest format.
- A custom plugin is worth its cost only when the convention is stable and the same across many projects. If teams keep adding exceptions, you end up maintaining a parser full of special cases.
Decision rule:
- If an official plugin understands your tooling, use it.
- Otherwise, if the problem is inconsistent cache settings, use
targetDefaults. - Write a createNodes plugin only when a file convention appears in many projects and adding targets by hand is a recurring cost.
- Keep explicit
project.jsontargets for one-off projects.
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 createNodes 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.
- Changing a shared variable is one edit and one review instead of editing every service's
.envby 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.