What is nx migrate and how does its two-phase upgrade work?
nx migrate is Nx's upgrade tool. Bumping version numbers in package.json and running an install is not enough, because each Nx release can change configuration formats, executor options, generator defaults, and the APIs that plugins rely on. nx migrate handles this by splitting the upgrade into two separate runs.
Phase one: plan. Running nx migrate with a target version resolves which Nx packages and related dependencies need to change. It rewrites their versions in package.json and writes a migrations.json file listing every code migration between your current version and the target. Your source code is not changed in this phase. The output is a plan you can read, edit, and review in a pull request.
Phase two: apply. Running nx migrate --run-migrations executes the entries in migrations.json. These are scripts shipped by Nx and its plugins. They update workspace configuration, rewrite deprecated options, and adjust code affected by breaking changes. The scripts come from the newly installed package versions, so those versions must be on disk first.
Neither phase installs anything. You run your package manager after phase one so the migration scripts exist. You run it again after phase two, because some migrations add or change dependencies.
The full flow:
Bump versions (
nx migrate <version>) → install → review and editmigrations.json→ run migrations (--run-migrations) → install again → verify (build, lint, test, affected checks) → commit
If you skip either install, migrations run against the old code or the dependency tree ends up out of sync with what the migrations expect.
# Phase one: plan. Updates versions in package.json and writes migrations.json.
# Nothing is installed and no source code is changed yet.
npx nx migrate latest
# Install so the migration scripts from the new package versions exist on disk.
npm install
# Review the plan. Remove or reorder entries if needed, then commit it for review.
cat migrations.json
git add package.json package-lock.json migrations.json
git commit -m "chore: bump nx versions and add migrations.json"
# Phase two: apply. Runs every entry in migrations.json against the workspace.
npx nx migrate --run-migrations
# Install again, because some migrations add or change dependencies.
npm install
# Verify the workspace before committing the migrated code.
npx nx run-many -t build lint test
# Commit the migrated code and remove the applied plan.
rm migrations.json
git add -A
git commit -m "chore: apply nx migrations"
A two-phase Nx upgrade using npm: plan with nx migrate, install, review migrations.json, apply with --run-migrations, install again, verify, and commit.
Why upgrade one major version at a time instead of jumping to latest?
Each migration is written against the workspace shape that the previous major leaves behind. A generator that rewrites a config option or moves an executor assumes the earlier rename has already happened. When you jump several majors at once, migrations from different releases run in one pass against code they were never tested on together. Older migrations are also not guaranteed to stay in newer packages, so some may not run at all. The result is one large diff with many unrelated changes, and a CI failure in that diff could come from any of them.
To step one major at a time, pass an explicit target instead of latest, for example nx migrate nx@<next-major>. Use the latest minor/patch of the next major, not its first release, so you pick up fixes to the migrations themselves. Run the full cycle, merge it, then repeat for the next major.
| Approach | PRs and CI runs | Diff size per PR | Attributing a failure |
|---|---|---|---|
| Jump straight to latest | One | Large, mixed concerns | Hard: many majors' changes overlap |
| One major per step | One per major | Bounded to one release's breaking changes | Easier: the failure belongs to one known set |
The cost is real: more PRs, more CI time, more review rounds. You get back a history where each commit maps to one major's breaking changes, with its own green or red CI result. You can bisect it and revert one step without undoing the others.
Platform teams that own large monorepos benefit most. They have many projects, custom plugins and executors, and many reviewers to coordinate. In that setting, a failure you can attribute quickly saves more time than the extra PRs cost.
#!/usr/bin/env bash
# Upgrade Nx by exactly one major version per branch/PR.
# Usage: ./nx-step-major.sh <version>
# Pass the latest patch of the NEXT major, never 'latest'.
set -euo pipefail
TARGET="${1:?usage: $0 <latest patch of the next Nx major>}"
BRANCH="chore/nx-migrate-${TARGET}"
git switch -c "$BRANCH"
# 1. Pin the target explicitly. This updates package.json and writes
# migrations.json, but changes no source files yet.
npx nx migrate "nx@${TARGET}"
npm install
git add -A
git commit -m "chore(nx): bump package versions to ${TARGET}"
# 2. Apply only this major's migrations, against the state the
# previous major left behind.
if [ -f migrations.json ]; then
npx nx migrate --run-migrations
npm install
rm migrations.json
fi
git add -A
git commit -m "chore(nx): run ${TARGET} migrations" || echo "no migration changes"
# 3. Gather CI evidence for this single step before opening the PR.
# A failure here belongs to one known set of breaking changes.
npx nx run-many -t lint test build
echo "Open a PR for ${BRANCH}, merge it, then rerun for the next major."
A script that upgrades a workspace by one explicitly pinned Nx major per branch, with separate commits for the version bump and the migrations, then runs lint, test and build so each step has its own CI result.
Pre-flight checklist: what should be in place before you run nx migrate?
Each item below exists so that, when something breaks later, you can tell whether the upgrade caused it.
- Clean git tree. Commit or stash everything before you start.
nx migraterewritespackage.jsonand, in the second phase, source and config files. Unrelated local edits mixed into that diff make review and rollback harder. - Green CI on main. Start the upgrade branch from a commit whose pipeline passed. If main is already red, you cannot tell inherited failures from new ones.
- A full, uncached baseline run. Run build, test, and lint across all projects with the computation cache disabled or cleared. Cached results can hide failures. Write down what "passing" means today: known flaky tests, skipped suites, and existing warnings. After migrating, you will compare against this record.
- A dedicated upgrade branch. Use one branch per major version so each step can be reviewed and reverted on its own.
- Recorded versions. Note the current Nx version, Node version, and package manager with its version.
nx reportprints most of this. Keep the output in the PR description so reviewers know the starting point. - Plugin support for the target major. Check that every third-party and community plugin has a release compatible with the target Nx major. An unmaintained plugin can block the upgrade. You may have to pin it, fork it, or replace it, and that decision is easier to make before you start.
- Node engine requirements. Confirm that the target Nx major and your plugins support your Node version. This includes CI runners and container images, not only developer machines.
#!/usr/bin/env bash
# Pre-flight checks before running `nx migrate`. Assumes npm; adapt for pnpm/yarn.
# Usage: ./nx-preflight.sh <target-nx-major>
set -euo pipefail
TARGET_MAJOR="${1:?usage: nx-preflight.sh <target-nx-major>}"
# 1. Refuse to start with uncommitted or untracked changes.
if [ -n "$(git status --porcelain)" ]; then
echo "Working tree is not clean. Commit or stash first." >&2
exit 1
fi
# 2. Branch from an up-to-date main whose CI run passed (check this in your CI UI).
git switch main && git pull --ff-only
git switch -c "chore/nx-upgrade-v${TARGET_MAJOR}"
# 3. Record the starting versions; paste this file into the PR description.
{
echo "node: $(node --version)"
echo "npm: $(npm --version)"
npx nx report
} > preflight-versions.txt
# 4. Uncached baseline: clear the Nx cache, then bypass it for every target.
npx nx reset
npx nx run-many --targets=build,test,lint --skip-nx-cache 2>&1 | tee baseline-run.log
# Next, write known flaky tests, skipped suites and existing warnings into the PR.
# 5. Node engine range declared by the target Nx major.
npm view "nx@^${TARGET_MAJOR}" engines
# 6. Peer and engine requirements of each third-party plugin (placeholder names).
for plugin in "@example-org/nx-custom-plugin" "nx-community-plugin-example"; do
echo "== ${plugin}"
npm view "${plugin}" peerDependencies engines
done
A pre-flight script that enforces a clean tree, creates a dedicated upgrade branch, records Nx, Node and npm versions, runs an uncached build/test/lint baseline, and inspects Node engine and plugin peer-dependency ranges for the target Nx major.
How do you review, edit, and commit migrations.json?
Each entry in migrations.json names the package that owns it, the version that introduced it, a short description, and the implementation that will run. Sort mentally by package and read the descriptions first. They are the most compact list you will get of the breaking changes the codemods expect to handle, and they tell you which projects, configs, or executors are about to change. An entry with a vague description is a signal to open the referenced migration source before running it.
You can defer or remove entries by deleting them from the file before running migrations. Do this deliberately, not to make a noisy diff go away. A skipped migration leaves the workspace in a state that later migrations, including ones in the next major, may not expect, because they are written assuming earlier ones ran. Record every deferred entry in an issue with its package, version, and the reason it was deferred, and decide when you will apply it, by running it later or by making the equivalent change by hand.
Commit in two steps:
- Version bump. Commit the
package.jsonchanges, the lockfile, andmigrations.json. - Codemod output. Commit everything that running the migrations changed.
This separation lets reviewers tell dependency changes apart from generated source edits, and lets you revert one without the other. Keep migrations.json in the PR as an audit record of what was applied. Delete it in a follow-up commit once the run succeeds, so nobody runs the same migrations again.
On large monorepos the codemod commit can touch hundreds of files. Line-by-line review stops being realistic at that size, so reviewers end up depending on the test suite and spot checks of representative projects.
# 1. Generate the plan: updates package.json and writes migrations.json
npx nx migrate latest
npm install # refresh the lockfile so the bump commit is complete
# 2. Review: one line per entry, grouped by package, descriptions first
jq -r '.migrations | sort_by(.package)[]
| "\(.package)\t\(.version)\t\(.name)\n \(.description)"' migrations.json
# 3. Defer one entry deliberately (placeholder name), then track it in an issue
# with its package, version, and reason. Later migrations may assume it ran.
DEFER="update-example-executor-options"
jq --arg n "$DEFER" 'del(.migrations[] | select(.name == $n))' \
migrations.json > migrations.tmp.json && mv migrations.tmp.json migrations.json
# 4. Commit the version bump on its own
git add package.json package-lock.json migrations.json
git commit -m "chore: bump Nx packages (migrations.json kept as audit record)"
# 5. Run the codemods and commit only their output
npx nx migrate --run-migrations
npm install # migrations can add or change dependencies
git add -A
git commit -m "chore: apply Nx migrations (deferred: $DEFER, see tracking issue)"
# 6. With large diffs, lean on tests rather than line-by-line review
npx nx run-many -t lint test build
# 7. After the run succeeds, delete the file so nobody re-runs it
git rm migrations.json
git commit -m "chore: remove applied migrations.json"
A shell workflow that lists migrations.json entries by package, version, and description, deliberately removes one entry for tracked deferral, and commits the version bump, the codemod output, and the removal of migrations.json as separate commits.
What does nx migrate not handle, and how do you verify the result?
Migrations are written by plugin authors against the workspace shapes they expect. If your setup drifts from those shapes, a codemod can skip a file or rewrite it only partially, and it still reports success. Treat migrations as best-effort and check these areas by hand:
- Node engine requirements. A new major may drop support for your Node line. Nothing in
migrations.jsonupdates.nvmrc, theenginesfield, or developer machines. - Lagging third-party plugins. Community plugins often trail Nx releases. The usual result is peer dependency conflicts that the package manager either rejects or quietly overrides.
- Custom executors and generators. Any code that imports Nx internals instead of the public devkit can break without a migration to fix it.
- CI configs and Docker images. Pinned Node, package manager, or Nx versions in pipeline files and base images will not be updated.
- Coupled bumps. An upgrade that also moves TypeScript or a framework widens the blast radius. Some failures will come from those tools, not from Nx.
Verifying the result
- Run
nx resetto clear the local cache and restart the daemon. A stale cache can replay outputs from before the upgrade, and the daemon can hold an outdated project graph. - Run
nx affectedfor the changed files. Then run a full build and test pass with--skip-nx-cache, because affected detection depends on the same graph you are trying to validate. - Open
nx graphand compare it with the previous graph. Look for missing projects or dependency edges that disappeared. - Confirm that
nxand every@nx/*package resolve to the same version.nx reportlists them.
An uncached full run costs real CI time, possibly hours on a large monorepo. That is still cheaper than shipping a false green and finding out from production.
When should you avoid or postpone an Nx major upgrade, and what are the alternatives?
Reasons to hold off
Postpone the upgrade when any of these is true:
- A critical plugin has no support for the new major yet. Community and in-house plugins pin peer ranges on
@nx/devkit. If you force past that range, generators and executors can fail at runtime in ways thatnx migratecannot detect. - A release freeze is in place. An upgrade changes the toolchain under every project at once. That is the wrong kind of change to land while you are trying to keep risk low.
- You have no CI baseline you trust. If main is already flaky or red, you cannot attribute new failures to the upgrade. Fix the baseline first.
Alternatives compared
| Approach | What you gain | What it costs |
|---|---|---|
| Single multi-major jump | Fewer upgrade events | Migrations stack up, and failures are hard to bisect |
| Manual version bumps, no migrations | Fast | Skips config and code rewrites, which leaves silent drift |
| Pin and stay behind | Stability now | Security gaps and a steeper climb later |
| Scheduled small upgrades | Small, reviewable diffs | Recurring, predictable effort |
The scheduled approach usually wins. Each upgrade stays small enough for one engineer to review and revert in an afternoon.
Rollback plan
- Revert the upgrade commits as a unit. This is why section 4 kept them separate.
- Reinstall from the restored lockfile using your package manager's frozen or CI install mode. The lockfile reproduces the old dependency tree exactly, and resolving dependencies again does not.
- Run
nx resetto clear the local cache and daemon state. - Do not assume that remote cache entries written by the new version are compatible with the old one. Hashing inputs and output formats can change between majors. Disable remote reads for the first rollback run, or point that run at a separate cache namespace.
How does upgrade cadence affect development cost and save engineering time?
Upgrade cost has two parts. Fixed overhead is what you pay every time: reading release notes, running nx migrate, reviewing migrations.json, a full CI run, and a release. Variable cost is the breaking changes. Upgrading every major keeps the variable part small and readable, but you pay the fixed part every time, so put it in the roadmap as recurring work. Deferring upgrades avoids that overhead for a while. The catch-up then bundles unrelated breaking changes into one branch, and a failing test can have several possible causes.
| Approach | Size of each migrations.json | Debugging a failure | Scheduling |
|---|---|---|---|
| Every major, soon after release | Small, one major's changes | One likely cause | Recurring, predictable |
| Multi-major catch-up | Large, mixed changes | Several interacting causes | Rare, disruptive |
Illustrative estimate (assumed numbers, not a benchmark)
Formula: cost = O + (B × F)
- O = fixed overhead in hours
- B = breaking changes that need manual work
- F = hours per fix
Assumed inputs: O = 4h. Each major brings B = 6. F = 1.5h when changes are isolated and 2.5h when they are entangled.
- Two separate upgrades: 2 × (4 + 6 × 1.5) = 26h, spread across the year.
- One two-major catch-up: you still step through each major, so O is paid twice: 2 × 4 + 12 × 2.5 = 38h, in one block.
Ways to save time
- Reusable checklist. Keep the pre-flight and verification steps in the repo so each upgrade starts from a known list.
- Standard PR template. Include sections for the version bump, the migrations that ran, any skipped migrations and why, and manual fixes. Reviewers then know where to look.
- Named rotating owner. One person owns each upgrade and the role rotates. Knowledge spreads across the team, and the upgrade does not stall while waiting for whoever has time.
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.