What does a monorepo migration to Nx actually replace?

A JavaScript monorepo tool does three separate jobs, and they are easy to blur together:

  1. Workspace and package linking. This determines which directories are packages, how they depend on each other, and how local packages get symlinked into node_modules. Your package manager's workspaces feature handles this, not Lerna or Turborepo.
  2. Task orchestration and caching. This runs build, test, and lint across packages in dependency order, in parallel where possible. It also skips work whose inputs haven't changed. This is Turborepo's core job, and it is what lerna run provides.
  3. Versioning and publishing. This bumps versions, writes changelogs, and pushes packages to a registry. Lerna is known for this. Turborepo leaves it to separate tooling.

Moving to Nx mostly replaces layer 2. Nx reads the same workspace definitions your package manager already uses, so your lockfile, install command, and dependency graph stay the same. Publishing can keep running on whatever tool you use today. Nx has its own release tooling, but you can evaluate it later as a separate change.

+-------------------------------------------+
| 3. Versioning & publishing                |  STAYS (optional later move)
|    current release tooling                |
+-------------------------------------------+
| 2. Task orchestration & caching           |  CHANGES
|    turbo run / lerna run  -->  nx run,    |
|    nx run-many, nx affected               |
+-------------------------------------------+
| 1. Workspaces & package linking           |  STAYS
|    package manager workspaces, lockfile   |
+-------------------------------------------+

Separating the layers keeps the migration small. Each layer can change and be verified on its own, and a regression in one layer won't be mistaken for a regression in another.

  BEFORE (Turborepo / Lerna)          AFTER (Nx)
+----------------------------+        +----------------------------+
| 3. Versioning & publishing |        | 3. Versioning & publishing |
|    current release tool    |  --->  |    same tool for now       |  STAYS
|    (lerna publish, etc.)   |        |    (nx release: later)     |
+----------------------------+        +----------------------------+
| 2. Orchestration & caching |        | 2. Orchestration & caching |
|    turbo run / lerna run   |  ===>  |    nx run-many, affected   |  CHANGES
+----------------------------+        +----------------------------+
| 1. Workspaces & linking    |        | 1. Workspaces & linking    |
|    pm workspaces+lockfile  |  --->  |    pm workspaces+lockfile  |  STAYS
+----------------------------+        +----------------------------+

  Layer 2 in Nx reads its dependency graph from layer 1,
  so the install command and lockfile do not change.

  Legend:  --->  carried over unchanged    ===>  replaced

The three monorepo layers before and after the move: Nx replaces task orchestration and caching, workspaces stay with the package manager, and publishing stays on its current tool until you choose to change it.

Who should migrate, and when is staying put reasonable?

Teams adopt Nx for three practical reasons. The project graph is derived from real package dependencies and imports. nx affected uses that graph to run only the projects a change can reach. Caching skips tasks whose inputs haven't changed. Nx also leaves room to adopt generators, plugins, and module boundary rules later, without committing to them now. The benefit grows with package count, build time, and CI spend. A repo with dozens of packages and 30-minute pipelines has a lot to recover. A repo with four packages and two-minute builds has almost nothing.

Option Reasonable when Main cost
Stay on Turborepo Caching and pipelines already keep CI fast Affected detection is less graph-driven
Stay on Lerna Versioning and publishing are the real need, and builds are cheap Little task-level optimization
Move to Nx Many packages, slow builds, expensive CI New config surface, learning curve, two tools during the transition

Illustrative estimate (assumed inputs, not measured): 8 engineers each wait on CI 4 times a day. Affected runs cut the average wait from 15 to 9 minutes. That saves about 3 hours a day across the team. If the migration takes 80 engineer-hours, it breaks even in roughly a month. Waiting time is only partly lost time, so treat this as an upper bound.

Account for the visibility cost too. Turborepo keeps its pipeline in one file. Nx spreads configuration across nx.json, per-project project.json files, and targets that plugins infer from your tooling. Engineers will spend time learning where a given setting actually comes from.

When should you use Nx?

Use Nx when the cost of running tasks, not the cost of publishing packages, is what slows the team down. Concrete signals:

  • CI runs work that a change cannot affect. If a one-line change in a leaf package still triggers builds and tests across the whole repo, graph-based nx affected runs address that directly.
  • Your current runner's affected detection does not match how packages really depend on each other. Nx builds its project graph from package.json dependencies and, with plugins, from source imports, so it can catch edges that a path-based filter misses.
  • The same tasks are rebuilt on CI and on every developer machine. A shared remote cache lets one run's output be reused elsewhere, as long as inputs are declared correctly.
  • You expect to need structure later. If you anticipate wanting enforced dependency directions, consistent package scaffolding, or graph-aware releases, Nx lets you add those one at a time on top of the task runner.
  • You are already on a recent Lerna. Because lerna run already delegates to Nx, configuring Nx directly is a small step with little new risk.

Do not migrate when builds are already fast, the package count is small and stable, or the team cannot spare time for a parallel-runner period. A migration done under release pressure tends to skip the cache-parity checks described below, and those checks are where most of the risk lives.

What are the alternatives to Nx?

Nx is one way to solve layer 2. The realistic alternatives:

  • Stay on Turborepo. If its pipeline and caching already keep CI fast enough, the main gain from Nx is graph-driven affected detection and the optional extras. That may not justify a new configuration model.
  • Stay on Lerna. Reasonable when the real need is versioning and publishing and builds are cheap. Since recent Lerna uses Nx for task running, you get some of the same caching without changing tools.
  • Package-manager workspace scripts only. npm run build --workspaces or pnpm -r run build run a script across packages, and pnpm's recursive run orders packages by their dependencies. There is no task caching and no affected detection, but there is also no extra tool to learn. This fits small repos where a full build is already quick.
  • Hand-written CI path filters. Some teams trigger jobs based on which directories changed. It works for a few loosely coupled packages, but the filters do not know about dependency edges, so a change to a shared library can skip the packages that consume it. It gets harder to maintain as the graph grows.
  • Splitting the monorepo. If packages rarely change together, separate repositories remove the orchestration problem entirely, at the cost of cross-repo changes and version coordination.

The comparison table in the previous section covers the tradeoffs for the three tools this article focuses on. Whichever you pick, the workspace layer (layer 1) stays with the package manager.

How can Nx save engineering time?

Time savings come from a few specific mechanisms. Each one only pays off if its prerequisite is in place:

  • Not running unaffected tasks. nx affected skips projects that a change cannot reach. This requires the correct --base and --head refs and enough git history in CI, as covered below.
  • Not re-running unchanged tasks. Local caching means re-running build or test after switching branches, or after a no-op rebase, restores outputs instead of recomputing them. This requires correct inputs and outputs. A wrong outputs path gives a cache hit that restores nothing.
  • Sharing work between machines. With remote caching, a task CI already ran can be restored on a developer machine with matching inputs, and the reverse if you allow developer writes. This requires aligned lockfiles, tool versions and declared environment variables.
  • Less time reasoning about the dependency graph. nx graph shows which projects depend on which. That shortens the "what will this change break?" investigation during reviews and incident triage.
  • Less repeated setup, later. Generators and plugin-inferred targets reduce the per-package boilerplate when new packages are created. These are optional and carry their own maintenance cost.

The illustrative estimate earlier shows how to reason about the payoff. Multiply the assumed number of CI waits by the assumed minutes saved per wait, then compare that against the migration effort. Do the same calculation with your own inputs before committing. If your builds are short or your package graph is shallow, the result may not justify the change. The safeguards in the rest of this guide, such as cache parity checks, one target type at a time, and keeping the old config as a fallback, exist so that the time saved is not spent later debugging a stale artifact.

How does nx init work in an existing repo?

Run npx nx init from the repository root on a clean branch. The command inspects what is already there: your package manager, workspace globs, and whether Lerna or Turborepo configuration exists. It then installs Nx as a dev dependency and writes an nx.json. It does not move packages or rewrite your package.json scripts. Nx treats those existing scripts as targets, so nx run api:build invokes the same build script your team already runs. Because nothing in the layout changes, you can roll back by reverting a single commit.

The prompts vary between Nx versions, but expect questions about which scripts are cacheable and where each one writes its output. Your answers become targetDefaults in nx.json. Review that file before you commit it:

  • Cacheable scripts. Only deterministic tasks should be cached, such as build, lint, typecheck and unit tests. Anything that deploys, publishes, seeds a database or depends on network state must stay uncached. Otherwise a cache hit will silently skip a side effect.
  • Declared outputs. Confirm that the output paths match what each tool actually writes, for example dist, build or a coverage directory. If a path is wrong, Nx will report a cache hit and restore nothing.
  • dependsOn. Check that build ordering, such as building dependencies first, reflects how your packages actually consume each other.
  • Ignore rules. Confirm the local cache directory was added to .gitignore.

Commit the generated config by itself, separate from any script or CI changes. A small diff lets reviewers question each caching decision while the reasoning is still fresh.

git switch -c chore/nx-init

npx nx init

git status --short
git diff -- package.json .gitignore

cat nx.json

npx nx show project api

grep -n 'nx' .gitignore

npx nx run api:build
rm -rf packages/api/dist
npx nx run api:build
ls packages/api/dist   # empty or missing means the declared outputs are wrong

git add nx.json package.json package-lock.json .gitignore
git commit -m "chore: add nx via nx init (no layout or script changes)"

A shell session that runs nx init on a clean branch, reviews the generated nx.json and cache settings, checks that a cache hit restores the declared outputs, and commits the config as a separate change.

How do you move from Lerna or Turborepo to Nx configuration?

Lerna

Recent Lerna releases already run tasks through Nx, so lerna run is often Nx under the hood. The migration is mostly configuration: move caching and task-dependency settings into nx.json and switch scripts from lerna run to nx run-many. Leave lerna version and lerna publish in place for now.

Moving versioning to nx release is a reasonable goal, but make it a separate change later. It changes how versions are bumped and how changelogs are generated. If you combine it with the task-runner switch and a release goes wrong, you won't know which change caused it.

Turborepo

Each task entry in turbo.json becomes a key under targetDefaults in nx.json. Most fields translate directly. The main difference is paths. Turborepo resolves output globs relative to each package, while Nx expects explicit tokens such as {projectRoot}. If you copy dist/** without the token, Nx caches the wrong location, or nothing at all.

Concern turbo.json (build task) nx.json targetDefaults.build
Build dependencies first "dependsOn": ["^build"] "dependsOn": ["^build"] (same meaning)
Outputs "outputs": ["dist/**"] "outputs": ["{projectRoot}/dist"]
Inputs "inputs": ["src/**"] "inputs": ["{projectRoot}/src/**/*"]
Environment variables "env": ["API_URL"] { "env": "API_URL" } entry in inputs
Caching cached by default "cache": true

Translate the inputs literally first, even if Nx's named inputs look cleaner. A one-to-one mapping keeps the cache behavior the same as before, so you can verify it before you refactor.

cat > turbo.json <<'EOF'
{
  "tasks": {
    "build": {
      "dependsOn": ["^build"],
      "inputs": ["src/**"],
      "outputs": ["dist/**"],
      "env": ["API_URL"]
    }
  }
}
EOF

cat > nx.json <<'EOF'
{
  "$schema": "./node_modules/nx/schemas/nx-schema.json",
  "targetDefaults": {
    "build": {
      "dependsOn": ["^build"],
      "inputs": ["{projectRoot}/src/**/*", { "env": "API_URL" }],
      "outputs": ["{projectRoot}/dist"],
      "cache": true
    }
  }
}
EOF

npx nx run-many -t build

The same build task in turbo.json and in nx.json targetDefaults, with dependsOn, inputs, outputs and the environment variable translated one-to-one.

How do you prevent stale cache hits after migrating?

The two tools do not fingerprint a task the same way. Turborepo hashes environment variables listed in env and globalEnv, plus files in globalDependencies, and each package's resolved lockfile entries. Nx hashes whatever its inputs and namedInputs declare. Anything you don't declare is ignored. Older Lerna setups often had no caching, so their implicit assumptions were never written down. A missed input does not cause an error. Nx reports a cache hit and restores an artifact built with the wrong API_URL or an outdated root tsconfig.base.json, and you only find out when that artifact reaches a running environment.

Re-declare what Turborepo hashed implicitly

  • Environment variables: add { "env": "VAR_NAME" } entries to the target's inputs. Put variables that affect every task into a shared named input such as sharedGlobals.
  • Root-level files: reference them with {workspaceRoot}/... paths in sharedGlobals, so a change to a root config invalidates every task that depends on it.
  • Lockfile influence: check that the targets hash external dependencies. If a build depends on the whole lockfile, list the lockfile explicitly.
  • production versus default: leave tests, specs and lint configs out of production, and point build at production. Editing a test should not invalidate a build.

Verify parity before switching CI

  1. Check out a single commit.
  2. Run the old runner, then run Nx with a cleared cache (nx reset).
  3. Compare the task graph in nx graph with the dependency order you expect.
  4. Diff the two output directories. Any difference means an input or a task dependency is missing.
  5. Edit one source file and run again. Only that project and its dependents should miss the cache.
  6. Change one environment variable and run again. Only the tasks that declare that variable should rerun.
// nx.json: re-declare what Turborepo's globalEnv, env and globalDependencies covered
{
  "namedInputs": {
    // Inputs that should invalidate every task, like Turborepo's global keys
    "sharedGlobals": [
      "{workspaceRoot}/tsconfig.base.json",
      { "env": "NODE_ENV" }
    ],
    // Every file in the project plus the shared globals
    "default": ["{projectRoot}/**/*", "sharedGlobals"],
    // Exclude test and lint files so editing them does not invalidate builds
    "production": [
      "default",
      "!{projectRoot}/**/*.spec.ts",
      "!{projectRoot}/jest.config.ts",
      "!{projectRoot}/eslint.config.mjs"
    ]
  },
  "targetDefaults": {
    "build": {
      "cache": true,
      "dependsOn": ["^build"],
      "inputs": [
        "production",
        "^production",
        // Baked into the bundle at build time, so it must be part of the hash
        { "env": "API_URL" },
        // Only needed if the build reads the whole lockfile
        "{workspaceRoot}/pnpm-lock.yaml"
      ],
      "outputs": ["{projectRoot}/dist"]
    },
    "test": {
      "cache": true,
      // Tests hash their own spec files plus dependencies' production sources
      "inputs": ["default", "^production"]
    }
  }
}

An nx.json that declares the environment variables, root files and lockfile Turborepo used to hash, and uses a production named input to keep test and lint files out of build hashes.

How do you switch CI to nx affected and set up remote caching?

Replace turbo run build --filter=...[origin/main] or lerna run build --since with nx affected -t build. Nx computes the affected set by diffing two git refs, --base and --head, so the refs you pass decide what runs.

Build type Base Head Why
Pull request Merge base with the target branch PR head commit Tests only what the PR changes
Main branch Last commit that passed CI on main Current commit Catches everything merged since the last green build

Using HEAD~1 as the base on main is fragile. If a build fails and the next merge passes, the work from the failed commit is never verified. Track the last successful SHA and use that.

Shallow clones are the most common breakage. If the checkout lacks the base commit, the diff cannot be computed. Depending on how your scripts handle the error, you get one of two results. Falling back to "run everything" is safe but slow, and it hides the misconfiguration. Silently treating the diff as empty skips affected projects, which is unsafe. Fetch enough history to include the base, and fail the job if the base ref cannot be resolved.

For remote caching, CI and developers must share the same task inputs: lockfile, tool versions, and the declared environment variables. Otherwise the hashes diverge and nobody gets cache hits. Treat cache artifacts as trusted build inputs. A restored entry is used instead of running the build. A poisoned entry, whether from a compromised laptop or a nondeterministic task, spreads to every consumer that matches the hash. Give CI write access to the cache, and make developer machines read-only.

What is a safe rollout plan, and what can you adopt later?

Keep turbo.json or lerna.json in the repo for one or two release cycles after Nx starts running tasks. If a cache problem or a missing dependency edge appears during a release, you can switch CI back to the old runner in a single commit instead of debugging under deadline pressure.

Move one target type at a time: build first, then test, then lint. Build goes first because test and lint usually depend on its outputs, so a wrong dependsOn or outputs setting shows up there before it can corrupt later steps. Let each target type run through several merges before you move the next one.

Running two task runners side by side has a cost. Every new package, renamed script or changed output directory has to be updated in both configs. If the two drift apart, the old tool stops being a valid fallback, and it can also hide problems. For example, a green Turborepo run may be passing only because it lacks an input that Nx correctly treats as part of the hash. Delete the old config once CI has been stable on Nx across a full release, not as soon as the first run passes.

After that, treat each further adoption as a separate decision:

Adoption Benefit Cost
Project tags + module-boundary lint rule Enforces allowed dependency directions Tagging every project; lint failures on existing violations
Plugin-inferred targets Less config to maintain Behaviour changes with plugin updates; harder to see what runs
Generators Consistent new packages Templates need maintenance as conventions change
nx release for publishing Versioning and changelogs tied to the project graph Replaces your existing publish pipeline and its edge cases

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 migrate turborepo to nx, 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.