What is workspace drift and why do nx sync generators exist?

Workspace drift is the gap between what your code actually imports and what your configuration files claim it depends on. In an Nx monorepo, the project graph already knows that orders-api depends on billing-core and shared-logging, because Nx derives those edges from source imports and package manifests. Several config files still list the same relationships by hand: the references array in each project's tsconfig.json, path mappings in a base tsconfig, and tool configs that enumerate upstream projects. Each of those lists is a copy of graph data, and copies go stale.

They go stale because nothing ties them to the import that created the dependency. An engineer adds an import from shared-auth, the code compiles locally through path mappings, and the PR merges. The missing tsconfig reference does not cause an obvious failure in that change. It shows up later as a tsc --build that cannot resolve declarations, an incremental build that skips work it should have done, or editor errors that disagree with CI. A removed import has the opposite effect: stale references make builds slower and pull projects into type-checks for no reason. Either way, the failure appears far from the commit that caused it.

Sync generators fix this by treating the project graph as the single source of truth. They regenerate derived config from the graph so nobody has to maintain those lists by hand. This matters most for backend and platform engineers running medium-to-large Nx workspaces with dozens of interdependent libraries, where dependency edges change every week and no reviewer can reliably catch a missing reference.

Who should use nx sync generators?

Sync generators fit teams where three conditions hold at once: the workspace already runs on Nx, some config file duplicates information the project graph already has, and that duplicated config changes often enough that people forget to update it.

In practice that usually means:

  • Platform and build teams that own a shared Nx workspace. They field the "works locally, fails in CI" tickets that drift causes, and they are the natural owners of generator code and of the nx sync:check gate.
  • Teams using, or moving to, TypeScript project references. Project references require every dependency edge to be listed in tsconfig files. That is the most common kind of graph-derived config, and the Nx JS plugin already ships a sync generator for it.
  • Backend teams whose deploy, packaging, or container tooling reads a dependency list. If a deploy script needs to know which internal libraries a service uses, a custom sync generator can produce that list from the graph instead of from a hand-edited file.
  • Workspaces with many libraries and frequent cross-library changes. The more often dependency edges change, the more often hand-maintained lists go stale.

Sync generators are a weaker fit for small workspaces with a handful of projects whose dependencies rarely change. A reviewer can catch a missing reference there, and the cost of owning generator code and a CI gate may exceed the time saved. They are also a poor fit if your project graph is known to be inaccurate. Fix the graph first, because the generator copies whatever the graph says. Sync generators are a relatively recent Nx feature, so confirm that your Nx version supports them and check its documentation for the exact configuration shape before you adopt them.

How do nx sync generators work?

A sync generator uses the same Tree API as any Nx generator. The difference is in how it is invoked. A normal generator scaffolds something once, and its output becomes hand-maintained code. A sync generator reads the current project graph, computes what certain files should contain, and writes that state through the Tree. Nx runs it repeatedly, so it must be idempotent: when nothing has changed, it should produce no changes. It can also return an out-of-sync message, so Nx reports a reason such as "project references are missing a dependency" instead of only a file diff.

In short, here is how it works. Nx computes the project graph from your source. The sync generator turns that graph into the expected file contents in a staged Tree. Nx then compares the staged contents with what is on disk. Depending on the command, Nx either writes the difference (nx sync, or automatically before a task) or only reports it and exits non-zero (nx sync:check).

Data flows in one direction:

source imports → project graph → sync generator → config files → nx sync:check in CI

There are two ways to attach a sync generator:

Task sync generator Global sync generator
Registered in syncGenerators option on a target sync section of nx.json
Trigger Before that target runs, and on nx sync On nx sync and nx sync:check
Scope Projects that participate in the task Whole workspace
Typical files Per-project tsconfig references Root-level aggregate config
Choose when A task would fail or misbehave on stale config The file has no single owning task

nx sync applies pending changes. nx sync:check reports drift and writes nothing, which makes it the command to use as a gate. Locally, Nx detects drift before running a task and prompts you to apply the changes. The applyChanges setting in the sync config lets Nx apply them automatically without the prompt.

// tools/sync/root-references.ts: a global sync generator.
// Keeps the root tsconfig.json `references` aligned with the project graph.
import { Tree, createProjectGraphAsync, readJson, writeJson } from '@nx/devkit';

export default async function rootReferencesSync(
  tree: Tree
): Promise<{ outOfSyncMessage?: string } | void> {
  // Desired state is derived from the graph, not from what is on disk.
  const graph = await createProjectGraphAsync();
  const desired = Object.values(graph.nodes)
    .map((node) => node.data.root)
    .filter((root) => tree.exists(`${root}/tsconfig.json`))
    .sort() // stable ordering keeps repeated runs idempotent
    .map((root) => ({ path: `./${root}` }));

  const tsconfig = readJson(tree, 'tsconfig.json');
  const current = JSON.stringify(tsconfig.references ?? []);

  // No change needed: write nothing, so nx sync:check passes.
  if (current === JSON.stringify(desired)) {
    return;
  }

  // Write through the Tree. Nx decides whether to apply the change
  // (nx sync) or only report it (nx sync:check).
  writeJson(tree, 'tsconfig.json', { ...tsconfig, references: desired });

  // Nx shows this reason alongside the diff.
  return {
    outOfSyncMessage:
      'Root tsconfig.json references do not match the projects in the workspace.',
  };
}

A global sync generator that reads the project graph, computes the root tsconfig.json references, writes only when they differ, and returns an out-of-sync message explaining the drift.

How do sync generators keep tsconfig references aligned?

Take a workspace with three projects: an api application, a billing library, and a shared-utils library. billing currently depends on nothing inside the workspace, so its tsconfig has no project references to other libraries.

A developer adds an import from shared-utils into a file in billing. Nx's import analysis records a new edge in the project graph: billing depends on shared-utils. The TypeScript sync generator in the Nx JS plugin reads that graph and compares it with the references declared in each project's tsconfig. It finds that billing is missing a reference and adds one that points at shared-utils. It may also update the root-level tsconfig that lists all projects. If the import is later removed, the edge disappears and the generator removes the stale reference on the next sync.

The change only touches tsconfig files. No source code is modified. Without the generator, the reference would have to be added by hand. If someone forgot, tsc --build could compile projects in the wrong order or skip incremental rebuilds, and the error would show up far from the import that caused it.

Adopting this setup costs more than enabling one generator:

  • Compiler settings: Referenced projects generally need composite enabled and must emit declaration files, which changes your compiler settings and build outputs.
  • Circular dependencies: TypeScript rejects circular project references. A cycle that path aliases previously tolerated becomes a hard error, and you have to break it before the migration can land.
import { formatCurrency } from '@acme/shared-utils';

$ npx nx sync          # writes the missing references
$ npx nx sync:check    # exits non-zero if files are out of sync

{
  "extends": "../../tsconfig.base.json",
  "references": []
}

{
  "extends": "../../tsconfig.base.json",
  "references": [{ "path": "../shared-utils" }]
}

{
  "compilerOptions": {
    "composite": true,      // required for a project to be referenced
    "declaration": true,    // consumers read the emitted .d.ts files
    "outDir": "../../dist/out-tsc/shared-utils"
  }
}

Conceptual sequence showing how a new import from shared-utils in billing becomes a graph edge, how nx sync adds the matching tsconfig reference, and which compiler settings the referenced project needs.

How do you write a custom Nx sync generator?

Take a concrete case: each service has a deps.generated.json that lists the internal libraries it depends on, and a deploy tool reads that file. The sync generator is an ordinary Nx generator function that receives a Tree. It loads the project graph with createProjectGraphAsync from @nx/devkit, walks the service's dependencies, and computes the file's desired contents. It writes them only through the Tree. Because the tree stages changes instead of writing to disk, Nx can diff the result. That diff is what lets nx sync:check report drift without modifying anything. When the contents differ, the generator returns an outOfSyncMessage that explains in one sentence what changed and why it matters.

Determinism matters most here. Sort library names explicitly and don't rely on graph iteration order. Leave out timestamps, absolute paths, and anything derived from process.env or the host OS. Use workspace-relative paths with forward slashes. If two machines produce different bytes, CI will flag drift that nobody can reproduce locally.

The generator must also be idempotent. A second run should produce no changes. Its output also has to match what your formatter and linter would produce, so run formatFiles or emit already-canonical JSON. Otherwise a formatting pass rewrites the file and sync:check fails on whitespace.

Test this behaviour directly. Build a fixture workspace with createTreeWithEmptyWorkspace, run the generator, then run it again and assert that tree.listChanges() is empty after the second pass.

Assign the generator an owner. Devkit APIs and the shape of the project graph can change between Nx upgrades, so include this code in your upgrade checklist.

import { Tree, createProjectGraphAsync, formatFiles, joinPathFragments } from '@nx/devkit';

// Sync generator: keeps <service>/deps.generated.json in step with the project graph.
export default async function depsSyncGenerator(tree: Tree) {
  const graph = await createProjectGraphAsync();

  for (const [name, node] of Object.entries(graph.nodes)) {
    // Assumed convention: services are tagged 'type:service'.
    if (!node.data.tags?.includes('type:service')) continue;

    const libs = (graph.dependencies[name] ?? [])
      .map((dep) => dep.target)
      // npm:* targets are external nodes, not in graph.nodes, so they drop out here.
      .filter((target) => graph.nodes[target]?.type === 'lib');

    // Dedupe, then sort explicitly. Never rely on graph iteration order.
    const libraries = [...new Set(libs)].sort();

    // joinPathFragments gives workspace-relative, forward-slash paths on every OS.
    const path = joinPathFragments(node.data.root, 'deps.generated.json');

    // Canonical JSON: 2-space indent, trailing newline, no timestamps or env data.
    const desired = JSON.stringify({ libraries }, null, 2) + '\n';

    // Write only on real differences so an in-sync run stages nothing.
    if (tree.read(path, 'utf-8') !== desired) {
      tree.write(path, desired);
    }
  }

  // Match the repo formatter so a later format pass can't introduce drift.
  await formatFiles(tree);

  if (tree.listChanges().length > 0) {
    return {
      outOfSyncMessage:
        'deps.generated.json no longer matches the project graph; the deploy tool would ship stale library dependencies.',
    };
  }
}

A deterministic, idempotent sync generator that reads the project graph, computes a sorted list of internal libraries for each service, writes only through the Tree when the contents differ, and returns an outOfSyncMessage when it stages changes.

How should you enforce nx sync:check in CI and code review?

Run nx sync:check as one of the first CI steps, before lint, type-check, or affected builds. It reads the workspace and the project graph without building anything, so it fails within seconds. If it runs later, a stale references array can surface first as a confusing type-check error or as an incremental build that silently skips a dependency. Engineers then spend time diagnosing a failure that was really drift.

When the check fails, someone has to commit the fix. There are two common options:

Approach Strengths Costs
Developer runs nx sync and commits The change lands in the same PR and is visible in review. No extra CI permissions are needed. Developers must know the fix path, and forgetting it causes a red build.
Bot pushes the sync commit to the PR branch Developers don't need to act. CI needs write access to the branch, it may need to retrigger pipelines, and the generated diff is easier to miss in review.

For most teams the developer-commits approach is simpler. To keep the check from feeling like friction, make the CI failure message state the exact fix: run nx sync and commit the result.

Mark generator-owned files so reviewers don't hand-edit them. Add a header comment to each file, and use a CODEOWNERS entry that routes changes to the platform team. Keep intentional settings, such as compiler options and path overrides, in a base config that the generated file extends. The generator then rewrites only the section it owns and never overwrites deliberate edits.

#!/usr/bin/env bash
set -euo pipefail

if ! npx nx sync:check; then
  echo "" >&2
  echo "Workspace config is out of sync with the project graph." >&2
  echo "Fix: run 'npx nx sync' locally, then commit the changed files." >&2
  echo "Do not hand-edit generator-owned files. Put intentional settings" >&2
  echo "in the base config that those files extend." >&2
  exit 1
fi

npx nx affected -t lint typecheck build --base=origin/main

A CI-agnostic script that runs nx sync:check before lint, type-check and build, and prints the exact fix path when it detects drift, so the check works as a safety net rather than an unexplained red build.

How can nx sync generators save engineering time?

The time saved comes from three places:

  • No manual bookkeeping. Nobody has to remember to add or remove a tsconfig reference, a path entry, or a line in a deploy manifest when an import changes. The fix is one command, and Nx can run it automatically before tasks.
  • Shorter diagnosis. Drift that would otherwise surface later as a confusing tsc --build error, a skipped incremental rebuild, or an editor/CI mismatch is caught at the start of CI with a message that names the cause. The expensive part of a drift bug is usually tracing it back to the commit that caused it, not fixing it.
  • Less review burden. Reviewers stop checking whether config lists match imports, because the CI gate verifies that mechanically.

Whether this adds up to a net saving depends on how often drift happens in your workspace. Here is an illustrative estimate. Every input is assumed, not measured, so replace them with your own numbers:

  • Assumed: 2 PRs per week introduce a dependency change without the matching config update.
  • Assumed: each one costs 45 minutes of someone's time on average, counting diagnosis of the downstream failure, the fix, and a re-run of CI.
  • Assumed: owning a custom generator costs about 1 engineer-day (8 hours) per quarter for upgrades, tests, and fixes, which is roughly 0.6 hours per week over a 13-week quarter.

Under those assumptions, drift costs about 2 × 45 = 90 minutes per week, against about 37 minutes per week of generator upkeep. That leaves a net saving of under an hour per week. Halve the drift rate and the saving mostly disappears. Double it and the case becomes clear. When you rely only on the built-in TypeScript sync generator, there is little custom code to maintain, so the upkeep side of the calculation shrinks. The point of running these numbers is to make the decision explicit: count how often drift-related failures actually happen before writing custom generators.

When should you avoid or scope down nx sync generators?

A sync generator is only as correct as the project graph it reads. If dynamic imports go undetected or implicit dependencies are misconfigured, the generator writes the wrong references into every affected project at once. Audit the graph before you automate on top of it.

Running sync before tasks has other costs. It adds latency to each run, and developers may see a prompt or find their working tree changed when they only wanted to run tests. Generated files in version control also create PR churn. A shared, frequently edited tsconfig can become a regular source of merge conflicts. If the output is non-deterministic, for example because of unsorted references or environment-dependent paths, nx sync:check becomes flaky, and people learn to bypass it.

Custom generators also cost engineering time. They need maintenance, tests, and updates when Nx or TypeScript changes. Write one only when that cost is smaller than the time your team spends fixing config by hand.

To scope down, use the sync section of nx.json. You can disable specific task sync generators there and pass generator options centrally. Start with a subset of targets, and enable the generator workspace-wide only after its output has been stable for a while.

Approach Ongoing cost Guarantee
Sync generators Generator upkeep, CI time Config derived from the graph
Hand-maintained config plus lint rules Manual edits Errors detected, not fixed
Scripts or pre-commit hooks Script upkeep, can be skipped locally Only as strong as enforcement
Drop duplicated config (no project references) Possibly slower type-checking Nothing to drift

What are the alternatives to nx sync generators?

The table above summarizes the options. Each one makes a different trade-off.

Hand-maintained config with a check. Keep editing tsconfig references and manifests by hand, and add a lint rule or CI script that compares them with the project graph and fails on a mismatch. You get detection without automatic repair. This works when drift is rare, but every failure still costs a manual fix, and the check itself is custom code you have to maintain.

Standalone scripts or pre-commit hooks. A script that queries the graph and rewrites files can do much of what a sync generator does. The differences are integration and enforcement. Nx does not run the script before tasks, it has no built-in check mode unless you write one, and local hooks can be skipped. If you go this way, you still need a CI step that runs the script and fails on a non-empty diff.

Remove the duplicated config. Often the most robust option is to stop keeping a copy at all. Many Nx workspaces resolve internal libraries through path mappings in a base tsconfig and type-check each project separately, without TypeScript project references. In that setup there is no references array to drift. The trade-off is that you give up tsc --build incremental builds across projects, and type-checking can be slower in large workspaces.

Compute derived data at task time instead of committing it. For files like deps.generated.json, a build or deploy target can produce the dependency list as a task output, for example by querying the graph, instead of committing it to the repository. Nothing in version control can go stale. The cost is that tools which read the file statically, such as editors or external systems that inspect the repository, never see it, and the data is only as fresh as the last task run.

Sync generators make the most sense when the file must exist in the repository, must stay exactly consistent with the graph, and changes often enough that manual upkeep or detect-only checks waste time.

How do you debug a sync generator that produces wrong output?

When a sync generator writes the wrong thing, the cause is usually in its inputs rather than its logic. Work through these checks in order:

  1. Inspect the graph the generator reads. A sync generator derives its output from the project graph, so a missing or incorrect dependency produces confidently wrong config. Run nx graph or nx show project <name> and confirm the edges you expect are present. Imports Nx cannot statically detect, such as dynamic paths or runtime-only dependencies, need an explicit implicitDependencies entry. Otherwise the generator has nothing to reference.

  2. Run nx sync locally and read the diff. Start from a clean working tree, run the command, then use git diff. Each changed line shows exactly what the generator believes is true. Removals often point to a dependency the graph lost.

  3. Run it twice. A second nx sync should produce no changes. If it does, the generator is not idempotent. Common causes are appending instead of replacing, or building output from a previous partial write.

  4. Hunt for nondeterminism. If nx sync:check fails on some machines or CI runs but not others, look for differences that do not change meaning:

    • Unsorted arrays, where object or filesystem iteration order varies.
    • Formatting that differs from what your formatter produces.
    • Paths built with OS-specific separators instead of forward slashes.

    Sort explicitly and normalize paths before writing.

  5. Rule out a stale daemon. The Nx daemon caches the project graph. After large refactors or branch switches, run nx reset and sync again. If the output changes, the daemon was serving an outdated graph.

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 sync generators, 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.