What does each tool own in an Nx pnpm workspace?
An Nx pnpm workspace is two tools with a hard boundary between them. pnpm owns the filesystem. pnpm-workspace.yaml lists which directories are workspace packages. pnpm install resolves every manifest's dependencies, writes pnpm-lock.yaml, and symlinks local packages into each consumer's node_modules. Nx owns the build graph. It reads the same manifests, the lockfile and your source imports to work out which projects depend on which, what each task's inputs are, and what to cache. Nx never installs a package or creates a link.
pnpm-workspace.yaml ─┐
├──> pnpm: resolve ──> pnpm-lock.yaml
package.json (each) ─┤ link ──> node_modules symlinks
│
pnpm-lock.yaml ──────┼──> Nx: project graph ──> task pipeline
source imports ──────┘ ──> cache hashes
Most failures in this setup come from expecting one tool to do the other's job. Here are the common ones:
- Nx sees an import pnpm never linked. If a library imports a package that isn't declared in its manifest, Nx may still draw a graph edge, but at runtime the module isn't there.
- The lockfile disagrees with a manifest. Nx hashes what the lockfile says is installed. If an install was skipped or failed, those hashes no longer match what's actually in
node_modules.
When something breaks, first decide which side of the boundary owns the symptom. Missing modules are a pnpm problem. Wrong rebuilds or stale cache hits are an Nx problem.
This setup suits backend and platform teams running several deployable services and shared libraries in one repository. Those teams need strict dependency isolation per package and fast, cached, graph-aware CI across all of them.
cat > pnpm-workspace.yaml <<'EOF'
packages:
- 'apps/*'
- 'libs/*'
EOF
pnpm add @acme/shared --workspace --filter @acme/orders-api
ls -l apps/orders-api/node_modules/@acme/
pnpm install --frozen-lockfile
pnpm nx show projects
pnpm nx show project orders-api
pnpm nx graph --file=graph.json
pnpm nx build orders-api
Each step runs on one side of the boundary: pnpm declares, links and locks the workspace packages, and Nx only reads the result to build its project graph and cached tasks.
Who should use an Nx pnpm workspace?
The combination fits teams that meet most of these conditions:
- Several projects share code. Typical examples are multiple deployable services, one or more frontends, and shared libraries for logging, database access, API clients or domain types, all changing together.
- CI time or feedback latency is a real cost. If every pull request rebuilds and retests everything, and that takes long enough that developers wait on it, Nx's affected detection and caching have something to remove.
- The team wants dependency mistakes caught early. pnpm's strict layout fails fast on undeclared imports, so you find them during development instead of in a pruned production image.
- Someone owns the build setup. Project graphs, target defaults, named inputs and catalogs need occasional maintenance. A platform or developer-experience owner, even a part-time one, keeps that work from drifting.
It is a weaker fit for a single application with no shared libraries, for repositories with only two or three packages, and for teams whose toolchain depends on a flat node_modules. The last section of this article covers those cases and the alternatives in more detail.
How does an Nx pnpm workspace work, step by step?
A typical cycle, from a fresh clone to a cached CI run, looks like this:
- pnpm discovers packages. It reads
pnpm-workspace.yamland treats every matching directory with apackage.jsonas a workspace package. - pnpm resolves and installs. It resolves every manifest's ranges, including
workspace:andcatalog:specifiers, and records the result inpnpm-lock.yaml. Each package version is stored once in a content-addressable store on disk and linked into the repository'snode_modules/.pnpmdirectory. Each package's ownnode_modulesthen gets symlinks only to the dependencies it declares, and local packages are symlinked directly to their source directories. - Nx discovers projects. It finds projects from
package.jsonfiles and anyproject.jsonfiles. Plugins can infer targets such asbuild,testorlintfrom tool configuration files. - Nx builds the project graph. It combines declared dependencies, lockfile data and the imports it finds in source files into a graph of workspace projects and external packages.
- Nx builds a task graph. When you run a target, Nx expands it using each target's
dependsOnsetting. A common rule is"dependsOn": ["^build"], which means "build my dependencies first". Independent tasks can run in parallel. - Nx hashes each task. The hash covers the task's configured inputs: the project's source files, relevant configuration, the versions of external dependencies it uses, and any other inputs you declare.
- Nx checks the cache. If a task with the same hash has run before, Nx restores its outputs and replays its terminal output instead of running it. Otherwise it runs the task and stores the result.
- Affected commands narrow the scope.
nx affectedcompares two Git revisions, maps changed files to projects, and walks the project graph to find their dependents. Only those projects' tasks run.
pnpm nx affected -t build test --base=origin/main --head=HEAD
pnpm nx run-many -t build
Affected commands decide which projects to run; the cache decides which of those tasks can be skipped entirely.
The rest of this article covers the parts of this cycle that most often go wrong: how local packages are linked, how versions are kept consistent, what happens when declarations are missing, and how lockfile changes feed into steps 6 to 8.
How does the workspace protocol work, and which form should you use?
The workspace: protocol tells pnpm to resolve a dependency only from packages inside the repository. If apps/orders-api/package.json declares "@acme/db": "workspace:*", pnpm symlinks node_modules/@acme/db to libs/db. It never falls back to the registry. If no workspace package named @acme/db exists, or its version does not satisfy the range, the install fails. Plain "@acme/db": "^1.0.0" gives no such guarantee and could silently pull a registry copy.
The three common forms differ only in what pnpm writes when you publish. pnpm replaces each with a concrete range based on the local package's current version, assumed here to be 1.4.2:
| Form | Published as | Use when |
|---|---|---|
workspace:* |
1.4.2 (exact) |
Internal-only packages that never leave the repo |
workspace:^ |
^1.4.2 |
Published libraries following semver |
workspace:~ |
~1.4.2 |
Published libraries where only patch drift is safe |
The * form is convenient because you never edit it. For published libraries, though, it pins consumers to one exact version. That causes duplicate installs and surprising conflicts downstream, so prefer ^ there.
Declare internal dependencies in package.json even when TypeScript path aliases already resolve the imports. Aliases satisfy the compiler, but Nx's dependency graph, pnpm's strict node_modules layout and Node's runtime resolution all read manifests. An explicit declaration keeps these three in agreement. It also prevents code that works only because a sibling package happened to hoist the dependency.
{
"name": "@acme/orders-api",
"version": "0.0.0",
"private": true,
"dependencies": {
"@acme/db": "workspace:*",
"@acme/logger": "workspace:^",
"@acme/money": "workspace:~",
"express": "^4.19.2"
}
}
A package.json for apps/orders-api that declares internal dependencies with each workspace: form; if each local package is at 1.4.2, publishing would write 1.4.2, ^1.4.2 and ~1.4.2.
How do pnpm catalogs keep dependency versions consistent?
Catalogs move version ranges out of individual package.json files and into pnpm-workspace.yaml. The default catalog lives under a top-level catalog key, and consumers reference it with catalog: as the version specifier. Named catalogs live under catalogs, keyed by name, and are referenced as catalog:<name>. Named catalogs are useful when a group of packages needs to move together, such as a set of framework packages that must stay on matching majors. When pnpm publishes or packs a package, it replaces the protocol with the concrete range, so consumers outside the repo never see catalog:.
The main payoff is maintenance. Without catalogs, bumping a shared dependency means editing every manifest that declares it, and any manifest you miss leaves the lockfile resolving two copies. With a catalog, the bump is a one-line change in a single file, and review shows exactly one diff.
To migrate an existing repo:
- List every dependency declared with more than one range across manifests.
- Choose one canonical range for each, usually the newest that all consumers tolerate.
- Convert the high-churn shared dependencies first, such as type packages, test tooling and framework cores. Leave rarely shared packages for later.
The trade-off is coupling. Every consumer of a catalog entry gets the same range. A package that needs a different version has to declare an explicit range or move to a named catalog. Because one bump reaches many projects at once, treat catalog edits as wide-impact changes. Before you migrate, check that your installed Nx version understands the catalog: protocol in its dependency analysis. Don't assume it does.
packages:
- "apps/*"
- "libs/*"
catalog:
typescript: ^5.4.0
vitest: ^1.6.0
"@types/node": ^20.12.0
catalogs:
react18:
react: ^18.3.1
react-dom: ^18.3.1
react19:
react: ^19.0.0
react-dom: ^19.0.0
A pnpm-workspace.yaml that defines a default catalog for shared tooling and two named React catalogs, with comments showing how manifests reference them via catalog: and how a package opts out with an explicit range.
Why do phantom dependencies break builds under pnpm, and how do you fix them?
pnpm gives each package a node_modules that contains only the dependencies that package declares, symlinked into the content-addressed store. Code that imports something it never declared, a phantom dependency, worked under npm or Yarn classic only because the flat layout happened to hoist it. Under pnpm the resolver walks up and finds nothing, so you get Cannot find module at runtime or at build time. These errors often surface in places that are easy to overlook: Jest or Vitest setup files, Babel or PostCSS plugins loaded by name from config, ESLint shareable configs, and generated clients that import a runtime library the generator never added.
To diagnose one, read the require stack or the resolver's error to find the file doing the import, then identify which package owns that file. If it is one of your projects, add the missing dependency to that project's package.json, not the root. If it is a third-party package that forgot to declare a dependency, patch its metadata with pnpm's packageExtensions setting instead of working around it in your own manifest. pnpm why <name> shows who currently pulls the package in.
Avoid fixing this with shamefully-hoist or a broad public-hoist-pattern. Those settings clear the error quickly by restoring a flat layout. The undeclared imports are still there, though. They fail again when you build a pruned, per-service deploy, because that output contains only what each manifest declares.
Some tools still assume a flat tree, mostly older plugin loaders and IDE integrations. For those, a narrow public-hoist-pattern entry that names the specific package is acceptable. Add a comment that explains why the entry exists, and remove it once the tool resolves dependencies correctly.
pnpm why tslib --recursive
pnpm --filter @acme/api-client add tslib
pnpm install
pnpm nx test web
A diagnosis workflow that starts from the require stack, uses pnpm why to trace the package, and adds the missing dependency to the manifest of the package that imports it, with packageExtensions as the fix for third-party packages that omit a dependency.
How should you resolve pnpm-lock.yaml merge conflicts?
A lockfile conflict is a symptom: two branches changed the dependency graph, and pnpm recorded each result separately. Hand-merging the YAML produces a file that no single pnpm install would have generated. It can contain integrity hashes, peer-resolution suffixes, or importer entries that contradict one another. Let pnpm compute the merged graph instead.
A repeatable workflow
- Resolve the inputs first. Fix conflicts in every
package.jsonand inpnpm-workspace.yaml, including catalog entries, by hand. These files express intent, so they are the right place for human judgment. - Take one side of
pnpm-lock.yaml, or delete it. Keeping the target branch's version usually gives a smaller diff, because pnpm only re-resolves what changed. - Run
pnpm installto regenerate the lockfile from the resolved manifests. - Review the lockfile diff before you commit.
The trade-off shows up in step 4. Regeneration can pull in newer transitive versions that the existing ranges allow, so the diff may touch packages that neither branch changed. This is most likely if you discarded the lockfile entirely. Treat that diff as a real dependency update and run the full test suite against it.
CI hygiene
In CI, run pnpm install --frozen-lockfile. An out-of-sync lockfile then fails the job instead of being silently rewritten on the build machine.
Pin pnpm itself with the packageManager field in the root package.json and use Corepack. Different pnpm versions can serialize the same graph differently, which creates churn and spurious conflicts. Corepack adds an onboarding step: it must be available and enabled on every developer machine and in every CI image, or the pin is ignored.
How do lockfile changes affect Nx affected detection and caching?
Nx reads pnpm-lock.yaml to build the external dependency nodes in its project graph. When the lockfile changes, Nx tries to map the change to specific packages and then to the projects that depend on them. How precisely it does this varies. Depending on the Nx version, the plugin configuration, and whether the lockfile or root package.json appears in global inputs (such as a shared named input or an implicit dependency), Nx may decide that every project is affected. The same rules feed the task hash, so a routine patch bump to one logging library can invalidate the cache across the whole repository.
Granular declarations reduce that blast radius. If each project lists only the packages it actually imports in its own package.json, and the lockfile is not a blanket input, a bump to a dependency used by one service changes the hash for that service and its dependents and leaves the rest alone. The phantom-dependency fixes from earlier sections help here too, because accurate declarations give Nx an accurate graph.
Illustrative estimate (assumed inputs): 40 projects, 5 agent-minutes each for build and test, and 10 dependency bumps per month.
- If every bump invalidates all caches: 40 × 5 × 10 = 2,000 agent-minutes per month.
- If each bump touches 3 projects: 3 × 5 × 10 = 150 agent-minutes per month.
These numbers are not measurements. They show how strongly the scope of invalidation affects CI cost.
Check how your own setup behaves. Commit a change that touches only the lockfile, run nx show projects --affected, and compare the list with the projects that actually depend on the bumped package.
How can an Nx pnpm workspace save engineering time?
The time savings come from work that no longer happens, and from failures that surface earlier, when they are cheaper to fix:
- Skipped tasks. A cache hit replaces a full build, test or lint run with an output restore. Locally, switching back to a branch you already built, or rerunning tests after an unrelated change, reuses earlier results. With a shared remote cache configured, CI agents and developers can also reuse each other's results.
- Smaller CI runs.
nx affectedruns tasks only for changed projects and their dependents. A change to one service's handler does not rebuild an unrelated frontend. - Less waiting on ordering. The task graph runs dependency builds first and runs independent tasks in parallel, so nobody hand-maintains build order in shell scripts.
- Faster installs. pnpm stores each package version once in its content-addressable store and links it into projects. Fresh clones and additional worktrees on the same machine reuse that store instead of downloading the same packages again.
- Atomic cross-package changes. A change to a shared library and all its consumers lands in one pull request, reviewed and tested together. With separate repositories, the same change needs a publish, a version bump in each consumer, and several reviews.
- Cheaper dependency upgrades. Catalogs turn a shared version bump into one edit, and the lockfile workflow above keeps the resulting diff reviewable.
- Earlier failures. pnpm's strict layout reports a missing declaration on the developer's machine instead of in a pruned production image, and
--frozen-lockfilestops lockfile drift at the CI install step instead of in a later debugging session.
The savings depend on keeping the graph accurate. Undeclared dependencies, overly broad global inputs and a lockfile that is a blanket input all widen invalidation and erode the cache hit rate. The previous section shows how to check that.
Illustrative estimate (assumed inputs): a team opens 20 pull requests per day, a full CI run on each takes 30 minutes, and a typical pull request affects about a quarter of the workspace's tasks, with half of those restored from cache.
- Without affected detection or caching: 20 × 30 = 600 CI-minutes per day.
- With both: 20 × 30 × 0.25 × 0.5 = 75 CI-minutes per day, plus the fixed overhead of install and cache restores.
These are assumed inputs, not measurements. Your ratios depend on how changes spread through your graph and how often inputs stay unchanged between runs. The developer-time effect is similar: a shorter feedback loop on each pull request means less time waiting for CI.
When should you avoid this setup, and what are the alternatives for deploying one service?
An Nx pnpm workspace earns its overhead when you have many projects and CI time worth saving. A repo with two or three packages rarely recovers the cost of learning project graphs, cache configuration and target defaults. pnpm's strict layout also assumes every package declares what it imports. If the team won't keep those declarations accurate, the fixes from earlier sections turn into a permanent backlog. Some toolchains also break under pnpm's symlinked layout, such as older bundler plugins, native-module build scripts and tools that walk node_modules directly. pnpm's hoisting settings can patch this, but every patch you add moves you further from the isolation you adopted pnpm for.
Alternatives
| Approach | Setup cost | Isolation | Maintenance effort |
|---|---|---|---|
| Plain pnpm workspaces, no Nx | Low | Strict package boundaries, no task caching | Low; you write task orchestration yourself |
| Nx with npm or Yarn | Medium | Depends on the manager's hoisting | Medium; phantom dependencies go unnoticed |
| Separate repositories | Low per repo | Full | High; cross-repo version bumps |
pnpm deploy for one app |
Low | Pruned install of one package | Low |
Nx-generated package.json and lockfile |
Medium | Pruned to the build output's imports | Medium; tied to executor configuration |
Pruned installs for a single service
To ship one service, you want only its dependency closure. pnpm deploy copies a filtered package and its dependencies into a target directory. Some Nx build executors can instead emit a package.json and a pruned lockfile next to the build output.
Either way, workspace: dependencies must resolve to real, installable packages in the pruned output. Otherwise the container fails at install time or at startup. Both commands have changed their flags and defaults across releases, and some versions need extra workspace settings before pnpm deploy will run. Check the documentation for your installed versions before you script either command.
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 pnpm workspace, 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.