How does the Nx project graph decide what is used?

An unused library in an Nx workspace is a project that no other project depends on: it has no incoming edges in the project graph. A dead project is broader. It may still have incoming edges, but nothing that ships or runs depends on it, directly or through other projects. A library used only by an abandoned app is dead even though the graph shows it as used.

Nx builds the project graph from three inputs:

  • Static import analysis. Nx parses source files and resolves import paths, such as TypeScript path aliases, to workspace projects. This catches nearly all ordinary code usage. It misses imports whose path is computed at runtime, code loaded by string name, and consumers outside the workspace, such as other repositories installing a published package.
  • Explicit implicitDependencies. These are edges you declare in project configuration for relationships that analysis cannot see. Nx does not check whether they are still true. A stale entry left behind after a refactor keeps a dead library looking used indefinitely.
  • package.json dependencies. When one workspace package lists another as a dependency, Nx records an edge, even if no code imports it anymore.

Dead projects still cost you. They inflate affected runs in CI, add tasks to hash and cache, carry ownership with no one behind it, and make new engineers learn code that does nothing. Platform and backend engineers who own large or long-lived monorepos pay these costs most.

+------------------+  +--------------------+  +-------------------+
| Static imports   |  | implicitDependen-  |  | package.json deps |
| (resolved paths) |  | cies (declared,    |  | (workspace pkgs,  |
|                  |  |  never re-checked) |  |  even if unused)  |
+--------+---------+  +---------+----------+  +---------+---------+
         |                      |                       |
         +----------------------+-----------------------+
                                |
                                v
                    +-----------------------+
                    |   Nx project graph    |
                    +-----------+-----------+
                                |
                                v
+------------------------------------------------------------------------+
| api --import--> auth                       used (shipped app)          |
| legacy-app --import--> lib-old             dead (abandoned app)        |
| web --implicitDep (stale)--> lib-gone      dead, looks used            |
| lib-orphan   (no incoming edges)           unused                      |
+------------------------------------------------------------------------+
| MISSED: runtime-computed import paths, code loaded by name,            |
|         consumers in other repositories                                |
+------------------------------------------------------------------------+

Static imports, declared implicitDependencies and package.json dependencies feed the Nx project graph. The graph shows edges, not whether a consumer still ships, so stale implicitDependencies and abandoned consumers can make dead libraries look used.

Who should use this checklist?

This checklist is for the people who answer for the workspace as a whole, not for a single feature:

  • Platform and developer-experience engineers who own CI time, cache configuration and workspace tooling. Every dead project adds tasks they have to run, hash and cache.
  • Tech leads and monorepo maintainers doing periodic cleanup, or preparing for work whose effort grows with project count, such as running nx migrate across the workspace, changing shared lint or TypeScript configuration, or restructuring folders.
  • Teams inheriting a workspace after reorganizations, where many libraries have no clear owner and nobody remembers which apps still ship.
  • Engineers about to split, merge or extract parts of a monorepo, who need to know which projects are worth moving at all.

It is less useful in a small workspace where one person can list every project and its consumers from memory. There, opening nx graph once and reading it is enough. It is also a poor fit when most real usage happens outside the workspace, for example a repository that mainly publishes packages to other repositories. In that case inbound edges say little about actual use, and registry and consumer data matter more than the graph.

How does the checklist work, step by step?

The process narrows a large set of projects down to a small set you can delete with confidence. Each step removes false positives that the previous step cannot see:

  1. Export the project graph and list libraries with no inbound edges. This is cheap and mechanical, and it produces candidates, not decisions.
  2. Check every candidate against the graph's blind spots. Runtime-built imports, scripts, CI and infrastructure files, published packages, convention-based loading and plain-string config references can all use a library without creating an edge. A repo-wide text search for the path alias and folder name is the main cross-check.
  3. Look for dead projects that still have edges. Follow edges upward from each library to see whether they end at an app that still ships. A library consumed only by an abandoned app or through a stale implicitDependencies entry is dead too.
  4. Optionally go below project level. Export-level analysis finds unused symbols inside libraries that are still live, so you can trim them instead of deleting them.
  5. Remove in two phases. Deprecate first so hidden consumers surface as lint failures or replies, wait a release cycle, then delete the folder, alias, CODEOWNERS lines and implicit dependencies in one revertible commit and run the full suite.
  6. Prevent new orphans. Required scope: and owner: tags plus module boundary rules make every new library declare where it belongs and who answers for it.
  7. Automate detection, not deletion. A scheduled job reports new orphans so the inventory stays current without blocking anyone's build.

The sections below follow this order.

How do you list Nx unused libraries from the project graph?

Start with the interactive view. Running nx graph opens a browser visualization of every project and the edges between them. It helps you spot obvious islands, but it doesn't scale to a workspace with hundreds of projects, and you can't diff it in a pull request. For analysis, export the same data with nx graph --file=graph.json. The resulting file contains a graph object with two parts: nodes, keyed by project name, and dependencies, which maps each source project to the list of targets it depends on.

To find candidates, invert that dependency map. Walk every edge, record each target as having at least one consumer, and then list the nodes that never appear as a target. Those projects have no inbound edges.

The raw result is noisy, because applications and e2e projects are supposed to have no inbound edges. They are the leaf consumers at the top of the graph, and nothing should import them. Filter on each node's type field, which Nx sets to app, lib, or e2e, and keep only lib. If a project's type looks wrong, check its projectType setting before trusting the filter. A misclassified project will either hide a real orphan or flag a healthy app.

Treat what remains as a candidate list, not a deletion list. A library with no inbound edges might be published to a registry, loaded at runtime, or referenced in a way the graph can't see. Record each candidate with its owner and keep the list for the next round of checks.

// find-orphan-libs.js
// Usage:
//   npx nx graph --file=graph.json
//   node find-orphan-libs.js graph.json
const fs = require('fs');

const file = process.argv[2] || 'graph.json';
const { graph } = JSON.parse(fs.readFileSync(file, 'utf8'));

// Invert the dependency map: every edge target has at least one consumer.
const consumed = new Set();
for (const edges of Object.values(graph.dependencies)) {
  for (const edge of edges) {
    consumed.add(edge.target);
  }
}

// Projects that never appear as a target have no inbound edges.
// Keep only libraries, because apps and e2e projects are expected leaf consumers.
const candidates = Object.values(graph.nodes)
  .filter((node) => !consumed.has(node.name))
  .filter((node) => node.type === 'lib')
  .map((node) => ({ name: node.name, root: node.data.root }))
  .sort((a, b) => a.name.localeCompare(b.name));

// This is a candidate list for review, not a deletion list.
// Use the project root to look up an owner before deciding anything.
console.log(`Libraries with no inbound edges: ${candidates.length}`);
for (const c of candidates) {
  console.log(`${c.name}\t${c.root}`);
}

A Node script that reads the file written by nx graph --file=graph.json, inverts the dependency map, and prints library projects with no inbound edges, along with their roots, as a candidate list for review.

What can the project graph miss before you delete a library?

The graph is built from static analysis of source files and project configuration. Anything that references a library without a resolvable import statement will not appear as an edge. Check each candidate against these blind spots before deleting it:

  • Dynamic imports built from runtime strings. If the module path is assembled from a variable or template, no analyzer can resolve it.
  • Consumers outside workspace source. Shell scripts, CI pipeline definitions, Dockerfiles and infrastructure code often copy or build a library by its folder path.
  • Published packages. If the library ships to a registry, other repositories may depend on it. Your workspace graph knows nothing about them.
  • Convention or reflection loading. Plugin loaders, DI containers that scan directories, and migration runners pick up code by location or naming pattern, not by import.
  • JSON or YAML config. Framework config, lint rules and generator settings can name a project or path as a plain string.
Blind spot How to check Risk if missed
Runtime-string imports Search for the alias fragment and folder name in source Runtime "module not found" in production
Scripts, CI, Docker, infra Search non-source files for the folder path Broken builds or deploys
Published to a registry Check publish config and registry download history Breaks other teams' repos
Convention or reflection Review loader and scanner configuration Features or migrations silently stop running
JSON/YAML config Search config files for the project name Tooling failures or misconfigured apps

Search the entire repository, not only source directories, for two strings: the library's tsconfig path alias and its folder name. Include dotfiles and config. If the graph reports zero consumers but the search finds hits, investigate each hit. Do not delete the library until every hit has an explanation.

#!/usr/bin/env bash
set -euo pipefail

PROJECT="legacy-utils"            # Nx project name
ALIAS="@acme/legacy-utils"         # tsconfig path alias
DIR="libs/shared/legacy-utils"     # library folder

npx nx graph --file=/tmp/nx-graph.json
graph_deps=$(jq -r --arg p "$PROJECT" \
  '[.graph.dependencies[][] | select(.target == $p) | .source] | unique | .[]' \
  /tmp/nx-graph.json)
echo "Graph dependents:"; echo "${graph_deps:-  (none)}"

echo "Text-search hits:"
git grep -n -I --untracked -F \
  -e "$ALIAS" -e "$DIR" -e "$(basename "$DIR")" \
  -- . ":(exclude)$DIR" || echo "  (none)"

if jq -e '.private != true' "$DIR/package.json" >/dev/null 2>&1; then
  echo "WARNING: $DIR/package.json is not marked private; check registry consumers."
fi

A bash script that lists the library's dependents from the Nx project graph, runs a repo-wide git grep for its path alias and folder name across all file types, and flags a possibly published package, so disagreements between graph and search can be investigated before deletion.

How do you find partially dead libraries and unused exports?

A library can have one live consumer and still be mostly dead. The project graph records dependencies between projects, not between symbols. If one app imports a single helper from a library of forty exports, the graph marks the whole library as used. To find dead code inside a library, you have to work at the export level.

The TypeScript compiler helps only partly. noUnusedLocals and noUnusedParameters catch unused declarations inside a file. They deliberately ignore anything that is exported, because the compiler treats an export as possibly consumed elsewhere. To find exports that no other project imports, you need a static analysis tool that resolves imports across the whole workspace. Use it alongside the graph, not instead of it. The graph tells you which projects are worth examining, and export analysis tells you what to trim inside them.

Export-level results are noisier in a monorepo. A library's index.ts barrel re-exports everything, so a naive tool sees each symbol as "used" by the barrel, or flags the whole public API as unused when only external packages consume it. Re-export chains, dynamic imports and symbols referenced only by framework decorators or config produce more false positives. You will need an ignore list for entry points and intentionally public exports. Treat that list as code: review it when libraries change, or it will gradually hide real dead code.

Method Accuracy Noise Effort
Project-level graph analysis High for whole projects; blind to unused symbols Low Low
Text search Catches strings the graph misses; no understanding of imports Medium to high Low per query, manual triage
Export-level analysis Finds unused symbols inside live libraries High until the ignore list is tuned Medium setup, ongoing maintenance

How do you remove a dead Nx project safely?

Removal is a two-phase change. Treat deprecation and deletion as separate pull requests so each can be reverted on its own.

  1. Deprecate first. Add a tag such as status:deprecated, a module boundary rule that rejects new imports of it, or a notice in the library's README. Send it to the owners listed in CODEOWNERS. This turns hidden consumers into lint failures or replies, which costs less than a broken deploy.
  2. Wait one release cycle. Consumers the graph cannot see, such as scripts, other repositories, or runtime-loaded plugins, tend to show up only when someone builds and ships.
  3. Delete everything in one commit. Remove the project folder, its path alias in the root tsconfig, its CODEOWNERS lines, and any implicitDependencies entries in other projects that point at it. A stale implicit dependency on a project that no longer exists can cause graph errors.
  4. Run the full suite. Build, lint, and test every project rather than relying on nx affected. Affected runs follow graph edges from the changed files. The edges that would show breakage are exactly the ones the graph never knew about, so an affected run can pass while a dynamic import or a lint rule that references the deleted project still fails.
  5. Record the removal. Write the reason in the commit message and note the commit hash in the changelog or ADR, so anyone who needs the library back can restore it with a single revert.
  6. Check long-lived branches. Release and feature branches may still import the library. Tell their owners before they rebase.

Expect a short-term drop in cache hit rates. The root tsconfig is usually a shared input to many projects, so editing it invalidates their cached results. In-flight branches will also compute a larger affected set after they rebase onto the deletion.

#!/usr/bin/env bash
set -euo pipefail

PROJECT="legacy-utils"            # Nx project name
PROJECT_DIR="libs/legacy-utils"    # project root
ALIAS="@acme/legacy-utils"         # path alias in tsconfig.base.json

git rm -r --quiet "$PROJECT_DIR"

if git grep -n -e "$ALIAS" -e "$PROJECT_DIR" -e "\"$PROJECT\"" -- . ; then
  echo "Remove the references above and stage them, then re-run." >&2
  exit 1
fi

if npx nx show projects | grep -qx "$PROJECT"; then
  echo "Nx still lists $PROJECT" >&2; exit 1
fi

npx nx run-many -t build lint test

git commit -m "chore: remove $PROJECT" \
  -m "Deprecated for one release with no remaining consumers. Restore with: git revert <this commit>"
echo "Removal commit: $(git rev-parse HEAD)"

for branch in $(git branch -r --list 'origin/release/*'); do
  git grep -l -e "$ALIAS" "$branch" -- . && echo "^ $branch still references $ALIAS"
done || true

A deletion-phase script that removes the project folder, stops if the alias, CODEOWNERS or implicitDependencies references remain, runs build, lint and test across every project, records the commit hash for a later revert, and lists release branches that still import the library.

How can tags and module boundary rules prevent new orphans?

Tags only help if every project has them. @nx/enforce-module-boundaries does not require a project to carry tags. An untagged library matches only constraints written for the wildcard source tag *, so it passes through every scoped rule unchecked. Close that gap in two places. First, have your library generators set a scope: tag and an owner: (or team:) tag when the project is created. Second, add a small CI check that reads each project's configuration and fails when either tag is missing. A new library then cannot merge without someone declaring where it belongs and who answers for it.

With tags in place, depConstraints turn placement into a review signal. Suppose a constraint says projects tagged scope:billing may depend only on scope:billing and scope:shared. A library dropped into the wrong scope "just to unblock a feature" now fails lint as soon as something imports it. The reviewer sees the violation in the pull request, while the author still remembers why the library exists. notDependOnLibsWithTags covers the reverse case, such as keeping type:app code out of shared libraries.

This moves the cost of cleanup to the moment of creation. A periodic audit has to reconstruct intent for dozens of projects at once. These rules ask one person one question while the context is still fresh. The owner tag also pays off later: when the graph flags a library, you know whom to ask before deleting it.

The rules have a clear limit. They govern which edges are allowed, not whether any edges exist. A correctly tagged library that nothing imports violates no constraint and passes lint indefinitely. You still need the graph-based consumer checks described earlier to find it.

When should you automate cleanup, and when should you avoid it?

A scheduled job closes that gap. Run it nightly or weekly on the main branch. It exports the project graph as JSON, lists library projects with no inbound dependency edges, and subtracts an allowlist of known exceptions such as published packages and plugin entry points. It then opens an issue or posts a report. It should not fail builds. An orphan is a cleanup task, not a defect in whichever commit happened to trigger the run. A red pipeline also trains people to add allowlist entries just to get unblocked.

Automation pays off in large workspaces with many teams and frequent library creation, where nobody can hold the full inventory in their head. Keep cleanup manual in small workspaces, where reviewing the graph by hand takes an hour. Keep it manual when reflection or runtime plugin loading makes the graph systematically incomplete. Keep it manual when many external consumers make inbound edges a poor signal of real usage.

The trade-offs need explicit handling:

  • Allowlist drift. Give every allowlist entry a named owner and a review date. Without both, the allowlist becomes a hiding place for dead code.
  • Stalled deprecations. Link each flagged library to a tracked issue with a removal date. Otherwise "deprecated" quietly becomes permanent.
  • CI cost. Exporting the graph is cheap. Avoid bundling the job with full builds or test runs across every project.

Illustrative estimate. Assume 300 libraries and a manual audit of 6 engineer-hours per quarter, so 24 hours a year. Assume the job takes 8 hours to build and 1 hour a month to maintain, so 20 hours in year one and 12 hours after that. The time savings are modest. The larger gain is that orphans surface within days instead of months.

What are the alternatives to graph-based detection?

The project graph is the cheapest starting point in an Nx workspace, but it is not the only way to find dead code. Each alternative answers a slightly different question:

  • Manual review with owners. Walk the project list with each team and ask which libraries they still need. This catches dead projects that still have edges, such as libraries used only by an abandoned app, which no static method flags. It does not scale and depends on people remembering correctly.
  • Text search only. A repo-wide search for aliases and folder names works without Nx at all and catches string references the graph misses. It has no notion of imports, so it produces many hits that need manual triage, and it cannot tell a live reference from a comment or a stale script.
  • Export-level static analysis. A tool that resolves imports across the workspace finds unused symbols, not just unused projects. It is more precise inside live libraries and noisier overall, as described earlier.
  • Runtime evidence. Code coverage from end-to-end or production-like test runs, or logging and tracing in deployed services, shows what actually executes. This is the only approach that sees code loaded by reflection or runtime-built paths. It only covers paths that were exercised, so absence of evidence is weaker than it looks, and it requires instrumentation you may not have.
  • Registry and deployment data. For published packages, download history and the list of dependent repositories show external usage. For apps, deployment records show whether a consumer still ships. This is how you confirm that a library with inbound edges is dead because its consumers are.
  • Doing nothing. If dead projects are few and cheap, leaving them alone is a legitimate choice. The cost grows with project count and with how often you run workspace-wide changes.

In practice these combine well: the graph produces candidates, text search and registry data remove false positives, and runtime evidence or owner review settles the cases static analysis cannot.

How can this save engineering time?

Dead projects cost time in places that are easy to overlook, because each instance is small:

  • CI and local task time. When a change touches a shared input such as the root tsconfig, lint config or a widely used library, nx affected includes every dependent project, dead ones included. Uncached build, lint and test tasks for those projects run on every such change.
  • Workspace-wide changes. nx migrate, dependency upgrades, lint rule changes and TypeScript configuration changes have to be applied to and verified against every project. Each dead project is more code to fix when an upgrade breaks it, even though fixing it delivers nothing.
  • Code review and ownership. Dead libraries still show up in CODEOWNERS, still get review requests from mechanical refactors, and still generate security or dependency update work.
  • Onboarding and navigation. New engineers read, search through and ask questions about code that does nothing. Search results and editor navigation are noisier.
  • Cleanup itself. The checklist and the prevention rules shorten the next audit. Owner tags remove the hunt for whoever might know about a library, and the deprecate-then-delete flow avoids time spent recovering from a broken deploy.

Illustrative estimate. Assume a workspace with 15 dead libraries, each with build, lint and test targets, and assume each task takes 1 minute when uncached. Assume shared-configuration changes that affect all of them land 10 times a month. That is 15 × 3 × 1 × 10 = 450 task-minutes a month of CI work that verifies nothing. Add an assumed 30 minutes per dead library during each major upgrade to fix or check code no one uses, and 15 libraries cost an assumed 7.5 engineer-hours per upgrade. These inputs are assumptions for illustration, not measurements; plug in your own task durations, change frequency and upgrade cadence to estimate your workspace.

The engineer-time portion usually matters more than the CI minutes. Machine time is cheap and parallel, while time spent fixing, reviewing or explaining dead code comes directly out of feature work.

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 unused libraries, 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.