In an Nx workspace backed by pnpm, the two tools have separate jobs. pnpm installs, resolves, and links packages. Nx reads the resulting dependency structure, together with your source imports, to build a project graph, then uses that graph to orchestrate tasks, compute affected, and cache outputs. Nx does not decide where packages live on disk, and pnpm does not know what a build target is.

pnpm's layout has three layers:

  • The content-addressable store. Each file of every package version is stored once in a global store on the machine. Installs hard-link files from that store instead of copying them, so ten projects using the same library share one set of bytes.
  • The virtual store. Under node_modules/.pnpm, each resolved package gets its own directory keyed by name and version. Inside it, the package's own dependencies appear as symlinks to their virtual-store entries.
  • The top-level symlinks. A package's node_modules contains links only to the dependencies listed in its package.json. Workspace packages referenced with the workspace: protocol are symlinked straight to their source directories, so edits are visible without republishing.

That third layer is why teams adopt this setup. npm and Yarn classic hoist most dependencies into a flat root node_modules. With a flat tree, code can import a package it never declared and still resolve it, because some other package pulled it in. That is a phantom dependency. Under pnpm, the same import fails at resolution time, so the missing declaration surfaces during development rather than after a deploy or an unrelated upgrade.

+-------------------------+           +--------------------------+
| Nx                      |  reads    | pnpm                     |
| project graph, affected |<----------| install, resolve, link   |
| task runs, cache        |           +--------------------------+
+-------------------------+                        |
                                                   v
+----------------------------------------------------------------+
| 1. Content-addressable store (global, one copy per file)       |
+----------------------------------------------------------------+
                  | hard links (no copies)
                  v
+----------------------------------------------------------------+
| 2. Virtual store: node_modules/.pnpm/<name>@<version>/         |
|    each entry's own deps --> symlinks to other .pnpm entries   |
+----------------------------------------------------------------+
                  ^ symlink (declared deps only)
                  |
+----------------------------------------------------------------+
| 3. libs/app-a/node_modules/                                    |
|    declared-dep  --> .pnpm entry                               |
|    @org/lib-b    --> libs/lib-b (workspace: protocol)          |
|    undeclared-x  --> missing: import fails (phantom dep)       |
+----------------------------------------------------------------+

pnpm links packages through a global store, a virtual store and per-package symlinks, so undeclared imports fail; Nx reads the result to build its project graph.

How do you set up pnpm-workspace.yaml so Nx discovers your projects?

A minimal layout puts deployables under apps/ and libraries under packages/, each with its own package.json. In pnpm-workspace.yaml, the packages key lists globs such as apps/* and packages/*. pnpm treats every directory matching a glob that contains a package.json as a workspace package. Nx reads the same files and infers one project per package.json, using its name field as the project name and its scripts as candidate targets. Keep the globs narrow. A loose pattern like ** can pull fixture or example directories into both the install and the project graph.

Internal dependencies use the workspace protocol. pnpm then links the local package and fails the install if no workspace package matches. A bare range such as ^1.2.0 has no such guarantee. Depending on your link-workspace-packages setting, pnpm may resolve it from the registry, and it always does so when the local version falls outside the range. You end up testing against a published copy while believing you are testing local code.

When you run pnpm pack or pnpm publish, pnpm rewrites the protocol using the local package's current version. Assume that version is 1.4.2:

Declared Packed/published as What external consumers get
workspace:* 1.4.2 Exact pin
workspace:^ ^1.4.2 Compatible minor and patch updates
workspace:~ ~1.4.2 Patch updates only

workspace:* needs no thought inside the monorepo. Once published, though, it pins consumers to exact versions. That causes duplicate installs and blocks patch fixes. For packages that leave the repository, prefer workspace:^. Reserve * for private packages that are never published.

# Root of the monorepo: declare which directories are workspace packages.
# Narrow globs keep fixtures and examples out of both pnpm and the Nx graph.
cat > pnpm-workspace.yaml <<'EOF'
packages:
  - "apps/*"
  - "packages/*"
EOF

# A publishable library. Nx infers a project named @acme/ui from this file.
mkdir -p packages/ui
cat > packages/ui/package.json <<'EOF'
{
  "name": "@acme/ui",
  "version": "1.4.2",
  "scripts": { "build": "tsc -p tsconfig.json" }
}
EOF

# A private app that consumes the library through the workspace protocol.
# workspace:^ always links the local copy and fails the install if no
# workspace package named @acme/ui exists. It also publishes as a caret range.
mkdir -p apps/web
cat > apps/web/package.json <<'EOF'
{
  "name": "web",
  "private": true,
  "dependencies": { "@acme/ui": "workspace:^" }
}
EOF

pnpm install

# Inspect the rewrite: pack a package that declares a workspace: dependency,
# then read the package.json inside the tarball. With @acme/ui at 1.4.2,
# "workspace:^" appears as "^1.4.2" ("workspace:*" would be "1.4.2").
# (pnpm pack works on private packages too; it is publish that refuses them.)
cd apps/web
pnpm pack
tar -xOzf web-*.tgz package/package.json

Creates a minimal apps/ and packages/ workspace where Nx infers one project per package.json, links an internal library with workspace:^, and runs pnpm pack to confirm the protocol is rewritten to ^1.4.2 in the packed manifest.

Why do missing dependency declarations break Nx affected and caching?

Nx builds its project graph from two inputs: the dependencies each package.json declares, and static analysis of import statements in source files. A workspace: reference is the most reliable of these. When @acme/api lists "@acme/utils": "workspace:^", Nx records an edge from api to utils no matter how the code imports it. Import analysis is less reliable. It misses dynamic import() calls with computed specifiers, require calls in build or test config files, and modules that are loaded indirectly by a tool.

An undeclared dependency breaks two systems. pnpm only links into packages/api/node_modules what api declares. A local build can still pass because a TypeScript path alias or a root-level link resolves the import by accident. A CI job that uses a filtered install, or that packages api alone, has neither fallback, so the build fails with a module resolution error.

The second failure is harder to spot. If Nx has no edge, a change to utils does not mark api as affected. nx affected -t build skips api. Its cache hash also excludes the outputs of utils, so Nx can replay a stale cached build as a hit.

To check this, run nx graph --focus=api and look for the edge to utils. Then change a file in utils and run nx show projects --affected. Add the workspace:^ declaration, run pnpm install, and repeat both commands. The edge should now appear, and api should be in the affected list.

An explicit declaration takes one line to add. Finding the same problem from a failure that only happens in CI usually takes much longer.

# Run from the workspace root. Assumes projects 'api' (@acme/api) and 'utils' (@acme/utils),
# and that api imports @acme/utils without declaring it in packages/api/package.json.

# BEFORE: check whether Nx records an edge from api to utils.
nx graph --focus=api            # opens the graph; look for the api -> utils edge

# Make a change in utils only. Nx counts uncommitted changes as part of affected.
echo '// touch' >> packages/utils/src/index.ts

# List projects affected by the change, compared with main.
nx show projects --affected --base=main
# If api is missing here, 'nx affected -t build' will skip it too.
nx affected -t build --base=main

# FIX: declare the dependency with the workspace protocol.
# This writes "@acme/utils": "workspace:^" into packages/api/package.json
# and links the package into packages/api/node_modules.
pnpm add "@acme/utils@workspace:^" --filter @acme/api

# AFTER: repeat both checks.
nx graph --focus=api            # the api -> utils edge should now be visible
nx show projects --affected --base=main   # api should now be listed

# api's build hash now covers utils, so a change in utils causes a cache miss
# for api and api is rebuilt, instead of Nx replaying a stale cached result.
nx affected -t build --base=main

# Undo the test change.
git checkout -- packages/utils/src/index.ts

Use nx graph and nx show projects --affected to check for the api-to-utils edge, add the workspace:^ declaration with pnpm, and run both checks again to confirm that api is now in the graph and the affected list.

When should you loosen hoisting, and when should you avoid shamefully-hoist?

By default, pnpm hoists every dependency into a hidden directory, node_modules/.pnpm/node_modules. Only packages inside the virtual store can resolve from there. Your own source code cannot. This is why an undeclared import fails in a pnpm workspace when it would quietly work under a flat layout. Three .npmrc settings control how far that boundary moves.

hoist-pattern decides what goes into the hidden directory. Narrowing it rarely helps. Its main use is to make transitive dependencies fail loudly when one package reaches into another's dependencies.

public-hoist-pattern copies matching packages into the root node_modules, where everything can see them. This is the right tool for software that assumes a flat tree: editor plugins, linters that resolve plugins by name from the root, or a native build step that searches a fixed path. List those packages by name. The default value of this setting has changed between pnpm releases, so check the effective value with pnpm config get public-hoist-pattern before you depend on it.

shamefully-hoist=true is the same as a public pattern of *. It makes a migration from npm or Yarn pass on the first day, but it does so by removing isolation entirely. Every phantom dependency from the last section comes back, and Nx's project graph goes blind to them again. Teams rarely turn it off later, because each week adds more undeclared imports that turning it off would break.

Setting Scope Risk Appropriate use
hoist-pattern Hidden .pnpm/node_modules, visible only to dependencies Low Leave at default; narrow it to expose sloppy transitive access
public-hoist-pattern Root node_modules, visible to all code Medium; phantoms limited to the listed names Named tools that require a flat layout
shamefully-hoist Everything at the root High; isolation is lost Short-lived migration step with a removal date
# .npmrc at the workspace root (next to pnpm-workspace.yaml)

# Hidden hoisting into node_modules/.pnpm/node_modules.
# Only packages in the virtual store resolve from here; your source cannot.
# '*' is the default. Leave it unless you want sloppy transitive access
# (package A importing package B's dependency) to fail loudly.
hoist-pattern[]=*

# Public hoisting into the root node_modules, visible to all code.
# List only the tools that assume a flat tree, by name or narrow glob.
# Each entry is a deliberate, reviewable phantom dependency.
public-hoist-pattern[]=eslint
public-hoist-pattern[]=eslint-plugin-*
public-hoist-pattern[]=@typescript-eslint/*
public-hoist-pattern[]=prettier

# Migration shortcut only. Equivalent to public-hoist-pattern[]=*.
# It removes isolation, brings every phantom import back, and hides
# those imports from the Nx project graph. If you must enable it,
# record a date for turning it off and track it like any other debt.
# shamefully-hoist=true

# After editing, reinstall and confirm the values pnpm actually uses:
#   pnpm install
#   pnpm config get hoist-pattern
#   pnpm config get public-hoist-pattern
#   pnpm config get shamefully-hoist

A workspace-root .npmrc that keeps the default hidden hoisting, publicly hoists only named lint and format tools that expect a flat node_modules, and leaves shamefully-hoist commented out as a temporary migration escape hatch.

How do you diagnose phantom dependencies and resolution failures?

Start from the error, not the tree. When a package fails to resolve, run pnpm why <name> from the failing project's directory (or with --filter) to see which workspace packages depend on it and through which chain. Use pnpm list <name> --depth Infinity to see every resolved version. Then check what Node actually loads: ls -l node_modules/<name> in the consuming package shows the symlink into node_modules/.pnpm, and node -p "require.resolve('<name>')" run from that package prints the resolved path. If the import succeeds only because the name happens to be visible from the root, you have a phantom dependency.

Decision rule: if your own code imports the package, declare it in that package's package.json, using workspace: for internal packages. This is almost always the right fix, and it also gives Nx the correct edge in its project graph. Change hoisting only when a third-party tool that you cannot patch looks up a dependency it never declared. In that case, add the narrowest public-hoist-pattern entry that fixes it.

Peer dependencies need separate attention. pnpm resolves peers per consumer, so two packages that see different peer versions get separate copies in .pnpm. Those copies appear as directories whose names carry a suffix encoding the peer versions. The result can be two instances of a framework or ORM client in one process. A class from one copy fails instanceof checks against the other, and a "singleton" exists twice. To detect this, run pnpm why on the framework and look for more than one version or more than one peer-suffixed path. To constrain it, align the version ranges across packages, pin a single version with pnpm.overrides in the root package.json, and run pnpm dedupe after changing ranges.

Should tooling live in root devDependencies or per-package, and what about TypeScript path aliases?

Root devDependencies are the default because they're easy. You install one copy of the linter, test runner and bundler, and every project resolves them by walking up to the root node_modules. The cost is that the graph loses information. A package's manifest no longer says which tools it needs, so a single package can't be extracted cleanly. pnpm deploy also produces a bundle that only works because the root happened to supply something. Per-package declarations restore that information but add more manifests to keep aligned.

Approach Benefits Costs Suits
Root devDependencies One version, short manifests Hidden tool usage, harder extraction Small teams, one deployable
Per-package devDependencies Explicit needs, self-contained packages More version drift to manage Independently published or deployed packages
TS path aliases No build step between packages Masks missing declarations, editor and build can disagree Apps bundled as one unit
workspace: links Same resolution as production Needs built output or source-pointing exports Libraries consumed like real packages

Path aliases cause the same kind of masking at the source level. TypeScript resolves @org/utils through paths, so a consumer with no @org/utils entry in its package.json still compiles. That missing entry also leaves the Nx graph incomplete. Problems show up later. A bundler or Node at runtime ignores paths and fails. A dependency can also resolve twice, once from source through the alias and once from node_modules through the link, which breaks instanceof checks and singletons.

Choose one model and apply it everywhere. If you choose linked packages, the alternatives to aliases are TypeScript project references, or exports entries pointing at source and gated by customConditions. Enforce declarations with Nx's @nx/dependency-checks lint rule.

What does this setup cost in CI, and how do you keep it fast?

Install with pnpm install --frozen-lockfile so CI fails when package.json and pnpm-lock.yaml disagree, instead of quietly re-resolving. Then narrow the work. nx affected -t build test limits tasks to changed projects, and pnpm --filter "...[origin/main]" does the same for pnpm-level scripts.

Watch the lockfile in cache inputs

Nx hashes the external packages each project depends on. If {workspaceRoot}/pnpm-lock.yaml is also listed in sharedGlobals or another file input, any lockfile edit invalidates every task. Remove it from those inputs and rely on per-project external dependency hashing. Use externalDependencies inputs only where a specific tool version must be tracked.

Illustrative estimate (assumed numbers, not a benchmark): wasted time = projects invalidated × average task minutes. Assume 40 projects at 3 minutes each. Bumping one library used by 4 projects costs 12 minutes with per-project hashing and 120 minutes with the whole lockfile as a global input.

Some tools don't handle symlinked packages well:

  • Bundlers may resolve a linked package to its real path and bundle it twice. Check settings such as webpack's resolve.symlinks or Vite's preserveSymlinks.
  • File watchers may not follow symlinks into the .pnpm store.
  • Docker can't follow links that point outside the build context.

To avoid all three, run pnpm deploy or a pruned-output step that copies each app's real dependencies into one directory. Use that directory as the image's build context.

When this is the wrong fit

A single deployable package doesn't need workspaces. If your bundlers or platforms expect a flat node_modules, node-linker=hoisted or another package manager's workspaces cost less than fighting symlinks in every tool.

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.
  • 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.