What is nx migrate and how does the two-phase upgrade work?
nx migrate is the Nx command for moving a workspace from one Nx version to another. It splits the upgrade into two phases, so you can see what will change before any source file is touched.
Phase one: plan. Running nx migrate with a target version (or latest) updates the Nx-related dependency versions in package.json and writes a migrations.json file. That file lists the migrations that Nx and its plugins define for the version range you are crossing. Nothing is installed in this phase, and your project code is unchanged. You run your package manager's install yourself.
Phase two: apply. nx migrate --run-migrations executes each entry in migrations.json. These migrations rewrite workspace configuration, project configuration, and sometimes source code, to match new defaults or replace deprecated APIs.
The flow:
version bump (package.json + migrations.json) -> install -> review migrations.json -> run-migrations -> verify
Neither phase is a one-shot upgrade. The version bump alone gives you new packages running against old configuration. The migrations only cover changes that plugin authors chose to automate. Third-party plugins, custom executors and generators, and your own conventions can still break.
In a large monorepo, one upgrade can touch hundreds of files owned by many teams. Treat it as a reviewable change. Commit each phase separately, keep the generated diff readable, and verify it the same way you would verify any change to shared build infrastructure.
#!/usr/bin/env bash
# Two-phase Nx upgrade, with each phase committed separately for review.
#
# version bump -> install -> review migrations.json -> run-migrations -> verify
#
set -euo pipefail
git switch -c chore/nx-upgrade
# Phase one: plan.
# Updates Nx-related versions in package.json and writes migrations.json.
# Nothing is installed yet, and project code is unchanged.
npx nx migrate latest
# Install the new versions yourself.
npm install
# Review the planned migrations before any of them run.
cat migrations.json
git add package.json package-lock.json migrations.json
git commit -m "chore: bump Nx versions and generate migrations.json"
# Phase two: apply.
# Runs every entry in migrations.json. Migrations can rewrite workspace
# config, project config and source files.
npx nx migrate --run-migrations
# Keep this diff separate from the version bump so reviewers can read it.
git add -A
git commit -m "chore: apply Nx migrations"
# Verify. Migrations do not cover third-party plugins, custom executors or
# local conventions, so run the full pipeline, not only affected projects.
npx nx run-many -t lint test build
# Once the branch is merged, migrations.json can be deleted in a follow-up commit.
A bash sequence that runs the nx migrate plan and apply phases as separate, reviewable commits and then verifies the whole workspace.
What should you check before starting an Nx version upgrade?
Before running anything, make the starting point boring and reproducible. Any failure you hit mid-upgrade should be caused by the upgrade, not by something that was already broken.
- Clean working tree on a dedicated branch. Migrations rewrite config and source files in place. Uncommitted local changes get mixed into the generated diff and make it hard to review or revert.
- Green CI on the current version. If tests are already flaky or failing, you can't tell a migration regression from existing noise. Fix or quarantine those failures first.
- A known-good lockfile. Commit the lockfile and confirm a fresh install reproduces it. Otherwise transitive drift can slip in alongside the Nx bump.
- An inventory of Nx plugins. List every core and community plugin in
package.json. Each one can ship its own migrations. Community plugins may also lag behind Nx releases and pin older peer ranges.
| Check | Why it matters | What failure looks like |
|---|---|---|
| Clean branch | Isolates generated changes | Unreviewable mixed diff |
| Green CI | Gives a regression baseline | Unclear whether migration broke tests |
| Locked dependencies | Keeps installs reproducible | "Works on my machine" drift |
| Plugin inventory | Shows every migration source | Missed or conflicting migrations |
Also look for peer dependency changes. Framework plugins often move their related tooling, such as TypeScript, test runners, linters or the framework itself, to new versions. That can turn an Nx upgrade into a framework upgrade.
For timing, schedule the upgrade right after a release and outside busy delivery windows. That gives teams room to absorb breakage without blocking shipping work.
How do you read and edit nx migrations.json safely?
Open migrations.json before running anything and review it the way you would review an infrastructure change plan. Each entry under migrations names the package that contributed it, the version it targets, and a description of what it changes. Group the entries by package. You will usually see a cluster from Nx itself and smaller clusters from plugins for frameworks, test runners, or bundlers. A large cluster from one plugin tells you which part of the workspace will see the most churn, and who should review that part of the diff.
Read every description, not just the names. Some migrations rename or move configuration options. Others rewrite source imports or change default behavior. The descriptions that mention changed defaults matter most, because the code still compiles after the migration while the build or test output changes.
Removing or deferring an entry is reasonable in a few cases:
- The migration targets a plugin or feature the workspace no longer uses.
- The change conflicts with a deliberate local customization, and you will port it by hand.
- The migration is large, and you want to land it in a separate, reviewable commit.
Removal has a cost. nx migrate computes entries from the version range between what is installed and the target. Once package.json moves past that range, a dropped migration is not offered again on the next upgrade. Its change still applies to your code. Later migrations may also assume it has already run, so the breakage shows up in a future upgrade where the cause is harder to trace. If you defer an entry, save it in a separate file, record it in the upgrade ticket, and run it explicitly before the next version upgrade.
#!/usr/bin/env bash
set -euo pipefail
# 1. Count entries per contributing package to see where the churn is.
jq -r '.migrations | group_by(.package) | .[] | "\(length)\t\(.[0].package)"' migrations.json \
| sort -rn
# 2. Print every migration with its target version and full description.
# Read these all, especially the ones that mention changed defaults.
jq -r '.migrations[] | "[\(.package)@\(.version)] \(.name)\n \(.description)\n"' migrations.json
# 3. Defer one entry. Match on package AND name, since names can repeat
# across packages. Both values are placeholders.
PKG="@nx/jest"
NAME="example-migration-name"
# Save the deferred entry to its own file so it is not lost.
jq --arg p "$PKG" --arg n "$NAME" \
'{migrations: [.migrations[] | select(.package == $p and .name == $n)]}' \
migrations.json > migrations.deferred.json
# Remove it from the main plan.
jq --arg p "$PKG" --arg n "$NAME" \
'.migrations |= map(select((.package == $p and .name == $n) | not))' \
migrations.json > migrations.tmp.json && mv migrations.tmp.json migrations.json
# 4. Run the remaining plan and commit it.
npx nx migrate --run-migrations=migrations.json
# 5. Before the NEXT version upgrade, run the deferred entry explicitly
# in its own commit. nx migrate will not offer it again.
# npx nx migrate --run-migrations=migrations.deferred.json
Uses jq to group migrations.json entries by package, print each description, and split one entry into a separate deferred file. That file is then run explicitly with nx migrate --run-migrations, because nx migrate will not offer the entry again.
How to apply migrations step by step across major versions
Hop one major version at a time. Each major's migrations are written and tested against the state the previous major leaves behind. If you skip majors, migrations from several releases run in one batch against code they were not tested on, and when something fails you cannot easily tell which release caused it.
For each hop, the sequence is:
npx nx migrate <next-major>rewritespackage.jsonand generatesmigrations.json.npm install(or your package manager's equivalent) installs the new versions. Migrations run from the newly installed packages, so they will not run correctly until the install is finished.- Commit the version bump and lockfile.
npx nx migrate --run-migrations, then commit the result on its own.- Make manual fixes until lint, build and tests pass, and commit those separately.
Keeping these as three commits makes the diff readable: reviewers can skim the generated changes and spend their attention on the hand-written fixes. It also means you can revert only the fixes without discarding the migration run.
| Approach | Calendar time | CI runs | Manual fixing | Debuggability |
|---|---|---|---|---|
| One major per hop | Longer | One set per hop | Small per hop | High |
| Single multi-major jump | Shorter | Fewer | Large, mixed causes | Low |
Worked example (illustrative estimate). Assume three majors to cross, a 45-minute CI pipeline, and about 2 hours of manual fixes per hop when you go incrementally. Three hops cost about 6 hours of fixing plus waiting on CI. A single jump saves two CI cycles, but if overlapping breakages triple the effort of isolating causes, fixing grows to around 12–18 hours. Under these assumptions, the incremental path uses less total engineering time even though it takes more calendar days.
#!/usr/bin/env bash
# One Nx major-version hop. Run once per major, e.g. ./nx-hop.sh 20, then ./nx-hop.sh 21.
# The version argument is a placeholder; use the next major after your current one.
set -euo pipefail
TARGET="$1"
# Phase 1: rewrite package.json and generate migrations.json for this major only.
npx nx migrate "$TARGET"
# Install before running migrations: they execute from the newly installed packages.
npm install
# Commit 1: version bump and lockfile only.
git add package.json package-lock.json migrations.json
git commit -m "chore(nx): bump to Nx $TARGET"
# Phase 2: apply the generated code and config changes.
npx nx migrate --run-migrations
# Migrations can add or change dependencies, so reinstall if package.json moved.
npm install
# Commit 2: generated migration output, kept apart so reviewers can skim it.
# migrations.json stays in this commit as a record of what ran; delete it after the upgrade if you prefer.
git add -A
git commit -m "chore(nx): run Nx $TARGET migrations"
# Phase 3: verify. Fix failures by hand, then commit them as a third, separate commit:
# git add -A && git commit -m "fix: manual fixes for Nx $TARGET"
# Do not start the next hop until lint, build and test all pass.
npx nx run-many -t lint build test
A per-hop script that bumps Nx one major version, installs dependencies before running migrations, and keeps the version bump, the generated migration changes and the manual fixes in three separate commits.
How do you verify an Nx upgrade and catch breaking changes migrations miss?
Affected-only runs are the wrong tool here. nx affected compares the project graph against a base commit, and an Nx upgrade changes the tooling that every project depends on, not a specific project's source. Projects whose files never changed can still break because a plugin now infers targets differently or an executor's defaults shifted. Run lint, typecheck, test and build across every project, for example with nx run-many.
Clear or bypass the cache for the same reason. Run nx reset locally and disable remote cache reads for this pipeline. A cache hit replays output produced by the old toolchain, so a green result only shows that the previous version worked.
The cost is real. Illustrative estimate: assume 300 projects, an affected run that normally touches 20, and about 90 seconds per project across all targets. The affected run takes about 30 minutes of compute. The full uncached run takes about 7.5 hours, spread across your CI agents. You pay that once per upgrade. Shipping a silent regression usually costs more.
A green build still doesn't prove the upgrade is correct. Migrations are written against standard layouts. Heavily customized configs, custom executors and unusual folder structures can make a migration fail, apply only partially, or rewrite options so behavior changes while builds still pass. Diff the build output, including bundle contents and emitted files, against the pre-upgrade baseline.
Then read the changelog for every major version you crossed. Search the codebase for each deprecated API, executor name and generator option it lists, including in custom plugins and scripts that migrations never touch.
#!/usr/bin/env bash
# Post-upgrade verification: every project, no cache, then hunt for leftovers.
set -euo pipefail
# Drop the local cache and stop the Nx daemon so nothing from the old
# toolchain is replayed.
nx reset
# Run every target on every project, not just affected ones.
# --skip-nx-cache bypasses cache reads, local and remote.
# Projects that do not define a target (e.g. typecheck) are skipped.
nx run-many -t lint typecheck test build --skip-nx-cache --parallel=3
# Compare emitted files against a baseline captured before the upgrade.
# Assumes the pre-upgrade build output was copied to ./baseline-dist.
diff -rq baseline-dist dist > build-diff.txt || true
echo "Files that differ from the pre-upgrade build:"
cat build-diff.txt
# Search for deprecated names from the changelogs you crossed.
# Example: the @nrwl/* scope was renamed to @nx/*. Replace these
# patterns with the deprecations listed for your target versions.
# Custom plugins and scripts are included because migrations skip them.
DEPRECATED_PATTERNS=(
'@nrwl/'
'some-removed-generator-option'
)
for pattern in "${DEPRECATED_PATTERNS[@]}"; do
echo "== $pattern =="
grep -rn --exclude-dir=node_modules --exclude-dir=dist --exclude-dir=.git \
-e "$pattern" . || echo "no matches"
done
A post-upgrade script that clears the Nx cache, runs lint, typecheck, test and build across all projects without cache reads, diffs build output against a pre-upgrade baseline, and greps the repo for deprecated names taken from the changelogs.
When should you avoid or delay an nx migrate upgrade, and what are the alternatives?
Upgrading now is the wrong call in three common situations.
A community plugin lags behind. Third-party plugins often declare a narrow peer range on @nx/devkit and ship no entries in migrations.json. Upgrading Nx past that range leaves the plugin's executors calling APIs that may have changed, and nothing rewrites its options for you.
The peer dependency blast radius is too large. First-party plugin migrations can also bump framework and tooling versions, such as TypeScript, Jest, ESLint or a frontend framework. In a large monorepo, one Nx upgrade can become several framework upgrades at once. Teams that don't own those frameworks then absorb breaking changes they didn't plan for.
The workspace is many majors behind. Migrations are written against the state the previous version left behind. The further back you start, the more each one depends on earlier steps having run cleanly, and the harder it is to tell which step broke something.
| Option | Cost | Risk | When it fits |
|---|---|---|---|
| Stay pinned | Low now, grows over time | Security fixes and plugin support drift away | Short freeze, release crunch |
| Single multi-major jump, manual fixes | One large, hard-to-review PR | Failures hard to attribute to a specific step | Small workspace, strong test coverage |
| Recreate config from a fresh workspace | Days of diffing generated config | Lost custom settings | Config heavily hand-edited or many majors behind |
| Pin, fork or replace the blocking plugin | Ongoing maintenance for forks | Fork diverges from upstream | One plugin is the only blocker |
How do you roll out and roll back an Nx upgrade in a shared monorepo?
Rollout
- Pick a merge window instead of a long freeze. A full freeze blocks every team for the length of the upgrade. A short window of an hour or two, announced in advance, keeps the base branch stable while you rebase and merge. Schedule it when merge traffic is lowest.
- Keep the upgrade branch short-lived. Migrations rewrite
package.json, the lockfile,nx.jsonand project configs. These are the files other teams touch most often, so every day the branch stays open adds rebase conflicts. If a conflict appears in a generated file, rerun the migration on the new base instead of hand-merging the file. - Announce the local workflow changes. Tell teams to reinstall dependencies after pulling, run
nx resetif the daemon or local cache behaves oddly, and update any changed command flags or generator names in their scripts. Include the commit SHA so people can tell whether a failure comes before or after the upgrade.
Rollback
- Revert the upgrade commits as a unit, in reverse order.
- Restore the previous lockfile exactly. Don't regenerate it, because a regenerated lockfile can resolve different transitive versions.
- Confirm CI and the remote cache. Computation hashes include dependency state, so after the revert you should get cache hits on entries from before the upgrade. Unexpected misses, or artifacts produced by the upgraded toolchain, mean the revert is incomplete.
Each step lands as its own commit and gets its own verification. When something breaks, you can trace it to one migration, one dependency bump or one manual edit, and the fix or revert covers only that step.
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 migrate upgrade, 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.