How does pnpm lay out node_modules in an Nx pnpm workspace?

pnpm stores every package version once in a global content-addressable store, keyed by file content hashes. Installing into a workspace hard-links those files rather than copying them, so ten Nx projects that depend on the same library version share one set of files on disk.

Inside the workspace, pnpm builds a virtual store at node_modules/.pnpm. Each package version gets its own directory, such as name@version/node_modules/name, with its own dependencies symlinked beside it. A project's node_modules then contains symlinks only to the packages that project's package.json declares. Node's resolver walks up directories, finds only those symlinks, and fails on anything undeclared. That failure is the point: it makes phantom dependencies visible.

npm and Yarn classic instead hoist the dependency tree into a single flat root node_modules. Any transitive package that lands at the root becomes importable from any project, whether or not that project declared it.

In pnpm, dependency hoisting has three levels:

  • Hidden hoisting (hoist-pattern): packages are hoisted into node_modules/.pnpm/node_modules. Only packages inside the virtual store can resolve them, so badly behaved libraries still work while your source code stays strict.
  • public-hoist-pattern: matching packages are hoisted to the root node_modules, where your code can see them.
  • shamefully-hoist=true in .npmrc: everything is hoisted publicly, which approximates the flat layout.

Some tools assume a flat layout. Plugin loaders that resolve peers from the repository root, or build tools that walk node_modules directly, may push you toward loosening these settings. Each public hoist lets a project import a package it never declared. Builds then pass locally and break when that service is deployed alone.

hoist-pattern[]=*

public-hoist-pattern[]=*eslint*
public-hoist-pattern[]=*prettier*

A workspace-root .npmrc showing pnpm's three hoisting levels: hidden hoisting through hoist-pattern, a narrow public-hoist-pattern for root-resolving tools, and shamefully-hoist commented out because it restores phantom dependencies.

How does an Nx pnpm workspace work end to end?

pnpm and Nx split the work. pnpm owns installation and module resolution. Nx owns the project graph and task execution. Neither replaces the other, and both choices described in this article (single version policy or per-project manifests) sit on top of the same pipeline.

  1. Workspace discovery. pnpm-workspace.yaml lists glob patterns such as apps/* and libs/*. Every matching directory with a package.json becomes a workspace package. Nx discovers projects from project.json files and, through its package.json integration, from workspace package.json files.
  2. Install. pnpm install at the root resolves every manifest in the workspace together and writes one pnpm-lock.yaml at the root. It then builds the virtual store and per-project symlinks described above. Under a single version policy most packages are declared at the root; with per-project manifests each project gets its own declared set. Either way there is one lockfile.
  3. Project graph. Nx reads project configuration, analyzes source imports, and reads manifests to produce a graph. Internal edges connect projects to each other (from imports, workspace: dependencies, or explicit implicitDependencies). External nodes represent npm packages, with versions taken from the lockfile.
  4. Task hashing. Before running a target such as build or test, Nx computes a hash from the target's configured inputs: the project's files, the outputs of the projects it depends on, relevant external package versions, and any named or global inputs. If that hash matches a previous run, Nx restores the cached output and terminal log instead of running the task.
  5. Affected detection. nx affected -t <target> compares the git diff between a base and head commit against the graph, finds the projects touched by the changed files, and adds everything that depends on them. Only those projects run.

The dependency strategy you choose changes steps 3 to 5. It decides where a version bump shows up as a file change, which projects hash it as an input, and therefore how much of the workspace a single dependency edit rebuilds.

What is the single version policy and why is it the default for backend teams?

In the single version policy, the root package.json declares every third-party dependency and its version, and every app and library in the workspace resolves against that one list. pnpm installs a single copy of each package, so express, pg, or your ORM exist once in the store and once in the lockfile.

Backend teams default to this model for three reasons:

  • One coordinated upgrade. Bumping a framework is one change to one manifest and one lockfile. CI then tests every affected service against the new version together.
  • No duplicate copies. Two services never pull slightly different patch versions of the same client library, so a shared library is never built against one version and run against another.
  • Fewer identity bugs. Libraries that rely on module-level singletons, such as DI containers, logger registries, or ORM metadata stores, break when two copies load in one process. instanceof checks fail across copies because each copy defines its own class. A single version removes this whole category of bugs.

A single root manifest does not record which project uses which package, so Nx builds that mapping itself. The project graph reads each project's imports and links them to external package nodes resolved from the lockfile. For projects that keep their own manifest, the @nx/dependency-checks ESLint rule compares actual imports against declared dependencies. It flags packages that are missing, packages that are declared but unused, and versions that drift from the root.

The policy has two costs:

  • One blocked service stalls upgrades for everyone. If a single service can't move to a new major version, the whole workspace waits on it or carries a workaround.
  • Ownership of dependencies is unclear. A root manifest with a hundred entries doesn't say who added a package, who depends on it, or who should approve removing it.
// libs/shared-db/eslint.config.mjs
// Lint config for a buildable library that keeps its own package.json.
// The rule checks that manifest against the library's real imports.
import baseConfig from '../../eslint.config.mjs';

export default [
  ...baseConfig,
  {
    // The rule lints the project's package.json, so it needs a JSON parser.
    files: ['**/*.json'],
    languageOptions: {
      parser: await import('jsonc-eslint-parser'),
    },
    rules: {
      '@nx/dependency-checks': [
        'error',
        {
          // Fail when code imports a package the manifest does not declare.
          checkMissingDependencies: true,
          // Fail when the manifest declares a package nothing imports.
          checkObsoleteDependencies: true,
          // Fail when a declared version range drifts from the root package.json.
          checkVersionMismatches: true,
          // Ignore test and config files so dev-only imports are not counted.
          ignoredFiles: ['{projectRoot}/**/*.spec.ts', '{projectRoot}/eslint.config.mjs'],
          // Packages that are provided at runtime and must not be declared here.
          ignoredDependencies: [],
        },
      ],
    },
  },
];

// Run it for this project only:
//   npx nx lint shared-db

An ESLint flat config that enables the @nx/dependency-checks rule on a library's package.json, so missing, unused, and version-drifted dependencies are flagged against the library's actual imports and the root manifest.

How does a package.json per project work, and when should you use it?

In this model every app and library is a pnpm workspace package with its own package.json. Internal dependencies are declared with the workspace: protocol, so pnpm symlinks the local package rather than fetching it from a registry. Each project's node_modules holds only what its manifest declares. A service that never listed axios cannot import it. Nx reads these manifests to build the project graph, so the declared edges and the graph stay aligned.

Who benefits

  • Multiple teams with clear ownership. A team can bump a dependency for its own service without coordinating a workspace-wide upgrade. The manifest is a reviewable record of what that service depends on.
  • Publishable libraries. A package going to a registry needs an accurate dependencies and peerDependencies list. If those are generated from a root manifest after the fact, they tend to be wrong.

What it costs

  • Version drift. Ten manifests can end up pinning four versions of the same logger, and nothing forces them back together.
  • Duplicate installs. pnpm's content-addressable store deduplicates files on disk, but each distinct version still gets installed and resolved separately.
  • Peer dependency conflicts. Two libraries resolved against different framework versions can produce two instances at runtime. This breaks singletons and instanceof checks.
  • Review overhead. More manifests mean more files to touch and review on every upgrade.

Middle ground

pnpm catalogs let you define a version once in pnpm-workspace.yaml and reference it from each project manifest with catalog:. Projects keep their own dependency lists, and the versions stay centralized. For transitive packages you don't declare directly, root-level pnpm.overrides can force a single resolution across the workspace.

packages:
  - "apps/*"
  - "libs/*"

catalog:
  react: ^18.3.1
  react-dom: ^18.3.1
  pino: ^9.5.0
  zod: ^3.23.8

A pnpm catalog centralizes shared versions in pnpm-workspace.yaml. Each project keeps its own manifest and references those versions with catalog:, internal packages are linked with workspace:*, and a root pnpm.overrides entry pins a transitive dependency.

How does each model affect Nx affected builds, caching and CI cost?

Whether a dependency edit stays cheap depends on how far Nx propagates it. Nx maps each external package to the projects that import it, so a version bump in the root package.json can in principle stay narrow. In practice, the blast radius often widens. A shared dependency like a logger or ORM touches most backend services. Many workspaces also list the root package.json or pnpm-lock.yaml in global inputs or implicit dependencies. When that happens, every lockfile change invalidates every cached task and marks every project affected. Affected-only CI then degrades to a full run on every dependency PR.

Per-project manifests make the edit itself project-scoped. Bumping a package in apps/billing/package.json is a file change inside one project, and Nx can attribute it precisely. The cost is more tracked inputs: more manifests to keep consistent, more files in each project's hash, and drift that the single version policy would have prevented.

Concern Single version policy Per-project package.json
Blast radius of a bump Every importer, or everything if the lockfile is a global input Projects whose manifest changed
Cache invalidation Broad Narrow
Maintenance overhead One manifest N manifests plus a sync check

Illustrative estimate (assumed numbers, not a benchmark). Formula: weekly CI minutes = dependency PRs × affected projects × minutes per project.

The assumed inputs are 40 projects, 10 dependency PRs per week, and 2 minutes per project:

  • Root model, worst case with the lockfile as a global input: 10 × 40 × 2 = 800 minutes.
  • Per-project model, averaging 3 affected projects per PR: 10 × 3 × 2 = 60 minutes.

Weigh the saved CI time against the engineer time spent reconciling version drift across manifests.

How can this setup save engineering time?

CI minutes are the visible cost. Engineer time is the larger one, and it goes to waiting on pipelines, chasing failures that only appear in deployment, and doing upgrades by hand. An Nx pnpm workspace reduces each of these, provided the dependency model is set up deliberately.

  • Less waiting on CI. nx affected limits runs to changed projects and their dependents, and the task cache replays results whose inputs have not changed. With a remote or shared cache, a task that already ran on one machine or CI agent does not run again on another. The win depends on keeping inputs narrow: avoid putting the lockfile or root package.json in global inputs unless you need it.
  • Fewer deployment-only failures. pnpm's strict layout makes an undeclared import fail on a developer machine, not in a pruned container. Debugging a missing module locally, with a stack trace in front of you, is far cheaper than diagnosing a crash loop after a release.
  • Faster installs and cheaper clean checkouts. The content-addressable store and hard links mean a package version already in the store is linked rather than downloaded and copied again. Switching branches or recreating node_modules does less work than a copy-based install.
  • Mechanical upgrades. nx migrate combined with --run-migrations applies code changes for Nx plugins and supported frameworks automatically, so an upgrade becomes reviewing a diff instead of editing every project by hand. Catalogs reduce a shared version bump to one line.
  • Less time on dependency archaeology. nx graph shows which projects use which package, and pnpm why explains how a package ended up in a project's tree. With @nx/dependency-checks failing CI, manifests stay accurate, so questions like "can we remove this package?" have a fast answer.

Illustrative estimate (assumed numbers, not a measurement). Assume a team of 8 engineers, each opening 5 PRs per week, with a full CI run assumed to take 25 minutes and an affected, partly cached run assumed to take 8 minutes. If an engineer waits on half of those runs, the assumed wait time drops from 8 × 5 × 0.5 × 25 = 500 minutes to 8 × 5 × 0.5 × 8 = 160 minutes per week. Replace every input with your own figures. The structure of the calculation matters more than these numbers.

None of this happens by default. A workspace with broad global inputs, shamefully-hoist=true, and unchecked manifests keeps the costs of a monorepo and loses most of these savings.

How do you deploy a single backend service without phantom dependencies?

Two mechanisms produce a pruned deployable. Nx's Node build executors can emit a package.json for the app. Under a single version policy, they infer that manifest from the project graph, copying the versions in the root manifest and lockfile for whatever the bundle imports. In the per-project model you already have a manifest, and pnpm deploy or a filtered install copies the app with only its declared dependency closure into a standalone directory.

Both approaches depend on the declared or detected dependency list being complete. A phantom dependency is a package your code imports without declaring it. It works locally because the root manifest installs it for everyone, or because a hoisting setting exposes it at the top of node_modules. In the pruned container that package is absent, and the service crashes on first import, sometimes long after startup.

Static analysis misses imports that are resolved at runtime. Examples include require(variableName), database drivers selected from a connection string, logger transports named in config, and framework plugins loaded through optional peer dependencies. None of these show up in the import graph, so neither Nx inference nor your manifest will include them.

You catch these before production by treating the pruned artifact as the thing under test:

  • Smoke-test the real image in CI. Build it, boot it, and exercise each code path that loads modules dynamically, such as each configured driver or plugin.
  • Lint per-project manifests. Nx's @nx/dependency-checks rule flags imports that are missing from a project's package.json.
  • Declare runtime-loaded packages explicitly. Add them to the app's manifest, or add a static import so the graph sees them.
#!/usr/bin/env bash
set -euo pipefail

APP=orders-api            # workspace package name of the service
OUT="dist/deploy/$APP"    # standalone output directory

rm -rf "$OUT"
pnpm --filter "$APP" deploy --prod "$OUT"

RUNTIME_MODULES=(pg mysql2 pino-pretty)

missing=0
for mod in "${RUNTIME_MODULES[@]}"; do
  if ! (cd "$OUT" && node -e "require.resolve('$mod')" >/dev/null 2>&1); then
    echo "MISSING in $OUT: $mod (add it to apps/$APP/package.json)" >&2
    missing=1
  fi
done
[ "$missing" -eq 0 ] || exit 1

(cd "$OUT" && timeout 15 node dist/main.js --smoke-test)
echo "pruned artifact for $APP resolves all runtime-loaded modules"

A CI script that produces a pruned deployable with pnpm deploy, then resolves a hand-maintained list of runtime-loaded modules and boots the app from inside that directory, so phantom dependencies fail the build instead of production.

How do upgrades differ between the two models?

Under a single version policy, an upgrade is one event. nx migrate updates the root package.json and writes a migrations file. nx migrate --run-migrations then applies code changes across every project. The result is one large PR that marks nearly every project as affected. You pay for one heavy CI run and one careful review, and then you are done. The cost is coordination. If one service cannot take a breaking major yet, the whole repo waits. The other option is a time-boxed escape hatch: that service gets its own package.json pinning the old version, plus a tracked deadline to remove it.

Per-project manifests let teams upgrade when they are ready. Without guardrails, those staggered upgrades turn into permanent drift. pnpm catalogs help here. You define a version once in pnpm-workspace.yaml, and projects reference it. A named catalog can hold the "previous major" for laggards, which makes the lag visible and easy to search for. Overrides are the blunt tool. They force a single version across the whole graph, which suits transitive security fixes that no team should be able to opt out of.

Aspect Single version policy Per-project upgrades
PRs per bump One, large Many, small
Review effort Concentrated, once Repeated changelog reading
Blocked service Blocks everyone or needs exception Stays on old catalog
Drift risk Low High without catalogs

The hybrid model keeps tooling at the root (Nx plugins, linters, test runners, TypeScript) and runtime dependencies per project. It only holds if the rules are written down:

  • Which category each dependency belongs to.
  • Who owns the catalog.
  • The maximum allowed version lag.
  • That @nx/dependency-checks fails CI rather than just warning.

Without those rules, the split erodes one convenient root install at a time.

What are the alternatives to an Nx pnpm workspace?

The two dependency models above are not the only options. If neither fits, these are the main alternatives, each with a different trade-off.

  • Nx with npm or Yarn workspaces. Nx works with other package managers, and both dependency models still apply. The main difference is layout: npm and Yarn classic hoist into a flat root node_modules, so phantom dependencies resolve silently and only surface at deploy time. You rely more heavily on @nx/dependency-checks and pruned-artifact tests to catch them.
  • Yarn with Plug'n'Play. Yarn's Plug'n'Play mode replaces node_modules with a resolution map and is also strict about undeclared dependencies. Tools that expect a physical node_modules directory may need configuration or Yarn's node-modules linker, which gives up the strictness.
  • pnpm workspaces without Nx. pnpm can run scripts across packages with pnpm -r run <script> and select packages with --filter, including filters based on changes since a git ref. You keep the strict layout and catalogs, but lose Nx's project graph from source imports, computation caching, code generators, and nx migrate. This is a reasonable fit for small workspaces where full rebuilds are cheap.
  • A single package with internal folders. One package.json, one build, and TypeScript path aliases or relative imports between folders. This is the simplest setup and is effectively a single version policy with no project boundaries. It stops scaling once you need independent deploys or affected-only CI.
  • Polyrepo. Each service lives in its own repository with its own lockfile, and shared code is published to a registry. Version isolation is complete and ownership is unambiguous, but every change to shared code becomes a publish-and-bump cycle across repositories, and nothing keeps versions converging.

The choice between these usually comes down to the same factors as the single-version-versus-per-project decision: how many teams share code, how often shared code changes, and how much CI time you are willing to spend on unaffected projects.

Which model should your team choose, and when should you avoid each?

Treat the choice as picking which failure mode you would rather debug. A single version policy fails loudly: one service blocks everyone's upgrade, and the friction is visible in a single pull request. Per-project manifests fail quietly: versions drift until two services serialize the same payload differently in production.

Factor Favors single version policy Favors per-project package.json
Teams and ownership One platform team, or a few teams sharing a release cadence Many teams with independent roadmaps and on-call
Publishable packages Few or none; most code is internal Many, consumed outside the repo with their own semver
Framework peer dependencies One framework major across services Services pinned to incompatible framework majors
Deploy unit One artifact, or images built from a shared lockfile Per-service images that must stay small and reproducible
Duplicate installs Low tolerance; disk and install time matter Acceptable cost for isolation

Avoid a single version policy when a service is legitimately stuck on an older framework major, for example because of a vendor SDK or a long-lived customer contract. Forcing it onto the root version turns every upgrade into a negotiation. Teams then work around the policy with overrides, and you get drift anyway, without the manifests that would make it visible.

Avoid per-project manifests when no one has the time to enforce the catalog and lag rules described above. Isolation without governance keeps the costs of duplicate installs and takes away the coordination that kept the runtime consistent.

If the checklist splits evenly, start with a single version policy. Carving out one project later is cheaper than reconverging a dozen projects that have drifted.

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.