What does migrating to Nx actually change, and who should do it?

Migrating a Lerna or Turborepo workspace to Nx is not a rewrite. Your package manager workspaces, package.json files, directory layout and existing scripts stay where they are. Nx sits on top as the task runner: it reads the workspace, builds a project graph from declared dependencies, and runs your existing scripts as targets. You can adopt it one package at a time and keep the old tool working until you are confident.

Why teams move

The main reason is the project graph. Nx knows which services depend on which shared libraries, so nx affected can run builds and tests only for projects touched by a change and their dependents. The second reason is finer control over cache inputs. Named inputs let you state that a service's test cache depends on its source, a shared config file and certain environment variables, but not on its README. In a backend repo, where a stale cache can let a broken migration or contract change through, that precision matters.

Who benefits, and who should skip it

Backend and platform teams with many interdependent services and shared libraries get the most from it, because their test matrix grows with every new package. If you only want cached script execution across a handful of packages, the extra concepts may not pay off. Nx brings targets, executors, plugins, generators and named inputs, and each one needs configuration, documentation and onboarding time.

Plan for that cost up front. Expect a few days of engineering time to audit cache inputs, verify the graph and update CI. Expect some friction while developers learn which commands replaced the old ones.

How does Nx work?

Nx does three things each time you run a target: it builds a project graph, computes a hash for each task, and schedules the tasks.

Project graph. Nx discovers projects from your package manager workspaces, package.json files and any project.json files. It adds dependency edges from package manifests and, for JavaScript and TypeScript, from analysing import statements in source files. Plugins can add projects, targets and edges. You can add edges by hand with implicitDependencies. To avoid recomputing this graph on every command, Nx can run a background daemon process that keeps the graph current as files change.

Task graph and hashing. When you run nx run-many -t test or nx affected -t test, Nx expands the requested targets into a task graph. It uses dependsOn to decide what must run first, for example ^build meaning "build every dependency first". For each cacheable task it computes a hash from the declared inputs: matching source files, named inputs, environment variables listed as { "env": "..." } entries, and, through ^ inputs, the inputs of dependency projects. It also includes the command being run.

Cache lookup and execution. If a task's hash matches an earlier run, in the local cache or a configured remote cache, Nx skips execution. It replays the stored terminal output and restores the files listed in outputs. If there is no match, Nx runs the underlying command, which is usually your existing script, then stores its output and declared artifacts under that hash. Tasks without unmet dependencies run in parallel.

Affected detection. nx affected adds one step before all of this. It diffs the base and head commits, maps changed files to the projects that own them, then walks the graph to include every project that depends on those projects. Only those projects' targets enter the task graph.

The whole model depends on declared inputs, outputs and edges being complete. Nx never checks whether a script reads a file you did not declare. Most of the work in a migration goes into making those declarations accurate.

When should you avoid migrating to Nx?

Skip or postpone the migration in these situations:

  • The workspace is small and stable. With only a few packages and few dependency edges, affected detection rarely excludes much. Plain cached script execution, which Turborepo already provides, captures most of the value. The new concepts cost more than they save.
  • Turborepo already meets your needs. If CI time is acceptable, cache correctness is not causing incidents, and nobody is asking for finer-grained inputs or graph tooling, a migration adds risk without fixing a problem.
  • Most of the repo is not JavaScript or TypeScript. Nx infers import-based edges for JS/TS. For Go, Python, Rust or JVM services you will be writing nx:run-commands targets, implicitDependencies and file inputs by hand, or relying on community plugins of varying maturity. If that describes most of the repo, a build tool native to those languages may fit better.
  • Nobody can own the configuration. Someone has to maintain nx.json, review input declarations when services start reading new config, and handle Nx upgrades. Without an owner, inputs drift, and the cache starts producing wrong hits.
  • Other large changes are in flight. If you are also changing package managers, CI providers or release tooling, wait. Changing several of these at once makes regressions hard to attribute, for the same reason this guide keeps Lerna's release commands separate.
  • Key tasks depend mostly on side effects. If most targets are migrations, deploys, or integration tests against shared environments, they must have cache: false. Caching and affected detection then have little to work on.

If one of these applies, a reasonable middle path is to keep the current tool and invest in its configuration: tighten Turborepo inputs and env, or add the missing dependency declarations. Revisit Nx when the repo grows.

How do you record a baseline before touching anything?

Before running any migration command, capture what the current setup actually does. Without that record, every later discrepancy turns into a debate about whether something was already broken. With it, you can compare each change against a known state and spend your time on real differences.

Collect four things from your main CI pipeline:

  • Task inventory and order. List every task that runs, per project, and what it waits on. Turborepo's dry-run output or Lerna's run logs give you this. Note any tasks that CI shell scripts run outside the task runner, because the migration will not see them.
  • Inputs and outputs. For each cached task, note which files, environment variables and lockfile changes invalidate it, and which directories it writes, such as dist, coverage reports and generated API clients.
  • Run time. Record wall-clock time for a cold run with no cache and a warm run on an unchanged commit. Repeat each run several times so normal variance does not look like a regression.
  • Cache behavior and results. Record hit and miss counts, test counts and checksums of build artifacts.
Metric Baseline (Turborepo) After Nx Parity rule
Tasks executed 42 42 Identical set
Tests run 1,318 1,318 Identical count
Cold CI time 14 min 13 min Within ±10%
Warm cache hits 40/42 40/42 Same misses

Illustrative estimate. All figures are assumed inputs, not measurements.

If the task set and test count match and the artifacts hash the same, a faster run is a real improvement. If a test count drops, a misconfigured target is probably skipping work, even when the run looks faster.

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

TASKS="build test lint"   # the same tasks your CI pipeline runs
OUT=baseline/$(git rev-parse --short HEAD)
mkdir -p "$OUT"

npx turbo run $TASKS --dry-run=json > "$OUT/dry-run.json"
jq -r '.tasks[].taskId' "$OUT/dry-run.json" | sort > "$OUT/task-ids.txt"

for i in 1 2 3; do
  start=$(date +%s)
  npx turbo run $TASKS --force > "$OUT/cold-$i.log" 2>&1   # --force skips cache reads
  echo "cold,$i,$(( $(date +%s) - start ))" >> "$OUT/timings.csv"

  start=$(date +%s)
  npx turbo run $TASKS > "$OUT/warm-$i.log" 2>&1           # same commit, so cache should hit
  echo "warm,$i,$(( $(date +%s) - start ))" >> "$OUT/timings.csv"
done

grep -hE 'Tasks:|Cached:' "$OUT"/warm-*.log > "$OUT/cache-summary.txt"

find apps packages -path '*/dist/*' -type f -print0 \
  | sort -z | xargs -0 sha256sum > "$OUT/artifacts.sha256"

echo "Baseline written to $OUT"

A shell script that records the Turborepo task graph, repeated cold and warm timings, cache hit summaries and build artifact checksums into a per-commit directory, so later Nx runs can be compared against the same files.

What does nx init do in an existing Lerna or Turborepo workspace?

nx init is an adoption command, not a rewrite. In an existing workspace it adds Nx as a dev dependency, creates an nx.json at the root, and inspects what is already there. When it finds Lerna or Turborepo configuration, it can carry over settings such as which scripts are cacheable and how tasks depend on each other. Depending on the version and the prompts you answer, it may also touch .gitignore, root scripts, or existing config files.

Because that behavior varies, run it on a dedicated branch and review the diff file by file. Don't rely on the summary the command prints. A changed root script or a missing outputs entry is easy to overlook in a summary and expensive to discover later as a stale cache hit. Compare the result against the baseline you recorded: every target you captured should still exist and resolve to the same underlying command.

Lerna workspaces

Recent Lerna versions already delegate task running to Nx. That means lerna run can keep working after nx init. Teams can move scripts and CI to nx run-many and nx affected one pipeline at a time, without a cutover day.

Versioning and publishing are a separate decision. lerna version and lerna publish can stay as they are while task running moves over. If you migrate task execution and release tooling together and a release goes wrong, you can't tell which change caused it. Settle the task runner first, then evaluate release tooling on its own.

git checkout -b chore/nx-init
npx nx@latest init

git status --short

for f in $(git diff --name-only); do
  echo "=== $f ==="
  git diff -- "$f"
done
cat nx.json

npx nx show projects

npx lerna run build

npx nx run-many -t build
npx nx affected -t test --base=origin/main --head=HEAD

Running nx init on a dedicated branch, reviewing the diff file by file, and confirming that lerna run still works alongside nx run-many and nx affected while release commands stay on Lerna.

How do turbo.json pipeline settings map to nx.json?

Turborepo and Nx describe tasks in similar terms, so most of the translation is mechanical. Do it by hand, one task at a time, so you understand each line in the resulting nx.json. Task-wide settings belong under targetDefaults, keyed by target name. Reserve project-level overrides for real exceptions.

turbo.json nx.json Notes
dependsOn: ["^build"] dependsOn: ["^build"] ^ means "this target in dependencies first" in both tools
dependsOn: ["lint"] dependsOn: ["lint"] Same-project dependency, no prefix
outputs outputs Nx paths use tokens such as {projectRoot}/dist
inputs inputs Nx can reference reusable namedInputs
env, globalEnv { "env": "VAR" } entries in inputs Each variable becomes part of the cache key
globalDependencies A shared named input, often sharedGlobals Then included in default
cache: false cache: false Set per target. Opt targets in explicitly

The example below shows a build and test pipeline before and after.

Backend workspaces need extra care with environment variables. Turborepo users often list DATABASE_URL or a feature-flag variable in env so that a change invalidates the cache. Leave one of these out of Nx inputs and Nx will restore a build or test result produced under different configuration. Nothing will warn you.

Start with broad inputs: the whole project root, root-level config files such as lockfiles and shared tsconfig bases, and every environment variable the old config listed. Narrow these later, once you have watched real cache behaviour. The two failure modes are not equal. A cache miss costs minutes. A wrong cache hit ships a stale artifact or reports a passing test that never ran.

// BEFORE: turbo.json
{
  "globalDependencies": ["tsconfig.base.json"],
  "globalEnv": ["NODE_ENV"],
  "tasks": {
    "build": { "dependsOn": ["^build"], "outputs": ["dist/**"], "env": ["DATABASE_URL"] },
    "test": { "dependsOn": ["build"], "inputs": ["src/**", "test/**"], "env": ["DATABASE_URL", "FEATURE_FLAGS"] }
  }
}

// AFTER: nx.json
{
  "namedInputs": {
    // globalDependencies + globalEnv become one shared named input.
    // The lockfile is included deliberately, to be conservative at first.
    "sharedGlobals": ["{workspaceRoot}/tsconfig.base.json", "{workspaceRoot}/package-lock.json", { "env": "NODE_ENV" }],
    // Broad by design: every file in the project, plus the shared globals.
    "default": ["{projectRoot}/**/*", "sharedGlobals"]
  },
  "targetDefaults": {
    "build": {
      "dependsOn": ["^build"],
      // ^default also hashes the inputs of dependency projects.
      "inputs": ["default", "^default", { "env": "DATABASE_URL" }],
      "outputs": ["{projectRoot}/dist"],
      "cache": true
    },
    "test": {
      "dependsOn": ["build"],
      // Wider than the old src/** + test/** globs. Narrow these later, after watching cache hits.
      // Every env var from the old config stays here. Dropping one allows stale cache hits.
      "inputs": ["default", "^default", { "env": "DATABASE_URL" }, { "env": "FEATURE_FLAGS" }],
      "cache": true
    }
  }
}

This example translates a Turborepo build and test pipeline by hand into Nx targetDefaults and namedInputs, keeping inputs broad and keeping every environment variable from the old config in the cache key.

How do you keep backend caching correct and the project graph complete?

Start with outputs. Every build target that writes files needs them declared, for example {projectRoot}/dist. If a declared path is missing, Nx can report a cache hit and restore nothing, so a downstream Docker build packages an empty or stale directory. Inputs work the same way. If a service reads DATABASE_URL, a feature flag or a config/*.yaml file at build or test time, add it to inputs as an env or file input. Without it, a test run against one configuration can be replayed for another.

Set cache: false on any target whose value is its side effect. That covers database migrations, seeding, integration tests against live services, and deploys. A cached migration prints success while the schema stays unchanged. A cached deploy ships nothing.

Check the graph, not your assumptions

Run nx graph and confirm that every package appears and that each edge you expect is drawn. Then run nx show project <name> on a few representative services to see their resolved targets, inputs and outputs. Nx infers edges from imports and package manifests. It does not infer edges from a shared tsconfig base, a codegen script, or .proto and OpenAPI sources that produce client code.

Fix these gaps explicitly. If a project consumes generated code, add an implicitDependencies entry pointing at the project that owns the schema. If the dependency is a file rather than a project, add it to inputs so that changes invalidate the cache. Without these entries, nx affected will skip the consumers.

Go, Python or Rust services in the same repo usually need custom nx:run-commands targets or a community plugin. Plugin maturity varies widely, so check each one for correct input hashing and output declarations before you trust its cache.

{
  "name": "orders-api",
  "implicitDependencies": ["orders-proto"],
  "targets": {
    "build": {
      "executor": "nx:run-commands",
      "options": { "command": "tsc -p tsconfig.build.json", "cwd": "{projectRoot}" },
      "cache": true,
      "inputs": [
        "{projectRoot}/src/**/*",
        "{projectRoot}/config/*.yaml",
        "{workspaceRoot}/tsconfig.base.json",
        { "env": "FEATURE_FLAGS" }
      ],
      "outputs": ["{projectRoot}/dist"]
    },
    "test": {
      "executor": "nx:run-commands",
      "options": { "command": "node --test dist/", "cwd": "{projectRoot}" },
      "dependsOn": ["build"],
      "cache": true,
      "inputs": ["{projectRoot}/src/**/*", "{projectRoot}/config/*.yaml", { "env": "DATABASE_URL" }]
    },
    "migrate": {
      "executor": "nx:run-commands",
      "options": { "command": "node scripts/migrate.js", "cwd": "{projectRoot}" },
      "cache": false
    },
    "deploy": {
      "executor": "nx:run-commands",
      "options": { "command": "./scripts/deploy.sh staging", "cwd": "{projectRoot}" },
      "dependsOn": ["build"],
      "cache": false
    }
  }
}

A backend service's project.json that declares dist as a build output, hashes env vars, YAML config and the shared tsconfig as inputs, adds an implicit edge to the proto project, and disables caching for migrate and deploy.

How should you move CI to nx affected without skipping tests?

Affected detection is only as good as the diff it computes. nx affected compares a base commit to a head commit, set with --base and --head or the NX_BASE and NX_HEAD environment variables. If either is wrong, projects drop out of the run and nothing reports an error. Two causes are common. First, shallow clones: if the CI checkout lacks the merge-base commit, the diff can't be computed correctly, so fetch enough history to include it. Second, PR merge commits: many CI systems build a synthetic merge of the branch into the target, so set the base to the target branch's merge-base rather than HEAD~1. On main, use the last commit that passed CI, not the previous commit, so that a failed run's changes get tested again.

Run the old pipeline and the nx affected pipeline side by side for a fixed window, such as two weeks. Compare which projects each one ran against the baseline you recorded. Any project the old runner tested that Nx skipped points to a missing graph edge or an input that isn't declared. During that window you pay for both: more CI minutes, and two caches that can disagree. Set an end date. If both runners stay in place, engineers stop knowing which result is authoritative. After cutover, keep a scheduled full run of every target as a safety net.

For remote caching, check three things:

  • Artifact security: whether cache artifacts are encrypted and access-controlled.
  • Write access: who can write to the cache.
  • Cache key inputs: whether keys include environment variables, toolchain versions and generated files.

A shared cache that any branch can write to can spread a poisoned artifact to every machine that reads from it. Limit writes to trusted CI runs on protected branches.

When should you adopt plugins and inferred targets, and what are the alternatives?

Running your existing package.json scripts through Nx keeps behavior explicit. Each target is a script you can read, and Nx only adds caching and ordering on top. Plugins go further. They read tool configs such as a TypeScript, Jest or ESLint config and infer targets, inputs and outputs from them. That cuts down on hand-written configuration, but a target's behavior now lives partly in plugin logic rather than in your repo. When a cache hit looks wrong, you have to ask Nx what it resolved, for example with nx show project <name>, before you can reason about it.

Defer plugins and generators until the task runner has reached parity with your baseline: the same tasks, the same order and the same outputs. After that, add one plugin at a time and compare the inferred targets with the scripts they replace.

Keep the migration reversible. Limit your changes to nx.json, project configuration and dev dependencies. Leave turbo.json or lerna.json in place until CI has run cleanly on Nx for a while. A rollback is then a single revert of those files that restores the old path.

Option Engineering time to adopt Ongoing maintenance
Nx with scripts only Low to moderate Moderate. You maintain nx.json and per-project inputs.
Nx with plugins Moderate Lower config volume, but you track plugin behavior across upgrades.
Stay on Turborepo None Low if your current pipeline already meets your needs.
Stay on Lerna None Low for versioning and publishing. Task orchestration may need another tool.
Package manager workspace scripts None Rises with project count, because there is no caching or affected detection.

How can Nx save engineering time?

The time savings come from not doing work that doesn't need doing, and from making the remaining work easier to reason about.

  • Shorter PR pipelines. With a complete graph, nx affected runs builds and tests only for changed projects and their dependents. In a repo with many services, a PR that touches one service's internals skips the rest of the test matrix.
  • Cache reuse across machines and runs. With a remote cache that CI writes and developers read, a developer who checks out a branch can restore build outputs instead of rebuilding them. Re-running a CI job after an unrelated infrastructure failure replays the tasks that already succeeded.
  • Less time diagnosing ordering bugs. Because dependsOn and the project graph are explicit, "the service built before its shared library" becomes a configuration error you can see in nx graph, not an intermittent CI failure.
  • Faster answers to impact questions. Before changing a shared library, nx graph shows which services consume it. You don't have to search the repo for imports.

These savings only appear once the migration costs are paid: auditing inputs, fixing graph edges, running both pipelines in parallel and retraining the team. Compare them honestly.

As a worked example, take these assumed inputs, none of them measured: 40 projects, a full test run of 20 minutes of CI time, a typical PR that affects 6 projects, test time roughly proportional to project count, and 30 PR pipeline runs per working day.

  • Full run per PR: 30 runs × 20 min = 600 CI minutes per day.
  • Affected run per PR: 6/40 × 20 min = 3 min, so 30 × 3 = 90 CI minutes per day.
  • Difference: roughly 510 CI minutes per day, and each developer waits about 3 minutes instead of 20 for test feedback.

Illustrative estimate. All figures are assumed inputs, not measurements. Real results depend on how many projects a typical change touches. A PR that modifies a widely shared library affects most of the graph and saves little. Run the same calculation with your own baseline numbers before committing to the migration. If typical PRs already touch most projects, or if the full run is already short, the savings may not cover the migration and maintenance cost. In that case, the reasons to avoid migrating listed above apply.

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.
  • 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.