How do npm, pnpm and Yarn Berry lay out node_modules in an Nx workspace?

npm and Yarn classic both hoist dependencies. They resolve the whole workspace, then flatten as many packages as possible into the root node_modules. Workspace members such as libs/shared are symlinked there too. Node's resolver walks up parent directories, so every service can require anything that landed at the root, including packages it never declared.

pnpm keeps one copy of each package version in a global content-addressable store and hard-links those files into node_modules/.pnpm. Each project's own node_modules holds only symlinks to its declared dependencies. The layout is deliberately non-flat, so undeclared imports fail at resolution time instead of working by accident.

Hoisted (npm / Yarn classic)        pnpm (isolated, symlinked)
node_modules/                       node_modules/.pnpm/
  express/                            express@x/node_modules/express  <- hard links to store
  lodash/   <- used by shared only    lodash@y/node_modules/lodash
  @org/shared -> libs/shared        apps/api/node_modules/
apps/api/      (resolves both)        express -> ../../.pnpm/express@x/...
apps/worker/   (resolves both)        @org/shared -> ../../libs/shared
                                    apps/worker/node_modules/
                                      @org/shared -> ../../libs/shared
                                      (no express, no lodash)

Yarn Berry goes further. By default it uses Plug'n'Play: there is no node_modules, and a generated .pnp.cjs map tells Node where each package lives. You can opt back into a conventional tree by setting nodeLinker: node-modules in .yarnrc.yml.

Declaring workspaces

  • npm and Yarn list workspace globs in the workspaces field of the root package.json.
  • pnpm reads them from the packages list in pnpm-workspace.yaml.
  • pnpm and Yarn Berry support the workspace: protocol, such as "@org/shared": "workspace:*". This forces resolution to the local library and is rewritten to a real version on publish.
  • npm has no workspace: protocol. It links a local package when the declared range matches the workspace version.
# npm / Yarn: workspace globs live in the root package.json
cat > package.json <<'EOF'
{
  "name": "org-monorepo",
  "private": true,
  "workspaces": ["apps/*", "libs/*"]
}
EOF

# pnpm: ignores the workspaces field and reads pnpm-workspace.yaml instead
cat > pnpm-workspace.yaml <<'EOF'
packages:
  - "apps/*"
  - "libs/*"
EOF

# A service depends on the internal library through the workspace protocol.
# pnpm and Yarn Berry always link the local package and never fall back to the registry.
# npm does not support "workspace:"; with npm, use a version range that
# libs/shared satisfies (for example "*"), and npm links the local copy.
cat > apps/api/package.json <<'EOF'
{
  "name": "@org/api",
  "private": true,
  "dependencies": {
    "@org/shared": "workspace:*",
    "express": "^4.19.0"
  }
}
EOF

# Yarn Berry: opt out of Plug'n'Play and get a conventional node_modules tree
cat > .yarnrc.yml <<'EOF'
nodeLinker: node-modules
EOF

Shows where each tool reads its workspace globs (the root package.json workspaces field versus pnpm-workspace.yaml), how a service links an internal library with the workspace: protocol, and how Yarn Berry's nodeLinker setting restores a node_modules layout.

Why do phantom dependencies matter more for backend services?

Consider an orders-api service whose code imports debug for logging. Nobody added debug to the service's dependencies; it arrives transitively because Express depends on it. Under npm's hoisted layout, debug sits in the root node_modules, so Node's resolver finds it by walking up the directory tree. Locally and in unit tests, the code works.

The problem appears when the service leaves the workspace. Backend services are usually shipped as a pruned install, a container image built from a generated manifest, or a bundle that marks node_modules as external. Each of these packages only what the service declares. The undeclared debug is not there, and the process fails at startup with Error: Cannot find module 'debug'. If the import sits in a rarely used code path, it fails later, on the first request that reaches it. A frontend bundle would inline the module at build time and hide the gap. A Node service resolves modules at runtime, in the environment you deployed, so the gap shows up in production.

Under pnpm's isolated layout, orders-api can see only the packages it declares. debug stays inside Express's own dependency folder. The same import fails with the same Cannot find module error on the first local run, test or build after pnpm install. The fix is a one-line dependency declaration, made before the code is merged.

Strict resolution does not prevent the mistake. It moves the failure from a deployed service to a developer's machine or a CI job. This is the main reason to make pnpm the default for backend monorepos.

# Assumes apps/orders-api has its own package.json with "name": "orders-api"
# that declares express but NOT debug.
#
# apps/orders-api/src/logger.js contains the undeclared import:
#   const debug = require('debug')('orders-api:http');

# --- npm (hoisted layout) ---
# debug is hoisted to the root node_modules as a dependency of express,
# so Node finds it by walking up the directory tree. The bug stays hidden.
npm install
node apps/orders-api/src/main.js     # starts normally

# --- pnpm (isolated layout) ---
# apps/orders-api/node_modules links only the declared packages.
# debug exists only inside express's own dependency folder in the store.
rm -rf node_modules apps/*/node_modules
pnpm install
node apps/orders-api/src/main.js
# Error: Cannot find module 'debug'
# Require stack:
# - /repo/apps/orders-api/src/logger.js
# ...

# The fix is to declare the dependency on the service that uses it.
# This is a one-line change to apps/orders-api/package.json.
pnpm --filter orders-api add debug
node apps/orders-api/src/main.js     # starts normally

# A pruned install, a container image, or a bundle with external
# node_modules now includes debug, because the service declares it.

The same undeclared require('debug') runs under npm's hoisted layout but fails with Cannot find module after pnpm install, so the fix of declaring the dependency happens locally instead of after deployment.

How does Nx use the package manager and its lockfile?

Nx does not install packages itself, but it reads the package manager's output closely. When it needs to run an install or add a dependency, it detects which package manager to use by looking for a lockfile at the workspace root: package-lock.json means npm, pnpm-lock.yaml means pnpm, and yarn.lock means Yarn. A stray second lockfile left over from an experiment can confuse that detection, so delete it rather than ignore it.

The lockfile also feeds the project graph. Nx parses it to create nodes for external packages and to record which resolved versions each project depends on. Those resolved versions become part of task hashes. If a lockfile change bumps a transitive dependency of orders-api, the cache keys for that service's build and test tasks change, and nx affected can treat it as touched even though no source file changed. This is why the lockfile format matters for caching: Nx can only hash what it can parse.

The same parsing makes deployment artifacts possible. Build executors that support generating a package.json produce a pruned manifest and lockfile for a single app. The pruned files contain only the dependencies that app actually uses, which keeps container images small and installs reproducible.

All of this depends on Nx's parser for each lockfile format. Less common setups, such as unusual pnpm workspace protocols, patched packages or Yarn Plug'n'Play, may be handled differently across Nx releases. Check the pruned output and affected results against the Nx version you run before relying on them.

pnpm vs npm vs Yarn Berry: which should a backend team choose?

The differences that matter for a backend monorepo are module resolution strictness and what you trade for it in tooling friction.

npm pnpm Yarn Berry
node_modules layout Flat and hoisted Symlinks into a content-addressable store Plug'n'Play (.pnp.cjs) by default, node-modules linker optional
Strictness Low: undeclared packages resolve if hoisted High: only declared dependencies resolve Highest under PnP: undeclared requires throw
Workspace declaration workspaces in package.json pnpm-workspace.yaml workspaces in package.json
Frozen install npm ci pnpm install --frozen-lockfile yarn install --immutable
Cache User-level npm cache Global store, hard-linked into projects .yarn/cache in the repo or a global cache, depending on config
Native modules Works as expected Usually fine; some tools need hoisting overrides Builds may need unplugging; tools reading paths can break
Onboarding friction None Low Higher: editor SDKs, PnP-aware tooling
Nx lockfile pruning Supported Supported Supported; verify PnP edge cases

pnpm is the strongest default. Strict resolution makes a missing dependency fail in development instead of inside a pruned production image. Hard links from a shared store keep disk use flat as the number of services grows.

npm has the lowest friction. It ships with Node, and new hires, base images and third-party tooling already assume it. The cost is that hoisting hides phantom dependencies. Only choose npm if you will catch those another way, for example with a lint rule that checks imports against declared dependencies.

Yarn Berry only pays off if you commit to Plug'n'Play or zero-installs on purpose. Before choosing it, budget for:

  • editor SDK setup
  • packageExtensions and patches for packages that don't declare their dependencies correctly
  • extra CI configuration
  • repository growth from committed cache archives, if you use zero-installs

If you would run Yarn Berry with the node-modules linker, you have taken on that overhead for little gain over pnpm.

Does install speed actually change your CI cost?

pnpm saves time and disk in a specific way. It keeps one content-addressable store per machine and hard-links files into each node_modules, so a package version is downloaded and written once and then reused. On a developer laptop with several clones or branches, this saves a lot. On an ephemeral CI runner the store starts empty, so the benefit only appears if you cache the store between runs. When every package manager restores a warm cache, all of them mostly do local file work, and the speed gap narrows.

Scenario Where pnpm helps Gap vs npm
Local, many checkouts Shared store, hard links Large (disk and time)
CI, cold runner, no cache Parallel fetch only Moderate
CI, warm cache restored Linking vs copying Small

Illustrative estimate (assumed numbers, not a benchmark)

Formula: minutes saved per month = runs × install steps per run × (old install − new install)

Assume 2,000 pipeline runs per month, 3 jobs per run that each install, and warm installs dropping from 1.5 to 1.0 minutes. That gives 2,000 × 3 × 0.5 = 3,000 runner-minutes saved.

Now assume each run spends 20 minutes on build, test and lint, and Nx affected-only execution plus remote cache hits cut that to 8 minutes. That gives 2,000 × 12 = 24,000 runner-minutes saved.

With these inputs, task caching saves eight times more than the faster installs. If you pick a package manager only for install speed, you are tuning the smaller part of your CI bill.

Your inputs will be different. Time cold and warm installs on your own repository and CI runners, and use those numbers instead of published comparisons.

How do you set up CI and Docker builds for each package manager?

Commit the lockfile and make CI fail if it drifts from the manifests. Use npm ci, pnpm install --frozen-lockfile or yarn install --immutable. A frozen install refuses to rewrite the lockfile, so a developer who edited package.json without reinstalling breaks the build immediately, before a production image is built from an unreviewed dependency tree.

Cache the package manager's download store, not node_modules. For npm, that is the npm cache directory (~/.npm by default). For pnpm, it is the content-addressable store; pnpm store path prints its location. For Yarn Berry, it is the Yarn cache, which is .yarn/cache unless the global cache is enabled. Key the cache on a hash of the lockfile. Restoring node_modules directly skips the install, along with its integrity checks and lifecycle scripts, and pnpm's hard links do not survive most cache archive formats.

For Docker, enable the build executor's option to generate a package.json for the service, and a pruned lockfile where the executor supports it. Use a multi-stage build. The first stage copies only those two files and runs a frozen install, so the layer stays cached until dependencies change. The second stage copies the built output and the installed dependencies onto a slim runtime image.

Symlinked node_modules

pnpm's layout causes problems wherever tools assume plain directories:

  • COPY steps: Install inside the image rather than copying a host node_modules. A partial copy leaves broken symlinks.
  • Bundlers: Check how your bundler resolves symlinks. Resolving to real paths can produce duplicate module instances.
  • File watchers: Some watchers do not follow symlinks.
  • Serverless packaging tools: Some of these zip node_modules naively.

If any of these tools breaks, set node-linker=hoisted for that build only.

# Build context: the workspace root, after CI has run `nx build api`
# with generatePackageJson enabled, so dist/apps/api contains main.js,
# a pruned package.json and (where the executor supports it) a pruned lockfile.

# Stage 1: install production dependencies only.
FROM node:22-slim AS deps
WORKDIR /app
# Corepack ships with this Node image and provides the pnpm binary.
RUN corepack enable
# Copy only the manifest and lockfile. This layer stays cached until
# the service's dependencies change.
COPY dist/apps/api/package.json dist/apps/api/pnpm-lock.yaml ./
# Install inside the image instead of copying a host node_modules.
# A frozen install fails if the lockfile and manifest disagree.
RUN pnpm install --frozen-lockfile --prod

# Stage 2: slim runtime with the built output and installed deps.
FROM node:22-slim AS runtime
WORKDIR /app
ENV NODE_ENV=production
# Copy the whole node_modules tree, including node_modules/.pnpm.
# pnpm's symlinks are relative, so they stay valid when the tree is
# copied intact. Copying only part of it would leave broken links.
COPY --from=deps /app/node_modules ./node_modules
COPY dist/apps/api/ ./
USER node
CMD ["node", "main.js"]

A two-stage Dockerfile for one Nx service. It runs a frozen pnpm install against the Nx-generated package.json and lockfile inside the image, then copies the complete symlinked node_modules tree and the built output onto a slim runtime image.

When should you avoid pnpm's strict mode or Plug'n'Play?

Strictness has a cost, and it falls on tools written with a flat node_modules in mind. Native modules built with node-gyp sometimes resolve prebuilt binaries or headers by relative path. Some ORMs generate a client into node_modules and expect it to be found from anywhere in the tree. Code generators and older CLIs often require() packages they never declared, because under npm those packages were always hoisted to the root.

On pnpm, this shows up on day one. A repo that has quietly depended on hoisting will fail to build right after the switch, often in several projects at once. Each failure is a real undeclared dependency, but finding and fixing them all takes time.

The escape hatches are graded:

  • public-hoist-pattern: Hoists only the packages you name. This is the narrowest fix.
  • shamefully-hoist: Hoists everything into the root.
  • node-linker=hoisted: Drops symlinks entirely and produces an npm-style flat tree.

Yarn Berry's equivalent is nodeLinker: node-modules, which replaces Plug'n'Play with a conventional layout. Each step up the ladder hands back more of the isolation you switched for. With full hoisting, phantom dependencies return, and you keep mostly the content-addressable store and the faster installs. Prefer declaring the missing dependency, or a targeted package extension, over global hoisting.

Zero-installs deserves separate scrutiny. Committing .yarn/cache means every dependency bump adds or replaces binary archives in Git. The repository grows permanently, clones get slower, and a one-line version change arrives in review alongside a wall of zip files nobody can meaningfully read. For most backend teams with a warm CI cache, that trade is not worth it.

# .npmrc at the workspace root (pnpm)
# Escape hatches, narrowest first. Enable only the first step that works.
# Before any of these, try declaring the missing package in the project
# that actually requires it.

# Step 1: hoist only the named packages into the root node_modules.
# Setting this replaces pnpm's default pattern list, so re-add any
# defaults you still rely on.
public-hoist-pattern[]=*legacy-codegen*
public-hoist-pattern[]=@example/orm-client

# Step 2: hoist everything into the root node_modules.
# Phantom dependencies resolve again, so undeclared requires stop failing
# and stop being caught.
# shamefully-hoist=true

# Step 3: no symlinks, npm-style flat tree.
# Most isolation is gone. You mainly keep the content-addressable store
# and install speed.
# node-linker=hoisted

# Yarn Berry equivalent, in .yarnrc.yml (not this file):
#   nodeLinker: node-modules

A pnpm .npmrc that lists the hoisting escape hatches from narrowest to broadest, with comments on how much isolation each step gives up.

How do you migrate an existing Nx repo from npm to pnpm?

Treat the switch as a dependency upgrade, not a tooling swap. Changing package managers regenerates the lockfile, and the new resolver can pick different transitive versions than npm did, even when every range in package.json is unchanged. Run it on its own branch, with no other changes, so any behavior difference can be traced back to the migration.

  1. Generate the new lockfile deliberately. pnpm import can build pnpm-lock.yaml from the existing package-lock.json, which keeps more of the resolved versions you already run in production. Once you have it, delete package-lock.json and every node_modules directory, including nested ones in apps and libs, so no npm-era layout leaks into the first install.
  2. Declare the workspace. Add pnpm-workspace.yaml listing the globs where your projects live. Convert any internal package references to the workspace: protocol so local libs resolve to the source in the repo, not to a registry copy.
  3. Fix what strict mode exposes. Builds or startup will now fail on imports that only worked because npm hoisted them. Add each one as an explicit dependency of the project that uses it. Avoid blanket hoisting overrides, because those bring back the problem you are migrating away from.
  4. Pin the version. Set the packageManager field in the root package.json and enable Corepack locally and in CI. This stops developers and pipelines from producing lockfiles that differ in format.
  5. Re-verify Nx. Run nx reset, then run the full affected graph twice. Confirm that the second run hits the cache, and diff the project graph against main to catch any dependency edges that changed.

Before merging, run the complete test suite and a staging deploy.

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 pnpm vs npm nx monorepo, 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.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

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.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • 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.