What is a Turborepo to Nx migration, and why would you do it?
A Turborepo to Nx migration is a translation of task semantics, not a rewrite. Your packages, build scripts and package manager stay where they are. What changes is the layer that decides which tasks run, in what order, and when a cached result can be reused. The job is to express what turbo.json already says (dependencies between tasks, declared outputs, cache inputs) in Nx's terms without changing behavior.
Turborepo already caches tasks, so caching alone does not justify the move. Before starting, the team should name the specific Nx capability it needs. Nx adds four things:
- A project graph you can query and visualize. Nx builds it from package manifests and, for JavaScript and TypeScript, from source imports.
- Affected-based task selection that uses that graph to decide which projects a change touches.
- Generators for scaffolding projects and applying codebase-wide changes in a consistent way.
- Plugins that infer targets from tool configuration files, so you write fewer target definitions by hand.
The teams that benefit most are platform teams running large or fast-growing monorepos, and teams whose CI cost depends on accurate, graph-aware selection of what to build and test.
Avoid the migration in three cases:
- Caching is the only goal.
- The team cannot maintain a larger configuration surface.
- Adoption is likely to drift into generators and module boundary rules nobody asked for.
Every feature you adopt has to be kept working through upgrades and explained to new engineers. That is a recurring development cost, and you pay it even for features nobody uses.
Nx vs Turborepo: how do their task models differ?
Turborepo keeps the task graph in one file. Nx assembles it from several layers, and most migration bugs come from not knowing which layer won.
Turborepo Nx
turbo.json ──► task nx.json targetDefaults ─┐
plugin inference ───────┤
package.json scripts ───┼─► effective target
project.json targets ───┘ (more specific wins)
| Concept | Turborepo | Nx |
|---|---|---|
| Task definition | tasks in turbo.json, with optional per-package turbo.json |
targetDefaults, plus per-project targets and inferred targets |
| Upstream ordering | dependsOn: ["^build"] |
Same caret convention in dependsOn |
| Cache inputs | inputs globs, defaulting to the package's tracked files |
inputs and namedInputs, with defaults set in nx.json |
| Environment | env, globalEnv, globalDependencies |
{ "env": ... } and fileset inputs, often in a shared named input |
| Long-running tasks | persistent, cache: false |
Non-cacheable targets, continuous |
| Selection | --filter |
affected, project lists, tags |
Three defaults cause most of the problems:
- Caching. Turborepo caches a task unless you opt out. Nx caches a target only when it is marked cacheable. A straight port can leave builds uncached without any warning.
- Outputs. In Turborepo, a task with no
outputsrestores only its logs. Nx falls back to conventional directories such asdistorbuild. That can mask a missing declaration, or capture files you never meant to cache. - Environment. Turborepo's strict mode limits which environment variables a task can see. Nx hashes only the variables you declare and does not hide the rest. A variable you forget to declare can then produce stale cache hits.
Before you assume Nx wins, run the same table against your current setup. If nothing in the right-hand column solves a problem you actually have, staying on Turborepo is a legitimate outcome.
TURBOREPO (single source) NX (layers merge, later wins)
┌──────────────────┐ ┌──────────────────────────┐
│ turbo.json │ │ plugin inference │ lowest
│ tasks.build │ │ (from tool configs) │
│ dependsOn, │ └────────────┬─────────────┘
│ inputs,outputs │ ▼
└────────┬─────────┘ ┌──────────────────────────┐
▼ │ nx.json targetDefaults │
┌──────────────────┐ └────────────┬─────────────┘
│ package.json │ ▼
│ script command │ ┌──────────────────────────┐
└────────┬─────────┘ │ package.json scripts │
▼ │ + "nx" field │
┌──────────────────┐ └────────────┬─────────────┘
│ task: build │ ▼
│ cached unless │ ┌──────────────────────────┐
│ cache: false │ │ project.json targets │ highest
└──────────────────┘ └────────────┬─────────────┘
▼
┌──────────────────────────┐
│ effective target: build │
│ cached only if marked │
│ cacheable │
└──────────────────────────┘
Turborepo reads a task's configuration from turbo.json and runs the package.json script, while Nx merges plugin inference, nx.json targetDefaults, package.json and project.json into one effective target where the more specific layer wins.
How do you add Nx to an existing Turborepo workspace?
Nx does not require you to restructure the repository. Running npx nx init at the workspace root adds Nx as a dev dependency and creates an nx.json. Your existing package-manager workspace definition, directory layout and build scripts stay where they are. Nx discovers projects through the same workspace globs your package manager already uses. This lets the two tools coexist on one branch while you compare their behavior.
Each script in a project's package.json becomes an Nx target with the same name. nx run api:build executes the build script in the api package, just as turbo run build --filter=api would. Cross-project ordering and caching are not inferred from the script itself. You declare them in nx.json, usually through targetDefaults, which section 4 covers.
Inspect what Nx actually resolved
Before you trust any target, look at what Nx resolved for it:
nx show projectslists every project Nx detected. Compare it against your workspace packages to catch missing or unexpected entries.nx show project <name>prints the merged configuration for one project: its targets, inputs, outputs and dependencies.nx graphopens the project graph, so you can confirm that dependency edges match what Turborepo'sdependsOn: ["^build"]implied.
Watch inferred targets
Nx plugins can read tool configuration files, such as a bundler or test-runner config, and create targets automatically. This cuts boilerplate, but it also means a target can exist without appearing in any package.json or project.json. An inferred target may carry its own inputs, outputs or cache settings that differ from your Turborepo pipeline. During migration, either add plugins one at a time or leave them out. Then review each inferred target with nx show project before you rely on its cache.
# Run from the existing Turborepo workspace root.
# No directories move and no package.json scripts change.
# 1. Add Nx alongside the current package-manager workspace.
# This installs Nx as a dev dependency and creates nx.json.
npx nx init
# 2. Confirm Nx found the same packages your workspace globs define.
# Compare this list against your packages to catch missing or extra entries.
npx nx show projects
# 3. Inspect the merged configuration for one project.
# Check each target's source: a package.json script or a plugin.
# Also review inputs, outputs and dependsOn before you trust the cache.
npx nx show project api
# 4. Run a package.json script as an Nx target.
# Nx runs the same "build" script that this Turborepo command runs:
# npx turbo run build --filter=api
npx nx run api:build
# 5. Open the project graph.
# Check that dependency edges match what dependsOn: ["^build"] implied in turbo.json.
npx nx graph
# 6. If you add a plugin, add one at a time, then re-inspect.
# Inferred targets can appear without any package.json or project.json entry.
# They can also carry their own inputs, outputs and cache settings.
npx nx show project api
Adds Nx to an existing Turborepo workspace in place, then uses the show and graph commands to check which projects, targets and dependency edges Nx resolved before you rely on them.
How do you map turbo.json tasks to Nx targets?
Once inferred targets are under control, translate the pipeline itself. In Turborepo, task configuration lives under tasks in turbo.json. In Nx, the equivalent shared settings go in targetDefaults in nx.json. Each package's package.json scripts stay the commands that actually run.
| Concern | turbo.json | nx.json |
|---|---|---|
| Run dependencies' build first | "dependsOn": ["^build"] |
"dependsOn": ["^build"] |
| Same-package prerequisite | "dependsOn": ["build"] |
"dependsOn": ["build"] |
| Source inputs | inputs globs |
namedInputs (e.g. production) referenced from inputs |
| Artifacts | outputs |
outputs with {projectRoot} tokens |
| Env vars | env, globalEnv |
{ "env": "NAME" } in inputs |
| Root config files | globalDependencies |
{workspaceRoot}/… in inputs |
| Dev/watch | "cache": false, "persistent": true |
"cache": false, plus continuous where your Nx version supports it |
Define a production named input that starts from default and excludes test files with negated globs. Point build and typecheck at ^production so editing a spec file doesn't invalidate downstream builds. test still uses default.
Declare outputs for every cacheable target. Nx restores only the files it recorded. If build writes dist/ but outputs is missing or points at the wrong path, the next run reports a cache hit, skips the command and restores nothing. Dependents then fail on missing artifacts. Turborepo has the same failure mode, but path conventions differ, so re-check every output path.
Add env vars such as NODE_ENV and root files such as tsconfig.base.json to inputs. This makes configuration changes produce a new hash. Without them, Nx can serve stale results after those files or variables change.
Finally, rewrite your scripts rather than renaming them. turbo run build --filter=... does not map one-to-one to nx run-many -t build -p … or nx affected, because the two tools select graph dependents and dependencies differently. --output-logs modes also differ from Nx's --output-style options.
{
"namedInputs": {
"sharedGlobals": [
"{workspaceRoot}/tsconfig.base.json",
{ "env": "NODE_ENV" }
],
"default": ["{projectRoot}/**/*", "sharedGlobals"],
"production": [
"default",
"!{projectRoot}/**/*.spec.ts",
"!{projectRoot}/**/*.test.ts",
"!{projectRoot}/jest.config.ts"
]
},
"targetDefaults": {
"build": {
"dependsOn": ["^build"],
"inputs": ["production", "^production"],
"outputs": ["{projectRoot}/dist"],
"cache": true
},
"typecheck": {
"dependsOn": ["^build"],
"inputs": ["production", "^production"],
"cache": true
},
"test": {
"dependsOn": ["build"],
"inputs": ["default", "^production"],
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
"cache": true
},
"lint": {
"inputs": ["default", "{workspaceRoot}/eslint.config.js"],
"cache": true
},
"dev": { "dependsOn": ["^build"], "cache": false, "continuous": true }
}
}
An nx.json mirroring a turbo.json pipeline: ^build and same-package build in dependsOn, a production input that excludes tests, explicit outputs, NODE_ENV and tsconfig.base.json as hash inputs, and a non-cached continuous dev target.
How do you verify Nx cache correctness before cutover?
Before CI depends on the new cache, prove that it is correct. A cache that restores stale output passes every check and still ships the wrong build to production. Finding this at cutover takes an afternoon. Finding it after release can take days.
A repeatable procedure
- Warm run, then repeat. Run
nx run-many -t buildtwice with no changes. Every task on the second run should be a cache hit. If one misses, a nondeterministic input such as a timestamp, an absolute path or a generated file is leaking into the hash. - Restore from a clean slate. Delete the build output directories and run the build again. Compare the restored artifacts against a run with the cache bypassed, using checksums or a recursive diff. If files are missing, the
outputsfor that task are incomplete. - Invalidate deliberately. Make one change at a time and record which tasks rerun:
- Edit a source file in a leaf library. That library and its dependents should miss, and nothing else should.
- Edit a root config file, such as the shared TypeScript config or the lockfile.
- Change an environment variable that a build reads.
Over-caching and under-caching
Read every result against what you expected:
- An unexpected hit means a missing input. This is over-caching, and it is the dangerous case because it produces stale artifacts.
- An unexpected miss means an over-broad input. This is under-caching. It is safe, but it wastes CI time.
A literal translation of turbo.json can produce either problem. The two tools differ in what they hash implicitly, including global files, lockfile handling and environment variables. As a result, a mapping that looks identical can still drop an input or add one.
#!/usr/bin/env bash
# Cache verification run before cutover. Assumes outputs land in dist/.
set -euo pipefail
snapshot() { # checksum every output file in a stable order
find dist -type f -print0 | sort -z | xargs -0 sha256sum > "$1"
}
# 1. Warm run, then repeat: the second summary should report every task from cache.
npx nx run-many -t build
npx nx run-many -t build | tee run2.log
grep -i 'cache' run2.log || true # any task that ran here has a leaky input
# 2. Restore from a clean slate, then compare against an uncached build.
rm -rf dist
npx nx run-many -t build # restores from cache
snapshot restored.sha
rm -rf dist
npx nx run-many -t build --skip-nx-cache
snapshot fresh.sha
diff restored.sha fresh.sha && echo 'restored artifacts match'
# 3. Invalidate deliberately, one change at a time; note which tasks rerun.
echo '// cache probe' >> libs/shared-utils/src/index.ts
npx nx run-many -t build # expect: shared-utils + dependents miss
git checkout -- libs/shared-utils/src/index.ts
echo '' >> tsconfig.base.json
npx nx run-many -t build # expect: projects that use it miss
git checkout -- tsconfig.base.json
API_URL= npx nx run-many -t build
# expect: only tasks that read API_URL miss.
# Unexpected hit = missing input (stale risk). Unexpected miss = over-broad input.
A bash script that checks Nx cache hits on repeat runs, compares restored outputs with an uncached build, and probes invalidation from a source file, a root config file and an env var.
How should you migrate CI from Turborepo to Nx?
Run both pipelines, but trust only one
Add an Nx job that runs nx affected alongside the existing Turborepo job, and keep Turborepo as the required check. For each pull request, compare which tasks each tool ran and whether build outputs match. Do this across several PRs that touch different areas: a leaf package, a shared library and a root config file. Switch the required check only after the task sets agree.
Get the git inputs right
Affected calculation diffs the PR head against a base commit. A shallow clone may not contain that base, so fetch enough history to include the merge base. Pass the base explicitly with --base and --head, using the target branch rather than the previous commit. A wrong base ref, an undeclared runtime-only import or a generated file that Nx does not know about will each shrink the project graph. The result is a green job that skipped tasks it should have run, with no warning.
Bound the dual-run period
Running both pipelines doubles CI spend and creates two sources of truth, which leads engineers to ignore whichever one disagrees. Set a fixed end date. Illustrative estimate, assumed inputs: 400 CI minutes per working day, a three-week window (15 days) and $0.01 per minute. That adds 6,000 minutes, about $60, plus the time spent reviewing mismatches.
Plan remote caching separately
Nx cannot reuse Turborepo's remote cache artifacts. Expect cold caches and slower CI for the first days after cutover. Decide where the Nx remote cache is hosted and who can write to it before you switch.
What does the migration cost, and when does it save engineering time?
The cost side starts with that cold cache, but it doesn't end there. Nx spreads configuration across nx.json, project.json files and targets inferred by plugins. When a task misbehaves, you first have to work out which of those layers defined it, a question Turborepo's single turbo.json never raised. Running both tools in CI during validation also doubles pipeline spend for that period. The slowest cost is human: package scripts, editor tasks, onboarding docs and muscle memory like turbo run build --filter all have to change.
The time savings show up as the repository grows. Affected-based selection skips projects that a change cannot reach, so pull requests stop paying for unrelated work. Graph tooling answers "why does this rebuild?" without anyone reading lockfiles. Generators keep new projects consistent, which avoids config drift between projects.
| Team situation | Recommendation | Why |
|---|---|---|
| Uses Turborepo only for caching, few packages | Stay on Turborepo | The cache already delivers the value, and Nx adds config surface without new benefit |
| Growing monorepo, frequent new projects | Migrate | Generators and graph tooling get more valuable as projects multiply |
| Heavy CI cost from running everything | Migrate | Affected selection reduces CI work on every pull request |
| Small team, near a release | Defer | Dual-run CI and retraining compete with delivery work |
Run cleanup only after Nx is authoritative in CI:
- Delete
turbo.json. - Remove the
turbodependency and update the lockfile. - Strip Turborepo commands and cache settings from CI and scripts.
- Document the new target names, affected usage and cache-write rules for the team.
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 turborepo to nx migration, 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.