How does pnpm's node_modules layout differ from hoisting, and why does it expose phantom dependencies?
In an Nx repo using pnpm workspaces, pnpm-workspace.yaml lists the project folders. Each project keeps its own package.json, and pnpm installs dependencies for all of them in one pass.
pnpm stores every package version once, in a content-addressable store keyed by file content. It then hard-links those files into a virtual store at node_modules/.pnpm. Each package there gets its own node_modules folder, which contains symlinks to only the dependencies it declares. A project's top-level node_modules holds symlinks to its direct dependencies and nothing else. Disk usage stays low because the files are shared. The more important effect is that the layout matches the dependency graph.
npm and Yarn classic work differently. They flatten the tree and hoist transitive dependencies to the root node_modules wherever versions allow. Node resolves an import by walking up parent directories, so with a flat layout any code in the repo can import a package that happens to sit at the root. That includes packages it never declared. These are phantom dependencies. They work until something unrelated changes: a dependency drops its transitive import, a version bump moves a different copy to the root, or the package is published and installed on its own. Then the import fails, often in CI or production rather than on the laptop where it was written.
pnpm's strict layout surfaces these failures at install and build time. The temptation is to restore hoisting to make them go away. The rest of this guide argues for the opposite approach: keep the layout strict, declare what each project imports, and use pnpm's tooling to keep versions consistent across projects.
PNPM: strict, symlinked node_modules
+-------------------------+ hard links +--------------------------------+
| content-addressable |----------->| node_modules/.pnpm (virtual) |
| store, keyed by content | | react@18/node_modules/react |
+-------------------------+ | lodash@4/node_modules/lodash |
+--------------------------------+
^ symlink ^ symlink
| |
+------------------------------+ | |
| apps/web/node_modules/react |-----------+ |
| libs/ui/node_modules/lodash |----------------------------------+
+------------------------------+
apps/web: import 'lodash' -> fails at build (not declared)
NPM / YARN CLASSIC: flat, hoisted node_modules
+--------------------------------------+
| <root>/node_modules (flat) |
| react |
| lodash (hoisted for libs/ui) |
+--------------------------------------+
^ declared ^ phantom: resolves anyway
| |
+-------------+ +---------------+
| libs/ui | | apps/web |
| dep: lodash | | deps: react |
+-------------+ +---------------+
pnpm links each project only to its declared dependencies via the virtual store, so undeclared imports fail; a flat hoisted root lets apps/web silently import lodash it never declared.
What do hoist, public-hoist-pattern, shamefully-hoist and node-linker actually change?
Each setting widens visibility at a different layer. Knowing which layer matters is how you loosen one thing instead of everything.
| Setting | Where packages become visible | Who can see them |
|---|---|---|
hoist (with hoist-pattern) |
node_modules/.pnpm/node_modules |
Other dependencies only, not your source code |
public-hoist-pattern |
Root node_modules, for matching names |
Everything, including every project's source |
shamefully-hoist |
Root node_modules, for every package |
Everything; equivalent to a public pattern of * |
node-linker |
Changes the whole layout: isolated (symlinks), hoisted (flat, npm-style), or pnp (no node_modules) |
Depends on the mode |
hoist is the quiet one. It lets badly packaged third-party libraries find their own undeclared imports, but your code still can't see them. public-hoist-pattern and shamefully-hoist are different: they put packages where Node's resolver, walking up from any project directory, will find them. That brings back phantom dependencies. Defaults for these patterns have changed across pnpm releases, so check what your version ships with.
Strict layout breaks two kinds of tools:
- Tools that assume a flat tree. These include bundlers or native toolchains that don't follow symlinks, and scripts that read
node_modules/<name>directly. - Tools that resolve plugins or peers from the workspace root. Examples are a linter loading plugins relative to a root config, or a framework expecting its peer at the top level.
Fix these with the narrowest setting that works, usually a single named public-hoist-pattern entry. Each entry needs a comment stating which tool requires it, why, and who owns removing it. An undocumented pattern stays forever and keeps hiding missing declarations.
node-linker=isolated
shamefully-hoist=false
hoist=true
hoist-pattern[]=*
public-hoist-pattern[]=
public-hoist-pattern[]=eslint-plugin-example
public-hoist-pattern[]=prettier-plugin-example
A root .npmrc that keeps the strict isolated layout. It allows only private hoisting for badly packaged dependencies. Each public-hoist-pattern entry is a single named exception with a comment naming the tool that needs it, the reason, an owner, and a removal condition.
Single version policy or per-project package.json: which dependency model should your Nx repo use?
With a single version policy, every third-party dependency lives in the root package.json, and projects import whatever the root provides. With per-project manifests, each app and library declares its own dependencies and is listed as a workspace package.
| Concern | Root-only (single version policy) | Per-project package.json |
|---|---|---|
| Best fit | Many apps, nothing published to a registry | Published libraries, independently deployed services |
| Upgrades | One edit, one version everywhere | Same change repeated across many manifests |
| Publishing | Build step must generate a manifest from imports | Manifest already exists |
| Container builds | Installs the whole repo's dependency set | Filtered install of one project's closure |
| Affected precision | Coarse | Close to actual usage |
| Drift risk | None by construction | High without catalogs or lint rules |
Root-only suits teams that want low ceremony and treat the repo as one deployable unit. The cost shows up in CI. A change to the root manifest or lockfile gives Nx little information about which projects use the changed package. Nx may then mark a large share of the graph as affected, so one patch bump can trigger a near-full test run. Container images also carry dependencies the service never loads, unless you prune them at build time.
Per-project manifests give Nx and pnpm an explicit edge from each project to each external package. A lockfile change then maps to the projects that declare that package. This also makes pnpm --filter installs practical for slim images. The cost is in daily development. Engineers must add a dependency to the correct manifest, keep versions in step, and review more files in each upgrade. Without central enforcement, two services can quietly end up on different major versions of the same library.
How do pnpm catalogs and the workspace: protocol enforce versions without hoisting?
Catalogs let you keep per-project manifests and still state each shared version once. You declare a default catalog in pnpm-workspace.yaml that maps package names to version ranges. Each project then lists the dependency with catalog: as its version specifier. An upgrade becomes a one-line change in a single file, and reviewers see the whole blast radius in one diff. Each project still declares only what it imports, so strict isolation stays intact and nothing has to be hoisted to share a version.
Named catalogs, declared under catalogs: and referenced as catalog:<name>, are the escape hatch for a team that can't take a breaking upgrade yet. You can move the default catalog to the new major and point the lagging service at a legacy catalog, so the rest of the repo isn't blocked. The cost is real, though. You have reintroduced the version drift that catalogs exist to prevent, now with official status. Give every alternate catalog an owner and a removal date, or it will become permanent.
Internal libraries use the workspace: protocol, which forces resolution to the local package and fails the install if that package doesn't exist. When you run pnpm publish or pnpm pack, pnpm rewrites both protocols into real ranges. workspace:* becomes the exact version, workspace:^ and workspace:~ become caret and tilde ranges, and catalog: becomes the range the catalog defines. Consumers outside the repo never see these protocols.
Only recent pnpm releases understand catalog:, and an older pnpm will fail to resolve it. Pin the exact pnpm version in the root package.json packageManager field. Use Corepack or your CI setup step so that laptops and pipelines run the same binary.
packages:
- "apps/*"
- "libs/*"
catalog:
react: ^19.0.0
react-dom: ^19.0.0
zod: ^3.23.8
catalogs:
legacy-react:
react: ^18.3.1
react-dom: ^18.3.1
A pnpm-workspace.yaml with a default catalog and a time-boxed named catalog, plus a project manifest that uses catalog: and workspace: specifiers and the ranges pnpm rewrites them to on publish.
How does Nx build its project graph from pnpm workspace dependencies?
Nx builds the project graph from two signals. First, it reads each project's package.json: a dependency declared with workspace:* on another workspace package becomes a static edge between the two projects. Second, it analyzes TypeScript and JavaScript imports in source files and maps each import specifier either to a workspace project or to an external node such as npm:express. Run nx graph and you will see both kinds of edges. If the two signals disagree, for example when code imports a package that the project never declares, the graph still records the edge, but pnpm will fail to resolve the import at runtime. That gap is the phantom dependency problem showing up at the graph level.
Lockfile changes and affected detection
When pnpm-lock.yaml changes, Nx compares the external nodes before and after the change. It marks as affected only the projects that depend on the packages whose resolved versions changed. This works only if each project's dependencies are accurate. If every library depends on a bloated root manifest, a single patch bump marks every library as affected, and CI rebuilds and retests all of them. When each project declares only what it imports, a bump to a logging library affects only the services that log through it. On a large repo, that difference shows up directly in queue time and in the number of runner minutes CI consumes.
Peer dependencies and duplicate singletons
pnpm resolves peer dependencies for each consumer. If two projects satisfy a peer such as react or a DI container with different versions, pnpm creates a separate copy of the dependent package for each peer set. Two copies of a framework runtime break identity checks, shared registries and context objects, often with errors that are confusing to debug.
You can deduplicate these copies in three steps:
- Pin singletons in a catalog so that every project resolves the same version.
- Run
pnpm why <pkg>to find the remaining duplicates. - Run
pnpm dedupeto collapse duplicates where the version ranges already overlap.
Treat a duplicate singleton as a bug to fix at its source. Do not hide it with hoisting.
#!/usr/bin/env bash
set -euo pipefail
pnpm why -r react
npm pkg set pnpm.overrides.react=18.3.1
npm pkg set pnpm.overrides.react-dom=18.3.1
pnpm install
pnpm dedupe
pnpm why -r react
npx nx show projects --affected --base=origin/main
npx nx affected -t build test --base=origin/main
Finds duplicate React copies with pnpm why, pins React to one version with a root pnpm override, and runs Nx affected so only projects that depend on React rebuild and retest.
How does it work end to end?
The pieces above form one pipeline. Here is what happens from a dependency change to a CI result:
- Declaration. An engineer adds a package to the
package.jsonof the project that imports it. Shared third-party versions usecatalog:, and internal libraries useworkspace:. - Resolution.
pnpm installreadspnpm-workspace.yaml, replaces eachcatalog:specifier with the catalog's range, links eachworkspace:dependency to the local package, and applies anyoverrides. It writes the result topnpm-lock.yaml. - Linking. pnpm places package files in the content-addressable store, hard-links them into
node_modules/.pnpm, and symlinks each project's direct dependencies into that project'snode_modules. Private hoisting makes undeclared transitive imports visible only to other dependencies. Namedpublic-hoist-patternentries are the only packages exposed at the root. - Graph construction. Nx reads the project manifests and source imports. It creates edges between workspace projects and from projects to external
npm:nodes. - Change detection. On a pull request, Nx compares the lockfile's external nodes against the base branch. It marks only the projects whose external dependencies changed as affected, along with the projects that depend on them.
- Verification. CI installs with
--frozen-lockfile, runs lint rules that check declarations and module boundaries, and runsnx affectedfor build and test. It also builds and smoke-tests the deploy image.
Each step depends on the previous one being accurate. Strict linking makes undeclared imports fail. Accurate declarations make the Nx graph precise. A precise graph keeps the affected set small.
What are the alternatives?
The pnpm-plus-catalogs approach is one option among several. The main alternatives, and their trade-offs:
- pnpm with
node-linker=hoistedorshamefully-hoist=true. You get npm-style compatibility with no migration work, and you keep pnpm's store and CLI. Phantom dependencies come back, and the Nx graph becomes less trustworthy for affected detection. This is reasonable as a temporary state while tooling issues get fixed. It is a poor permanent target. - npm workspaces. These are built into npm and need no extra binary. The layout is hoisted and flat, so phantom dependencies are possible, and there is no built-in equivalent of catalogs for stating shared versions once. Version consistency then depends on lint rules or review discipline.
- Yarn classic workspaces. Same hoisted model and the same phantom dependency exposure as npm workspaces. Yarn classic is in maintenance mode, so new repos rarely choose it.
- Yarn Berry (v2 and later). With Plug'n'Play it is stricter than pnpm: there is no
node_modules, and undeclared imports fail at resolution. Tools that expect a realnode_modulesdirectory need extra configuration or itsnode-moduleslinker. With thenode-moduleslinker, thenmHoistingLimitssetting can limit hoisting to each workspace, which gives behaviour closer to pnpm's isolation. - Root-only single version policy with any package manager. Covered in the comparison table above. It trades affected precision and slim container builds for one-edit upgrades and no drift.
Choose pnpm's strict layout with catalogs when you want both per-project precision and centrally stated versions without hoisting. Choose a hoisted alternative when tool compatibility matters more than catching undeclared imports, and you accept that the graph will be coarser.
How can it save engineering time?
The savings come from a few specific mechanisms, not from the package manager being faster in general:
- Failures move earlier. A phantom import fails on the developer's machine at build time, not in CI on a different install or in production after a transitive dependency changes. Debugging a "cannot find module" error with the code still open is much cheaper than tracing a production startup failure back to a dependency that moved.
- Smaller affected sets. With accurate per-project declarations, a lockfile change marks only the projects that use the changed package. Fewer projects rebuild and retest, so pull requests wait less in the queue and use fewer runner minutes.
- One-line upgrades with catalogs. A shared version bump is a single edit in
pnpm-workspace.yaml, not a search-and-replace across many manifests. Reviewers see the whole change in one diff, and drift between services doesn't build up into a painful multi-major catch-up later. - Less singleton debugging. Pinning runtimes such as
reactin a catalog, plus a CI check for duplicates, prevents the class of bugs where two copies of a framework break context or identity checks. Those bugs are slow to diagnose because the errors don't point at the cause. - Faster, slimmer deploy builds. Filtered installs with
pnpm --filterinstall one project's dependency closure instead of the whole repo's, which shortens image builds and reduces what each image carries. - Fewer review arguments. Documented
public-hoist-patternentries and overrides, each with an owner and a removal condition, make exceptions explicit. Nobody has to rediscover why a setting exists before deciding whether it can go.
The upfront cost is the migration work described below. The illustrative estimate at the end of this guide shows how to weigh that cost against CI savings for your own repo.
How do you enforce the version policy in CI and handle overrides safely?
Guardrails belong in CI, where they run on every change.
Make CI fail on drift
- Install with
--frozen-lockfile. Ifpackage.jsonandpnpm-lock.yamldisagree, the install fails. It does not quietly rewrite the lockfile. That way the dependency tree you reviewed is the one you test. - Lint dependency declarations. The
@nx/dependency-checksrule flags imports that a project'spackage.jsondoes not declare, plus declared packages it never uses. Under strict linking, those are the exact gaps that pass on one machine and break on another. Pair it with@nx/enforce-module-boundariesso that tags limit which projects may depend on which. - Check singletons. Script a check over the lockfile, or over
pnpm whyoutput, for packages such asreactorgraphql. Fail the build when more than one version resolves.
Keep overrides separate and accountable
Use the overrides field for transitive pins, such as forcing a patched version of a vulnerable nested package. Do not use it to set versions for direct dependencies. Those belong in the catalog. Keeping the two apart makes each override read as a deliberate exception. Attach these details to every entry:
- Reason: the advisory or bug it addresses.
- Owner: the person responsible for it.
- Removal condition: usually "upstream ships the fix."
Review overrides on a schedule. An override nobody remembers can pin a package below a later security fix.
Test the deploy path, not just the workspace
Pruned per-app lockfiles and multi-stage Docker builds resolve dependencies differently from the full workspace install. A package missing from the pruned output only shows up at container start. Build and smoke-test the actual image in CI.
When should you migrate from a hoisted setup, and when should you avoid strict mode?
Migration path
- Turn on the strict layout in a branch. Remove
shamefully-hoistand anynode-linker=hoistedsetting, deletenode_modules, and reinstall. Then run every target, not just affected ones. Skipped projects can still hide phantom imports. - Fix what breaks, one project at a time. Each "cannot find module" error points to a phantom import. Add the package to that project's own
package.jsoninstead of the root one, so Nx and pnpm both see the real edge. If a tool genuinely needs a flat location, add a narrowpublic-hoist-patternentry and track its removal as a separate task. - Move shared versions into a catalog gradually. Start with dependency families that drift most, such as test runners, type packages and framework cores. Migrate one family per PR so a version change is easy to bisect.
When to delay
Wait if your build depends on tools that walk up to a root node_modules, such as bundler plugins or code generators, and you can't patch or configure them. Also wait if nobody can own the breakages for a few weeks. A partly migrated repo with growing hoist exceptions is harder to reason about than a consistently hoisted one.
Illustrative estimate
These inputs are assumed. A repo has 40 projects and 30 phantom imports, and each import takes about 20 minutes to fix. Add two days for tooling issues, and the total is about three engineer-days.
The return comes from dependency bumps. Assume six bumps per month that currently invalidate the whole 40-minute pipeline. With per-project declarations, each bump would touch around a quarter of the projects. That saves roughly three CI hours a month, so the main benefit is correctness, with the time savings a smaller gain.
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 workspaces, 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.