What does pnpm do in an Nx monorepo, and what does Nx do?
pnpm and Nx each build a dependency graph, and they build them from different evidence. Problems start where the two disagree.
pnpm owns the graph on disk. pnpm-workspace.yaml lists the directories that count as packages. pnpm resolves every package.json, writes the lockfile, and symlinks workspace packages into each other's node_modules. If a dependency is not declared, it is not reachable at runtime. That is what your deployed container will see.
Nx owns the task graph. It builds a project graph from package.json dependencies and from imports it finds in source files. It uses that graph to order builds, compute cache hashes, and decide which projects are affected by a change.
Where the graphs diverge
- Undeclared imports.
orders-apiimports@acme/db, but itspackage.jsondoes not list it. Nx sees the import and builds in the right order. Locally, the code may resolve through a path alias or a hoisted copy. In the deployed artifact, pnpm never linked the package, so the service fails at startup. - Stale installs. Nx hashes what it reads: sources, configuration, and resolved versions. It does not hash the contents of
node_modules. If a CI cache restoresnode_modulesthat no longer matches the lockfile, Nx can replay a cached build produced against different dependencies.
The results are stale cache hits, "affected" runs that skip a broken service, and builds that pass in CI but fail in production. Most "Nx bugs" in backend repos turn out to be package manager misconfiguration.
Who this setup suits
It suits backend and platform teams shipping several independently deployed services that share internal libraries. It is overhead for a single service, or for a team that has no need for task ordering and caching.
+------------------------------------------------------------+
| Repository: pnpm-workspace.yaml, package.json files, |
| source files (imports) |
+-----------------+--------------------------+---------------+
| |
workspace dirs + declared deps declared deps + imports
| |
v v
+---------------------------+ +-----------------------------+
| pnpm: graph on disk | | Nx: project / task graph |
| - resolves package.json | | - package.json deps |
| - writes pnpm-lock.yaml | | - imports found in source |
| - symlinks node_modules | | - hashes sources, config, |
| - declared deps only | | resolved versions |
+-------------+-------------+ +--------------+--------------+
| |
v v
+---------------------------+ +-----------------------------+
| Deployed artifact: sees | | Task order, cache hashes, |
| only what pnpm linked | | "affected" projects |
+---------------------------+ +-----------------------------+
GAP 1: orders-api imports @acme/db; its package.json omits it
Nx: import edge -> builds OK | pnpm: no link -> fails at startup
GAP 2: CI restores node_modules that no longer match the lockfile
Nx: node_modules not hashed -> replays a stale cached build
pnpm builds the dependency graph that exists on disk and ships with the service, Nx builds a task graph from declared dependencies and source imports, and undeclared imports or stale node_modules let the two disagree.
How do you set up pnpm-workspace.yaml for backend services?
A typical backend layout puts each deployable service under apps/ (for example apps/orders-api, apps/billing-worker) and shared code under libs/ or packages/. In pnpm-workspace.yaml, list the same directories under packages: with globs such as apps/* and libs/*. These globs should match the directories Nx treats as projects. If a library exists for Nx but sits outside the globs, pnpm will not link it, and imports break at install time. If pnpm links a directory that Nx ignores, the project graph stops matching what is actually installed.
For internal dependencies, use the workspace protocol in each service's package.json:
| Specifier | Local install | Rewritten on publish to |
|---|---|---|
workspace:* |
Links the local package, any version | Exact version, e.g. 1.4.0 |
workspace:^ |
Links the local package | Caret range, e.g. ^1.4.0 |
workspace:~ |
Links the local package | Tilde range, e.g. ~1.4.0 |
The protocol tells pnpm to resolve the dependency only from the workspace. With a plain semver range, pnpm can fall back to a registry package of the same name when the local version doesn't satisfy it. That can silently install someone else's @acme/logger. With workspace:, the install fails instead.
The trade-off: with workspace:*, any change to a library makes every dependent "affected." A broad libs/common that every service imports means one edit retests and rebuilds everything. To limit this fan-out, keep libraries small and focused, such as libs/db-client and libs/auth. Then use Nx's module boundary lint rule with project tags so services cannot import each other and only depend on the libraries they need.
# pnpm-workspace.yaml (repository root)
# Keep these globs identical to the directories Nx treats as projects,
# so pnpm links exactly the projects that appear in the Nx project graph.
packages:
- "apps/*" # deployable services, e.g. apps/orders-api, apps/billing-worker
- "libs/*" # small shared libraries, e.g. libs/db-client, libs/auth
# Each service then declares internal libraries with the workspace protocol
# in its own package.json, for example apps/orders-api/package.json:
#
# "dependencies": {
# "@acme/db-client": "workspace:*", # always the local copy; exact version on publish
# "@acme/auth": "workspace:^" # always the local copy; ^x.y.z on publish
# }
#
# Because of the workspace: prefix, pnpm resolves these only from libs/*.
# If the package is missing locally, the install fails instead of pulling
# a same-named package from the registry.
A pnpm-workspace.yaml whose globs match the Nx project directories, with comments showing how a service references internal libraries through the workspace protocol.
How do pnpm catalogs keep dependency versions consistent across services?
Once services share libraries, they also need to share dependency versions. If one service runs a different major version of the HTTP framework or ORM than the libs/db-client it imports, you get type mismatches and duplicate installs that only show up at runtime. pnpm catalogs address this by defining each shared version once.
Add a catalog section to pnpm-workspace.yaml that maps package names to version ranges for your framework, ORM, logger and test runner. In each service's package.json, write "catalog:" as the version instead of a range. pnpm resolves it from the workspace file at install time and replaces it with the real range when you pack or publish. An upgrade then becomes a one-line change plus one lockfile update, and Nx's affected detection shows which projects need retesting. You stop sending a dozen near-identical PRs, and services stop drifting apart over time.
When not to use a single catalog
A shared version only helps when the services that use it can upgrade together. If a team has to stay on an older major version because of its own release schedule or a compliance freeze, leave its dependency out of the default catalog or move it into a named catalog under catalogs, referenced as catalog:<name>. Treat a major bump in a widely used entry as a cross-team change, because it hits every consumer at the same moment.
Check your tooling first
Catalogs are a fairly recent pnpm feature. Confirm that the pnpm version pinned in your repo and in CI supports them. Dependency update bots, older IDE integrations and custom scripts that parse package.json may not understand the catalog: protocol. Test each of these before you migrate.
# pnpm-workspace.yaml (repo root)
packages:
- "apps/*"
- "libs/*"
# Default catalog: one version range per shared dependency.
# Services reference these with "catalog:" in package.json.
catalog:
fastify: ^5.0.0 # HTTP framework
kysely: ^0.27.0 # query builder / data access
pino: ^9.0.0 # logger
vitest: ^2.0.0 # test runner
# Named catalogs: for services that must upgrade on their own schedule.
# Referenced as "catalog:<name>", e.g. "catalog:fastify4".
catalogs:
fastify4:
fastify: ^4.28.0 # held back during a release or compliance freeze
# --- apps/orders-api/package.json (follows the default catalog) ---
# {
# "dependencies": { "fastify": "catalog:", "kysely": "catalog:", "pino": "catalog:" },
# "devDependencies": { "vitest": "catalog:" }
# }
#
# --- apps/billing-api/package.json (pinned to the named catalog) ---
# {
# "dependencies": { "fastify": "catalog:fastify4", "pino": "catalog:" },
# "devDependencies": { "vitest": "catalog:" }
# }
#
# Upgrading the shared logger then means editing one line above,
# running `pnpm install` to update the lockfile, and letting
# `nx affected -t test` show which projects to retest.
A pnpm-workspace.yaml that defines shared versions once in the default catalog, adds a named catalog for a service that must stay on an older major version, and shows how each service's package.json references those entries with catalog: and catalog:.
Why does pnpm's strict node_modules expose phantom dependencies, and when should you change hoisting?
By default pnpm uses an isolated layout. Every package lives once in a content-addressed virtual store under node_modules/.pnpm, and each project's node_modules contains symlinks only to the dependencies that project declares. If orders-api imports lodash without listing it, Node's resolver fails, even when another service depends on lodash. That failure is the point. When you ship one service on its own, through a container or a pruned install, only its declared dependencies come with it. A phantom dependency that resolved by accident in the monorepo would surface as a runtime crash in production.
.npmrc gives you four ways to relax this:
| Setting | What changes | When it is justified |
|---|---|---|
hoist-pattern |
Hoists matches into the hidden node_modules/.pnpm/node_modules, where packages in the store can see them but your code cannot |
Rarely touched. It lets badly declared third-party packages find their own peers. |
public-hoist-pattern |
Hoists matches into the root node_modules, where all code can see them |
Tools that resolve plugins from the root, such as some ORM generators or older CLIs |
shamefully-hoist=true |
Same as public-hoist-pattern=* |
Almost never. Prefer a narrow pattern. |
node-linker=hoisted |
Produces a flat, npm-style tree with no symlinks | Native addons or build tooling that cannot handle symlinked paths |
Scope public-hoist-pattern to the exact packages a tool needs, such as an ORM's client and engine packages. Leave the rest of the tree isolated. Broad hoisting puts every transitive package where any service can import it. Missing declarations then stay invisible until a pruned deploy fails.
To catch drift earlier, enable the @nx/dependency-checks lint rule or import/no-extraneous-dependencies. Both compare what each project actually imports against the dependencies in its package.json.
# .npmrc at the workspace root (next to pnpm-workspace.yaml)
# Keep the default isolated, symlinked layout. Each service sees only
# what its own package.json declares. Do not set node-linker=hoisted
# unless a native addon or build tool cannot follow symlinks.
node-linker=isolated
# Never turn this on globally. It is equivalent to public-hoist-pattern=*
# and lets every service import any transitive package without declaring it.
shamefully-hoist=false
# Hoist to the root node_modules ONLY the packages a tool resolves from
# the root. Here, a placeholder ORM's code generator and engine.
# Setting this list replaces pnpm's default public-hoist-pattern, so add
# any default entries your tooling still relies on.
public-hoist-pattern[]=@acme-orm/client
public-hoist-pattern[]=@acme-orm/engines
# Leave hoist-pattern (the hidden node_modules/.pnpm/node_modules) at its
# default. It only helps third-party packages with sloppy peer declarations
# and is never visible to your service code.
# Verify the effect after install:
# pnpm install
# ls node_modules/@acme-orm # hoisted: visible from the root
# pnpm why lodash --filter orders-api # confirm orders-api declares what it imports
A workspace .npmrc that keeps pnpm's isolated layout and uses a narrowly scoped public-hoist-pattern for one ORM's packages instead of enabling shamefully-hoist globally.
How do you build a deployable artifact for one service from the monorepo?
Copying node_modules from the repo root into an image does not work. pnpm stores packages in a content-addressable store and links them into node_modules/.pnpm, so a service's node_modules is mostly symlinks pointing outside its folder. Copy the folder alone and those links break. Copy the whole root and you ship every service's dependencies.
pnpm deploy solves this. Running pnpm --filter orders-api --prod deploy /out/orders-api writes one directory that contains the service, its production dependencies, and real copies of any workspace: packages it uses. That directory has no links back to the monorepo, so you can COPY it into a slim runtime stage.
Another option is a filtered install inside the build stage. pnpm install --frozen-lockfile --filter orders-api... installs only that project and its dependency graph. It uses the same lockfile but keeps the workspace layout.
To keep Docker layer caching, put the slow steps that change rarely first:
- Copy only
pnpm-lock.yamlandpnpm-workspace.yaml, then runpnpm fetch. This step downloads packages from the lockfile alone, so the layer stays cached until dependencies change. - Copy the source and run
pnpm install --offline. - Build with Nx, run
pnpm deploy, and copy the result into the final stage.
In CI, use nx affected -t build (or nx show projects --affected) to get the list of changed services, and run image builds only for those.
The cost is extra moving parts: a separate deploy step for each service, a multi-stage Dockerfile, and one more place where a missing dependency declaration surfaces as a runtime failure.
How do you keep Nx and pnpm consistent in CI?
Start with the install. Run pnpm install --frozen-lockfile so CI fails when pnpm-lock.yaml and the package.json files disagree, instead of quietly resolving new versions. pnpm turns this on by default when it detects a CI environment, but stating it explicitly documents the intent. Pin pnpm itself with the packageManager field in the root package.json and enable Corepack in the pipeline, so developers and runners all use the same pnpm. Different pnpm versions can rewrite the lockfile format, and that causes noisy diffs and frozen-install failures.
Next, make sure dependency changes reach the Nx cache. Nx factors the resolved versions of each project's external dependencies into its task hashes. The blunt alternative is to add pnpm-lock.yaml to sharedGlobals. That is safe but expensive, because any lockfile change invalidates every project.
The single lockfile is also a merge-conflict hotspot. Resolve the package.json conflicts, then run pnpm install to regenerate the lockfile. Don't edit it by hand.
Illustrative estimate
All inputs here are assumptions, not measurements:
- The repo has 40 projects.
- Build plus test averages 6 minutes per project.
- A routine bump touches a package used by 5 services.
With the whole lockfile as a global input, that bump reruns 40 × 6 = 240 compute-minutes. With inputs scoped to each project's actual dependencies, it reruns 5 × 6 = 30 compute-minutes. With weekly bumps, the gap compounds into real runner cost and longer queues.
Should you use pnpm --filter or Nx to run tasks, and what are the alternatives?
Both tools can run a script in one package, so the overlap needs a written convention. A developer who types pnpm --filter orders-api build gets a correct build, but Nx never sees it: no cache read, no cache write, and no automatic build of upstream libraries. Over time the remote cache hit rate drops and nobody can say why. Document the rule in the repo's contributing guide and enforce it in CI by invoking only Nx for targets.
| Task | Use | Why |
|---|---|---|
| Install, add or remove a dependency in one package | pnpm add --filter <pkg> |
pnpm owns the lockfile and node_modules layout |
| Run a target across many projects | nx run-many -t <target> |
Dependency ordering, parallelism, caching |
| Run only what a change touches | nx affected -t <target> |
Uses the project graph and the git base |
| One-off script with no outputs | Either | Caching gives no benefit here |
Alternatives
- pnpm workspaces alone, using
pnpm -r run: Recursive runs follow topological order but have no task cache. This fits a handful of services with fast builds. The cost grows with every service you add, because CI rebuilds everything on each change. - Nx with npm or Yarn workspaces: Nx works the same way with these package managers. You lose pnpm's strict isolation and catalogs, so phantom dependencies and version drift become a matter of team discipline rather than something the tooling catches.
- Nx with a single root
package.json: Every project shares one dependency set, and imports resolve through TypeScript path aliases. Upgrades are simpler because there is only one version of each dependency. The trade-off is that you must prune dependencies per service at deploy time, and every service has to move to a new major version together.
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.
- Changing a shared variable is one edit and one review instead of editing every service's
.envby 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.