Why do TypeScript project references drift out of sync in a monorepo?
In a TypeScript monorepo, each package already declares what it depends on. The package manager reads it from workspace dependencies in package.json, and Nx infers the same edges into its project graph from imports and manifests. With project references and composite builds, you write that information a third time in each tsconfig.json's references array. Nothing forces the three copies to agree.
They drift in ordinary ways. Someone adds an import from libs/billing to libs/invoices and updates package.json, but forgets the reference. Someone deletes a dependency and leaves the reference behind. Each mistake looks harmless in review, but tsc --build trusts the references, not your imports, so the build goes wrong:
- Stale builds:
tsc -bdoes not rebuild a missing reference first. The consumer type-checks against old.d.tsoutput from an earlier build. - Type errors that never appear: a breaking change in the dependency stays invisible until someone does a clean build, often in CI.
- Confusing failures: errors that point at output files which were never built, or that only reproduce on a fresh clone.
Path aliases never had this problem because they do much less:
| Concern | tsconfig paths aliases |
Project references |
|---|---|---|
| What it changes | Module resolution only | Build graph for tsc --build |
| Build order | None | Dependencies built first |
| Incremental boundaries | None, one large program | Per-project, with emitted declarations |
| Cost when wrong | Import fails to resolve | Silent staleness |
Moving to references therefore adds a maintenance cost that aliases never had. Backend and platform engineers with growing monorepos feel it most, because every new library adds edges that someone has to keep in sync by hand.
cat libs/invoices/package.json
cat libs/invoices/tsconfig.json
npx tsc -b libs/invoices --verbose
npx tsc -b libs/invoices --clean
rm -rf libs/billing/dist
npx tsc -b libs/invoices --verbose
The package.json declares a dependency on @acme/billing, but the hand-written tsconfig references omit it, so tsc -b never builds billing first and type errors stay hidden until a clean build.
Who should use Nx sync generators?
Sync generators are aimed at teams that already run an Nx workspace and either build TypeScript with project references or plan to move to them. In practice that means:
- Platform and build engineers who own the monorepo's tooling and currently field "works on my machine, fails on a clean build" reports caused by missing or stale references.
- Application and library teams in larger workspaces, where projects are added, split and re-wired often enough that hand-editing
referencesarrays becomes routine work that reviewers rarely check carefully. - Teams that want CI to enforce derived files. The same mechanism that keeps
tsconfigreferences correct can keep other graph-derived files correct, such as a generated CODEOWNERS file, through a custom generator.
It is a weaker fit for small repos with a handful of projects, for teams that intend to stay on tsconfig paths aliases without composite builds, and for repos that are not using Nx at all. Adopting Nx only to get this feature is a much larger decision than the feature itself. The last section of this article covers those cases in more detail.
What are Nx sync generators and how do they work?
Nx removes that manual step by treating the project graph as the only source of truth. A sync generator is a generator that Nx runs to make workspace files agree with the graph. The graph already knows which projects depend on which, because Nx infers those edges from imports and configuration. Files such as tsconfig.json references then become derived output. You no longer maintain them by hand.
Task sync generators and global sync generators
Nx distinguishes two kinds of sync generators by what triggers them:
- Task sync generators are attached to a target. A target opts in by listing generators in its
syncGeneratorsarray. Before the task runs, Nx checks only those generators. For example, abuildtarget that depends on correct project references can make sure they are current before compilation starts. - Global sync generators are listed under the
syncsection ofnx.json. They are not tied to any task. Use them for workspace-wide consistency that no single target owns.
The execution flow
Every sync run follows the same steps:
- Nx builds or loads the project graph.
- Nx runs each relevant generator against a virtual file tree. Nothing is written to disk at this point.
- Nx compares the virtual tree with the files on disk.
- Nx either reports which files are out of sync or applies the changes.
The entry points differ in how they finish step 4:
nx syncapplies the changes.nx sync:checkonly reports differences and exits with an error when it finds drift, which makes it suitable as a gate.- Running a task checks that task's sync generators first. If the files are out of sync, Nx can prompt you to apply the changes or apply them according to the workspace configuration.
+---------------------------+ +-------------------------------+
| Task sync generators: | | Global sync generators: |
| target syncGenerators | | nx.json: sync section |
+-------------+-------------+ +---------------+---------------+
| |
+------------------+------------------+
v
+-------------------------------------------------+
| 1. Build/load project graph (source of truth) |
+------------------------+------------------------+
v
+-------------------------------------------------+
| 2. Run generators on a virtual tree (no writes) |
+------------------------+------------------------+
v
+-------------------------------------------------+ +------------+
| 3. Diff virtual tree against files on disk |<---| disk files |
+------------------------+------------------------+ +------------+
v
+-------------------------------------------------+
| 4. Report drift or apply changes |
+------------------------+------------------------+
+----------------------+-----------------------+
v v v
+-------------------+ +---------------------+ +---------------------+
| nx sync | | nx sync:check | | running a task |
| applies changes | | reports drift only | | checks its sync gens|
| to disk | | exits non-zero | | prompts or applies |
+-------------------+ +---------------------+ +---------------------+
Task and global sync generators feed one flow: Nx loads the project graph, runs generators on a virtual tree, diffs it against disk, and then nx sync applies the changes, nx sync:check reports drift and fails, and a task run checks its own generators before executing.
How do you set up the @nx/js TypeScript sync generator?
Prerequisites TypeScript enforces on its own
Project references depend on four settings, whether or not Nx is involved:
composite: truein every referenced project. It makestscrecord each project's inputs and outputs sotsc -bcan skip unchanged ones.- Declaration emit. Consumers type-check against the referenced project's
.d.tsoutput, not its sources.compositeturns ondeclaration, so don't setnoEmiton referenced projects. - A distinct
outDirand.tsbuildinfoper project. If two projects write to the same location, each overwrites the other's build state. - A root solution-style
tsconfig.jsonwith an emptyfilesarray and areferencesentry for each project. This givestsc -bone entry point for the whole workspace.
Wiring the generator
Add @nx/js:typescript-sync to the syncGenerators array of your typecheck and build targets. The generator reads the project graph and writes references to match it, both in each project's tsconfig and in the root tsconfig.
Take api, which imports auth and db. Before a sync, api's references array is empty. After a sync, it points at both libraries, and the root tsconfig lists all three projects. If you then import a new logging library into api, the next sync produces a two-line diff: one new entry in api's references and one in the root's.
Misconfiguration surfaces in tsc, not in sync
The generator updates references and nothing else. If logging is missing composite, sync still succeeds. The failure shows up when tsc -b runs and reports that the referenced project must have composite: true (TS6306). Projects that share an output directory fail the same way, with tsc errors about overwriting files. When you see these errors, fix the project's compiler options. Re-running sync won't change them.
"targetDefaults": {
"typecheck": { "syncGenerators": ["@nx/js:typescript-sync"] },
"build": { "syncGenerators": ["@nx/js:typescript-sync"] }
}
"references": [
{ "path": "../../libs/auth" },
- { "path": "../../libs/db" }
+ { "path": "../../libs/db" },
+ { "path": "../../libs/logging" }
]
"files": [],
"references": [
{ "path": "./apps/api" },
{ "path": "./libs/auth" },
- { "path": "./libs/db" }
+ { "path": "./libs/db" },
+ { "path": "./libs/logging" }
]
{
"compilerOptions": {
"composite": true, // required for any referenced project
"declaration": true, // implied by composite; consumers read .d.ts
"outDir": "../../dist/libs/logging", // unique per project
"tsBuildInfoFile": "../../dist/libs/logging/tsconfig.tsbuildinfo"
},
"include": ["src/**/*.ts"]
}
This example registers the TypeScript sync generator in nx.json and shows the two-line references diff produced when api adds a dependency on logging. It also shows the composite, declaration and per-project output settings that you must add to logging yourself.
How does it work end to end, from a new import to an updated reference?
Putting the pieces together, this is what happens when a developer adds import { log } from '@acme/logging' to a file in apps/api:
- The graph picks up the edge. Nx analyses the source files and project configuration and records a dependency from
apitologgingin the project graph. No tsconfig file has changed yet. - A trigger fires. Either the developer runs
nx sync, or they run a target such asnx typecheck apiwhosesyncGeneratorslist includes@nx/js:typescript-sync. - The generator computes the expected references. For each project, it takes that project's dependencies from the graph and turns them into relative
pathentries. It does the same for the root solution tsconfig, which should list every project. All writes go to the virtual tree. - Nx diffs the result against disk. The only difference is the new
loggingentry inapps/api/tsconfig.jsonand in the roottsconfig.json. - The change is applied or reported.
nx syncwrites it. A task run prompts or applies it according tosync.applyChanges.nx sync:checkprints the out-of-sync files and exits non-zero. tsc -bnow sees the edge. Becauseapireferenceslogging,tsc -bbuildsloggingfirst and type-checksapiagainst fresh declarations, which removes the stale-build failure mode described at the start of this article.
The key design point is that the generator never inspects your imports itself. It only translates the project graph into tsconfig syntax. That is why the debugging section below starts with the graph, not the generator.
How should nx sync run locally versus in CI?
Day to day, there are two entry points. Running nx sync applies every pending change from registered sync generators and exits. Running any task whose target has sync generators attached makes Nx check sync state before it executes, so a stale references array is caught before tsc sees it.
What happens on that pre-task check is controlled by applyChanges under the sync key in nx.json. When it is unset, Nx prompts in an interactive terminal. Setting it to true applies changes without asking. Setting it to false skips both the prompt and the write.
| Setting | Local behaviour | Trade-off |
|---|---|---|
true |
Files rewritten silently before the task | Less friction, but unexpected diffs appear in the working tree |
| unset | Prompt on each out-of-sync run | Noisier, but every write is explicit |
false |
No write, no prompt | Predictable, but developers must run nx sync themselves |
Non-interactive environments have no one to answer a prompt. Choose their behaviour explicitly rather than relying on the default.
In CI, run nx sync:check as an early step. It exits non-zero when committed files differ from what the generators would produce. CI should verify rather than fix, because a pipeline that rewrites tsconfig files builds code that does not match the commit. The repository stays wrong, and the next developer inherits the drift.
Commit the generated tsconfig changes in the same commit as the dependency change that caused them. That keeps the history bisectable. Developers no longer edit references by hand, reviewers no longer check hand-edited references, and fewer stale-build failures need to be bisected.
#!/usr/bin/env bash
set -euo pipefail
npm ci
if ! npx nx sync:check; then
echo "Workspace is out of sync. Run 'npx nx sync' locally and commit" >&2
echo "the tsconfig changes with the dependency change that caused them." >&2
exit 1
fi
npx nx run-many -t build test
A vendor-neutral CI script runs nx sync:check first, so the pipeline fails on out-of-sync tsconfig references and never rewrites them. The comments show the local nx sync and commit step that keeps the reference changes and the dependency change in one commit.
How can Nx sync generators save engineering time?
The time savings come from removing three kinds of recurring work:
- Hand-editing references. Every new or removed dependency between projects used to mean finding the right tsconfig files, computing relative paths, and updating the root solution file. With the generator, the developer runs
nx sync(or lets a task trigger it) and commits the result. - Reviewing those edits. Reviewers no longer need to check that a
referencesarray matches the imports in a pull request.nx sync:checkin CI does that mechanically, and the diff it asks for is small and predictable. - Investigating stale-build failures. Missing references produce failures that appear only on clean builds or fresh clones, far from the change that caused them. These are the most expensive part, because someone has to recognise the symptom, bisect, and trace it back to a tsconfig file. When CI rejects out-of-sync commits, this class of failure is caught at the commit that introduces it.
A rough way to size the benefit for your own repo is to multiply how often dependencies change by how long each manual step takes. As an illustrative estimate, with assumed inputs only:
- Assumed: 5 cross-project dependency changes per week, each taking 5 minutes to edit references and have them reviewed. That is about 25 minutes per week, or roughly 100 minutes per month.
- Assumed: 1 stale-build incident per month that takes 2 hours to diagnose and fix.
- Illustrative total: about 100 + 120 = 220 minutes, or a little under 4 engineer-hours per month, for this hypothetical team.
These numbers are not measurements. Substitute your own counts from commit history and incident notes. Also subtract the costs listed in the last section: initial migration, occasional merge conflicts in the root tsconfig, and the time engineers spend learning what a failed nx sync:check means. In small repos the subtraction can outweigh the savings.
How do you write a custom Nx sync generator?
A sync generator is an ordinary Nx generator with a stricter contract. It receives the virtual Tree, reads the project graph (createProjectGraphAsync from @nx/devkit), writes the file the invariant requires, and returns an object that may include an outOfSyncMessage. Nx compares the tree before and after. If nothing changed, the workspace is in sync. If something changed, nx sync writes the changes to disk, and nx sync:check fails and prints your message. Write that message for the person reading a failed CI log, for example "CODEOWNERS is missing entries for 2 projects; run nx sync." Tell them what drifted, not only that something did.
A minimal example: generated CODEOWNERS
Assume each project declares an owning team in its metadata. The generator walks the graph's nodes, sorts them by project name, builds the file content, and writes it only if the result differs from the current file. The sort matters because graph iteration order is not guaranteed. Without a sort, two machines can produce the same entries in different orders, and sync:check will report drift that does not exist.
Registering it
- Task generator: add it to a target's
syncGeneratorsarray, either per project or throughtargetDefaultsinnx.json. It then runs before that target executes. Use this when the invariant only matters for that task. - Global generator: list it under
sync.globalGeneratorsinnx.json. It runs only throughnx syncandnx sync:check. CODEOWNERS fits here because no build depends on it.
Keep it deterministic and fast
These generators run before tasks and during checks. Avoid timestamps, random IDs, unordered globbing, environment-specific paths, and network calls. Any of these can produce flaky out-of-sync failures, and every millisecond the generator spends is added to each task run that triggers it.
Is the project graph wrong, or is the generator? Debugging drift
When a reference looks wrong, decide first whether Nx has the wrong picture of the workspace or whether the generator misread a correct picture. Start with what Nx believes. Run nx graph and focus on the project in question, then open its project details view (nx show project <name> gives the same information in the terminal). Compare the edges you see with the imports in the source.
If an edge is missing or extra in the graph, the problem is upstream of the generator. Common causes:
- Undeclared dependency. The project imports another project, but the dependency is not listed in its
package.json. - Uninferred import. Nx did not infer the import, for example a dynamic import built from a string, or a path alias that does not resolve.
- Stale edge. The graph still shows a dependency on a project the code no longer uses.
Fix the declaration or the import. Do not hand-edit the tsconfig, because the next sync will overwrite your edit.
If the graph is correct but the written references are not, the bug is in the generator. Check its path computation and its rules for which tsconfig file it writes to.
The order matters because the generator's output can only be as correct as the graph it reads. When a dependency is undeclared or misinferred, the generator still writes references that match the graph. The sync check then passes, so the drift is hidden rather than flagged.
Tooling outside Nx has a separate blind spot. Editors, and a bare tsc -b run by someone who skipped sync, see only the tsconfig files on disk. They do not know about the graph. The guarantee therefore holds only if CI rejects out-of-sync commits.
When should you avoid Nx sync generators, and what are the alternatives?
Sync generators pay off in repos with many TypeScript projects that already build with tsc -b, or plan to. There, hand-maintaining references across dozens of packages is the real cost, and the generator removes it. In a small repo with a handful of projects, the extra machinery usually costs more than it saves.
Avoid them if your team relies on tsconfig paths aliases and does not want the stricter composite model. Also avoid them if you use manual references to express ordering that has nothing to do with imports, such as building a codegen package first. The generator owns the file and will rewrite those entries.
Expect these costs:
- Merge conflicts. The root solution tsconfig changes often, so it conflicts often. Rerunning sync after a merge usually resolves the conflict.
- Stricter builds. Composite builds can surface type errors that path aliases were hiding, and cold builds get slower.
- Learning the CI check. Engineers need to understand why
nx sync:checkfailed and how to fix it locally.
| Approach | Keeps references accurate | Main drawback |
|---|---|---|
| Paths aliases only | Not applicable (no references) | No incremental tsc -b; editors type-check sources globally |
| Hand-maintained references | Only through reviewer discipline | Drift is silent until a build breaks |
| Custom script from package.json | Yes, if the script is run | You own the tooling and its CI enforcement |
| Nx sync generator | Yes, derived from the project graph | Owns the files and requires Nx |
To migrate a repo with existing references:
- Run sync once.
- Review the diff carefully, and treat every removed entry as a question to answer.
- Remove any manual edits that conflict with what the generator writes.
- Decide which targets, typically
typecheckandbuild, should declare the generator insyncGenerators.
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.
- 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.