What is the Nx single version policy, and how do per-project versions differ?
Under the Nx single version policy, one root package.json and one lockfile set the version of every third-party dependency for every app and library in the workspace. Projects don't declare their own versions. An API service and a shared data-access library both import the same resolved copy of a package, so builds and tests in the workspace all run against that one version.
The per-project model gives each project its own package.json, usually wired together with package-manager workspaces. Each project declares its own ranges. In a root-only setup, the root manifest lists a dependency such as "some-orm": "^5.0.0", and apps/billing has no manifest entry for it. In a per-project setup, apps/billing/package.json might declare "some-orm": "^5.0.0" while apps/ledger/package.json declares "some-orm": "^6.0.0".
The package manager reconciles those declarations at install time. If the ranges overlap, it resolves one version and, with a hoisting layout, places it in the root node_modules. If the ranges conflict, it has to install a second copy in a nested node_modules under the project that needs it. pnpm isolates packages through symlinks instead of flat hoisting, but it still stores both versions. Either way, two versions of the same package end up in the dependency graph.
| Dimension | Single version | Per-project versions |
|---|---|---|
| Source of truth | Root package.json |
Each project's package.json |
| Lockfile shape | One entry per dependency, typically | Can hold multiple resolved versions per dependency |
| Duplication risk | Low | Grows as ranges diverge |
| Upgrade unit | Whole workspace at once | One project at a time |
| Team autonomy | Low; changes need workspace-wide agreement | High; teams upgrade on their own schedule |
{
"name": "acme-workspace",
"private": true,
"dependencies": {
"some-orm": "^5.0.0"
}
}
{
"name": "acme-workspace",
"private": true,
"workspaces": ["apps/*", "libs/*"]
}
{
"name": "billing",
"dependencies": { "some-orm": "^5.0.0" }
}
{
"name": "ledger",
"dependencies": { "some-orm": "^6.0.0" }
}
The same dependency declared once at the root under a single version policy, and declared per project with conflicting majors, which produces a hoisted copy plus a nested duplicate.
How does it work? Nx's project graph under each dependency model
In short, the single version policy works by combining two mechanisms. The package manager installs one resolved version of each dependency from the root manifest and lockfile. Nx then works out, from source imports, which projects actually use each of those packages. The first mechanism guarantees consistency. The second keeps that consistency from turning every change into a full rebuild or every deployable into a bloated artifact.
Nx builds a project graph by analyzing each project's source files. Every import becomes an edge, either to another workspace project or to an external package node derived from the lockfile. The graph records which projects actually use a dependency, whether or not it is declared in a per-project manifest.
That edge-level detail drives affected commands. When the root package.json or lockfile changes, Nx can compare the old and new resolved versions and mark only the projects whose graph edges reach a changed package, plus their dependents. Bumping a queue client then retests the three services that import it, not all forty projects. How precisely this works depends on your Nx version and package manager.
root package.json ─┐
├──► project graph (source imports → package nodes)
lockfile ──────────┘
┌─────────────┬──────────────┬─────────────┐
│ orders-api* │ billing-api* │ docs-site │
│ pg, queue │ pg, queue │ markdown │
└──────┬──────┴──────┬───────┴─────────────┘
* affected: queue │ │
version changed ▼ ▼
dist/orders-api dist/billing-api
package.json: package.json:
pg, queue pg, queue
(pruned lockfile) (pruned lockfile)
The same graph matters at build time. For deployable or publishable artifacts, Nx tooling can generate a manifest, and in some setups a pruned lockfile, that lists only the packages the project imports. It can also check a hand-written manifest against those imports. As a result, one root package.json does not force every container image to ship every package. Support for per-project manifests, pruning, and workspace protocols differs between package managers and changes across releases, so check the current Nx and package-manager docs before you rely on any of these behaviors.
Under the per-project model, the same graph still exists, but the inputs differ. Each project's manifest feeds the package manager, which may resolve several versions of one package. Nx still derives edges from source imports, so affected detection and build pruning continue to work. The difference is that a version change in one project's manifest affects only that project and its dependents, and nothing forces the versions to converge.
root package.json ──┐
├──► project graph (source imports → package nodes)
lockfile ───────────┘
│
┌───────────────────┼───────────────────┐
▼ ▼ ▼
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│*orders-api* │ │*billing-api*│ │ docs-site │
│ pg, queue │ │ pg, queue │ │ markdown │
└──────┬──────┘ └──────┬──────┘ └─────────────┘
│ │ not affected:
│ │ no edge to queue
▼ ▼
┌─────────────┐ ┌─────────────┐
│dist/orders- │ │dist/billing-│
│api │ │api │
│package.json:│ │package.json:│
│ pg, queue │ │ pg, queue │
│pruned lock │ │pruned lock │
└─────────────┘ └─────────────┘
*name* = affected: resolved version of queue changed in lockfile
Root manifest and lockfile feed the project graph; a queue bump marks only importing projects affected, and each build artifact gets a pruned dependency list (check current Nx and package-manager docs).
Why do runtime-singleton dependencies make single-version the safer default for backend services?
The version split that matters most is not about features. It is about identity. Some libraries hold process-wide state or define classes and types that cross library boundaries: web frameworks, ORMs, logging and tracing clients, and shared type or schema packages. When two copies of one of these load into the same Node process, each copy has its own module instance. The package name is the same, but the code is separate.
Three failure modes appear repeatedly:
instanceofreturns false. Suppose a shared data-access lib resolves ORM copy A and throws itsNotFoundError. The service resolves copy B and checkserr instanceof NotFoundError. The check fails because the two constructors are different objects. The request falls through to the generic 500 handler, and nothing in the stack trace explains why.- Duplicated module-level state. Tracing and logging clients often keep a global registry or provider. With two copies, the service registers its exporter on one registry while instrumented libs report spans to the other. The result is broken traces or missing log context, with no error raised.
- Type mismatches. In TypeScript, classes with private or protected members are compared nominally across declarations. Two libs that each depend on their own version of a schema package can fail to compile when one passes an entity to the other. Teams then tend to work around the error with casts that hide real incompatibilities.
Each of these bugs sits in a seam between libraries, so unit tests in either lib rarely catch it. A single version policy makes the whole class of bugs impossible for the packages where it matters most. That is the main reason to make single-version the default for backend services.
// --- libs/data-access/src/find-order.ts ---
// Resolves @acme/orm (placeholder package) from the root node_modules, e.g. 5.1.x.
import { NotFoundError } from '@acme/orm';
export async function findOrder(id: string): Promise<never> {
// ...query elided; the record does not exist...
throw new NotFoundError(`order ${id} not found`);
}
// --- apps/orders-api/src/routes/get-order.ts ---
// Resolves @acme/orm from apps/orders-api/node_modules, e.g. 5.2.x.
// Same package name, but a separate module instance with its own NotFoundError class.
import { NotFoundError } from '@acme/orm';
import { findOrder } from '@myorg/data-access';
export async function getOrder(id: string) {
try {
return { status: 200, body: await findOrder(id) };
} catch (err) {
// false: err was built by copy A's constructor, and this checks against copy B's.
// instanceof walks the prototype chain looking for B's prototype object,
// which never appears there.
if (err instanceof NotFoundError) {
return { status: 404, body: { message: err.message } };
}
// A missing record falls through to here and the client gets a 500.
return { status: 500, body: { message: 'internal error' } };
}
}
// Diagnosis: `npm ls @acme/orm` lists every installed copy. More than one
// version in the tree means the two sides of this seam can disagree.
A shared data-access lib throws NotFoundError from one copy of an ORM package, and the service's instanceof check against its own copy returns false, so a 404 becomes a 500.
How do upgrades work under the single version policy, and how does that save engineering time?
Under the single version policy, an upgrade is one pull request. You change the version in the root package.json, regenerate the lockfile, and every project that depends on the package moves together. Run nx affected -t test to test only what the change touches, or the full suite if the package is used widely. Breakages surface in one CI run, and one engineer fixes them while the changelog is fresh. For Nx and its plugins, nx migrate latest updates versions and writes a migrations.json. nx migrate --run-migrations then applies code and config rewrites across the workspace.
With per-project versions, the same bump happens across N package.json files on N timelines. A security patch has to be applied, reviewed, and released many times. The services nobody owns drift until they are several majors behind, and those are the most expensive upgrades.
The lockstep model has real costs:
- One slow team or one incompatible service can block a bump for everyone.
- A root
package.jsonchange can mark most of the graph as affected, so routine bumps can trigger near-full CI runs. - Large breaking upgrades need a central owner, not a shared backlog ticket.
Illustrative estimate (assumed numbers, not a benchmark). Assume 12 services, 2 hours per bump-and-review, 3 services needing 1 hour of fixes each, and 1 hour of extra CI and coordination for the shared PR.
- Per-project: N × bump + k × fix = 12 × 2 + 3 × 1 = 27 hours
- Single-version: bump + coordination + k × fix = 2 + 1 + 3 × 1 = 6 hours
#!/usr/bin/env bash
set -euo pipefail
git switch -c chore/bump-deps
npm install --save-exact typescript@5.4.5
npx nx migrate latest
npm install # install the versions nx migrate wrote
npx nx migrate --run-migrations # apply code/config rewrites across the workspace
rm -f migrations.json # remove once migrations are applied and committed
npx nx show projects --affected --base=origin/main --head=HEAD
npx nx affected -t test --base=origin/main --head=HEAD
git add -A
git commit -m "chore: bump typescript and Nx across the workspace"
A single-branch upgrade in an Nx workspace: bump a root dependency, run Nx migrations, list affected projects, and test them before opening one pull request.
How can you run a large breaking upgrade without abandoning the single-version rule?
The single-version rule fails when a breaking upgrade is treated as one giant pull request. When that PR stalls, someone suggests letting a few projects stay on the old major "for now," and that temporary fork tends to become permanent. The way to avoid this is to do most of the migration work before the version changes, so the bump itself is small and boring.
A workable sequence:
- Wrap the dependency in an adapter library. Create a library such as
libs/shared/http-clientthat exposes your own interface, for examplecreateClient()andrequest(). Inside, it calls the third-party API. Migrate call sites to the adapter in batches of small commits, each passingnx affectedchecks. Call sites now change once, onto your API, instead of once per breaking release. - Add enforcement. Use a lint rule such as
no-restricted-importsto block direct imports of the dependency outside the adapter. This stops new code from bypassing it while the migration is in progress. - Put behavior changes behind flags. If the new version changes defaults like timeouts, serialization, or error shapes, implement the new behavior inside the adapter behind a flag. Turn it on per service while still on the old version, and watch for problems.
- Bump last. By this point, the only code that touches the dependency's API is inside the adapter. The version bump becomes a single-library change plus a lockfile update.
Every commit along the way leaves the repo green and on one version. You never need a long-lived branch or a second copy of the dependency.
Who should use the single version policy?
The single version policy fits workspaces where projects share code at runtime and ship from the same repository:
- Backend teams running many similar Node services that share an ORM, web framework, logging or tracing client, or DI container. These are the teams most exposed to the duplicate-instance bugs described above.
- Product teams with internal shared libraries (UI components, data-access, schema or type packages) consumed by several apps. One version means a library is only ever compiled and tested against one set of dependencies.
- Organizations with a platform or developer-experience team that can own workspace-wide upgrades, including the large breaking ones.
- Teams that need fast, uniform security patching, where one lockfile change and one CI run is preferable to patching many manifests separately.
It is a weaker fit for:
- Workspaces that are mostly unrelated apps sharing a repository for convenience, with little shared code and independent release schedules.
- Repositories that mainly publish packages to external consumers who need a range of supported versions. These still benefit from central dev-dependency pinning, but their published
peerDependenciesranges are deliberately wide. - Organizations with no one able to own upgrades. Lockstep upgrades without an owner tend to stall, which then creates pressure for unmanaged exceptions.
When should you use per-project versions, and when should you avoid them?
Divergence is justified only when a specific constraint forces it, and each exception should carry an owner and an exit date.
| Reason for a per-project version | Justified? | Expected cost |
|---|---|---|
Publishable package supporting a range of consumer versions via peerDependencies |
Yes | Low. Pin dev versions centrally and test against the range's bounds. |
| Legacy service frozen on an old major, scheduled for retirement | Yes, time-boxed | Moderate. Separate lockfile entries and security patching until deletion. |
| Conflicting native or runtime constraints (ABI, platform, engine) | Yes | Moderate. Isolated build and CI path for that project. |
| Code imported from another repo mid-migration | Yes, time-boxed | Moderate. Converges as part of the migration plan. |
| Team prefers autonomy | No | High. Every shared upgrade becomes a negotiation. |
| Skipping a hard upgrade | No | High and growing. The gap widens with each release. |
| Stateful or type-bearing libraries shared across projects | No | Severe. Duplicate instances, mismatched types, and runtime bugs that only appear in integration. |
The shared-library case is the dangerous one. Two copies of an ORM, DI container, or schema library compile without errors but break on instanceof checks and shared registries.
The most common failure is the mixed model. The repo is nominally single-version but tolerates unmanaged exceptions. You still coordinate upgrades across projects, and you also pay for drift, so you carry both costs and get the benefit of neither.
Choose deliberately among three models:
- Strict single-version with a short, documented exception list.
- Per-project versions as the default, accepting heavier upgrade overhead.
- Splitting a frozen service into its own repo, so it stops constraining everyone else.
What are the alternatives to the Nx single version policy?
If strict single-version doesn't fit, these are the main alternatives, roughly ordered from most to least centralized:
- Per-project manifests with package-manager workspaces. npm, Yarn, and pnpm workspaces each let projects declare their own dependencies while sharing one install and one lockfile. Nx's project graph and affected commands still work on top of this. You gain team-level autonomy and pay with possible duplicates and repeated upgrade work, as described above.
- Per-project manifests with targeted forcing. Keep per-project manifests, but force a single version for the packages that must not be duplicated. npm's
overridesfield, Yarn'sresolutionsfield, and pnpm'spnpm.overridessetting all pin a dependency to one version across the install tree. This is a practical hybrid: runtime singletons such as the ORM, framework, and tracing client stay single-version, and leaf utilities can vary per project. The forced version still has to work for every project that uses it, so this approach moves the coordination problem rather than removing it. - Shared version declarations with per-project manifests. Some package managers let projects reference a centrally defined version instead of a literal range. pnpm, for example, supports catalogs for this. Projects keep their own manifests but point to one shared version. Check your package manager's current documentation for availability and exact syntax.
- Peer dependencies for shared libraries. Internal libraries can declare runtime singletons as
peerDependenciesinstead ofdependencies, so the consuming app supplies the single copy. This lowers the risk of duplicate instances inside one process, but it does not stop two apps from using different majors. - Separate repositories. Moving a project with genuinely independent constraints into its own repository removes it from the workspace's version decisions. You lose atomic cross-project changes and shared-code refactoring, and shared libraries then have to be versioned and published.
None of these remove the need for the guardrails below. They change where the version decision is made, not whether someone has to make it.
What guardrails and checklist should you use to decide and enforce a policy?
Whichever model you choose, exceptions need to stay visible. The guardrails below make every divergence a deliberate, owned decision.
Guardrails for exceptions
- Explicit allowlist. Keep a checked-in file (for example,
dependency-exceptions.json) with one entry per divergent package. Each entry records the package name, the allowed versions, the project that needs them, an owner, and an expiry date. Expiry dates matter because they force someone to renew or remove each exception. - CI duplicate check. A short script parses the lockfile and lists packages that resolve to more than one version. It compares that list against the allowlist and fails the build on any duplicate not listed there, or on any entry past its expiry. The same script should flag any newly added
package.jsonunder project directories, so per-project manifests can't appear unnoticed. - Boundary fencing. Tag exception projects (for example,
scope:exception) in their project configuration. In the@nx/enforce-module-boundarieslint rule, adddepConstraintsso projects taggedscope:sharedmay only depend on libraries taggedscope:shared. Single-version code then cannot import a library compiled against a divergent dependency.
Decision checklist
| Factor | Points to single version | Points to per-project |
|---|---|---|
| Number of deployables | Many, similar services | Few, unrelated apps |
| Shared runtime libraries | Yes (ORM, DI, framework) | None |
| Team autonomy and release cadence | Coordinated releases | Independent schedules |
| Publishing needs | Internal consumption only | Packages published to external consumers |
| Central upgrade capacity | Platform team can own upgrades | No central owner |
If most of your answers land in the left column, use the single version policy with the guardrails above. If most land in the right column, per-project versions are defensible, but the CI duplicate check is still worth running.
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 single version policy, 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.