How does Nx build the project graph?

The project graph is a directed graph in which each node is a project (an app or library) and each edge is a dependency between projects. Nx builds it by combining three inputs: TypeScript/JavaScript imports it can resolve to workspace projects, package manifests that reference other workspace packages, and explicit configuration such as implicitDependencies in a project's config.

imports + package.json + project config → project graph → interactive UI (nx graph) / JSON export

Edges are labeled by how Nx found them. The label tells you how much evidence backs the edge.

Edge type Where it comes from What it means for an audit
Static Top-level import statements Hard compile-time coupling. Removing it requires a code change.
Dynamic import() expressions, often for lazy loading A real dependency that loads on demand. It is still coupling, even if bundle splitting hides it.
Implicit implicitDependencies and other config Declared by a human. Check that it is still true, because nothing in the code enforces it.

The core limitation is that the graph shows only what Nx can infer from source and config. It cannot see:

  • runtime dependency injection wiring
  • modules loaded from computed strings
  • behavior selected by environment variables
  • HTTP or message-queue calls between services

Two services with no edge between them can still fail together in production. A clean graph shows that code is decoupled. It does not show that the systems are decoupled.

The graph can also be stale. Nx caches project graph state and the daemon keeps it in memory, so after branch switches or config edits the graph may not match the code on disk. nx reset clears both. The next command then rebuilds the cached state from scratch, so it will run noticeably slower once.

+----------------------+  +----------------------+  +----------------------+
| Source imports       |  | package.json         |  | Project config       |
|  import x from 'lib' |  |  deps on other       |  |  implicitDependencies|
|  import('lib')       |  |  workspace packages  |  |  in project.json     |
+----------+-----------+  +----------+-----------+  +----------+-----------+
           |                         |                         |
   static + dynamic               static                   implicit
         edges                     edges                     edges
           |                         |                         |
           +-------------------------+-------------------------+
                                     |
                                     v
               +------------------------------------------+
               |              PROJECT GRAPH               |
               | nodes: apps, libs   edges: dependencies  |
               | state held by daemon + local cache       |
               | stale? nx reset -> cold rebuild          |
               +---------------------+--------------------+
                                     |
           +-------------------------+-------------------------+
           v                                                   v
+----------------------+                            +----------------------+
| Interactive UI       |                            | JSON export          |
|  nx graph            |                            |  for audit scripts   |
+----------------------+                            +----------------------+
+--------------------------------------------------------------------------+
| Not in the graph: DI wiring, string-built module paths, env-driven       |
| config, HTTP and message-queue calls between services                    |
+--------------------------------------------------------------------------+

Nx merges resolved imports, workspace package manifests, and explicit project config into a cached project graph that feeds both the nx graph UI and a JSON export, while runtime wiring, string-loaded modules, environment-driven config, and network calls stay invisible to it.

How does a graph-based dependency audit work?

An audit built on the project graph is a short pipeline. Each stage has its own job.

  1. Nx computes the graph. It finds projects from their configuration files (project.json, workspace package.json files, and projects inferred by installed plugins). It then analyzes source files and manifests to produce edges. The daemon and local cache hold the result so later commands don't repeat the analysis.
  2. You explore it interactively. nx graph with --focus, --exclude, or --affected answers one-off questions about a project or a branch.
  3. You export it as data. nx graph --file=graph.json writes nodes and edges to disk. From this point the audit no longer depends on Nx's UI. It is ordinary JSON processing.
  4. Scripts query the data. A script first checks that the file has the shape it expects, then computes signals such as fan-in, libraries with no dependents, app-to-app edges, cycles, and tag-based layer violations.
  5. Rules lock in the findings. Tags on projects and the enforce-module-boundaries lint rule turn agreed constraints into build failures, so fixed problems don't come back.
  6. Snapshots show drift. Storing each run's output and diffing it against the previous one shows new edges as they appear, not months later.

The sections below cover each stage in turn. Every stage inherits the limits of the first one. If Nx cannot infer an edge, no later script will find it.

Who should run a dependency audit, and when?

A dependency audit answers questions that come up whenever someone owns shared code. The most common one is blast radius. Before you change a shared library's public API, you need to know which applications and libraries import it, directly or transitively, and how many teams own them. The graph also surfaces removal candidates: libraries with no dependents, or with a single consumer that could absorb them. It exposes layering violations too, such as a domain library importing from an application or a UI package reaching into data-access code. During review, the affected subset of the graph shows what a branch actually touches. This is often more than the diff suggests.

Some moments make an audit worth the time:

  • Before a large refactor, so the migration order follows real dependency edges instead of guesses.
  • While onboarding to an unfamiliar workspace, where the graph is a faster map than reading every project.json.
  • Before adopting module-boundary rules, because you need to know how many existing edges would fail a new constraint before you turn it on.
  • On a recurring CI schedule, so drift shows up as a small diff between snapshots rather than a surprise months later.

A graph audit is the wrong tool in two cases. In a workspace with a handful of projects, the structure is already obvious and the audit adds ceremony. More importantly, the graph only sees static imports and declared dependencies. Coupling through runtime configuration, message queues, or HTTP calls between services won't appear in it. For that kind of coupling, use distributed tracing or contract tests.

When should you use project graph JSON for auditing?

Use the exported graph when the question is about build-time structure and you need an answer you can repeat or check automatically:

  • The workspace is too large to reason about by eye. Once the unfocused nx graph view is unreadable, counting and filtering edges in JSON is the only practical way to see the whole workspace.
  • Several teams share libraries. Fan-in per project, joined with ownership tags, shows which changes need coordination across teams before anyone opens a pull request.
  • You need evidence, not impressions. A list of edges with source, target, and type can be attached to a design review or ticket, and someone else can regenerate it from the same commit.
  • You want to track a trend. Questions like "is coupling into shared-utils growing?" only make sense when you compare snapshots, and only data can be compared.
  • You are preparing to enforce rules. Running a proposed tag constraint against the exported graph shows how many existing edges would fail before you switch the lint rule on.
  • Most of the code is TypeScript or JavaScript. These are the languages Nx analyzes out of the box, so the graph is most complete there.

When should you avoid relying on a graph audit?

Skip it, or pair it with other tools, in these cases:

  • Small or simple workspaces. If you can list every project and its dependencies from memory, scripts and CI checks add maintenance without adding information.
  • Coupling happens at runtime. Services that talk over HTTP, share a message topic, or share a database schema look independent in the graph. Use tracing, contract tests, or schema ownership reviews instead.
  • Languages Nx doesn't analyze. If part of the workspace is written in a language Nx has no plugin for, its dependencies come only from hand-maintained implicitDependencies. An audit there checks your declarations, not your code.
  • The graph may be stale. After branch switches, rebases, or config edits, run nx reset before trusting an export. An audit run against cached state can report edges that no longer exist or miss new ones.
  • You need a verdict on design quality. Fan-in, missing dependents, and edge counts point to places worth a closer look. They don't decide whether a library is well designed, and treating them as targets encourages gaming, such as extracting single-file libraries just to lower a number.
  • You can't maintain the parsing code. The JSON shape is not a stable public contract and can change between Nx releases. If no one owns the audit script, it will eventually break silently or get disabled, and an interactive nx graph --focus session is the more honest choice.

How do you use the nx graph command for interactive exploration?

Running nx graph starts a local server and opens an interactive view of the workspace. In a workspace with hundreds of projects, the full view is not useful on its own. Narrow it first.

--focus=<project> shows one project and the projects connected to it, both its dependencies and its dependents. This is usually the question you actually have, such as "what will break if I change this library?" --exclude removes projects that add edges without adding information, for example a shared utilities library that nearly everything imports. If your workspace is organized by directory, such as one folder per domain or team, --groupByFolder draws those folders as boxes. Cross-domain edges then stand out against edges that stay within a domain.

To understand why one project depends on another, select the edge between them in the UI. For static dependencies, it shows the files that create the link. That tells you whether the coupling comes from a single stray import or from a real dependency on the library's API.

Before a review or merge, run nx graph --affected --base=<ref> --head=<ref>. It shows which projects the branch touches, so a change that is unexpectedly large becomes visible before anyone reads the diff.

Some questions don't need a picture. nx show projects lists project names, and nx show project <name> prints one project's resolved configuration. Both are faster than opening the graph.

The interactive view has limits. In a large workspace, an unfocused graph is mostly visual noise, and a screenshot pasted into a ticket rarely settles a decision. Nobody can diff it, filter it, or rerun it next quarter. For any check you plan to repeat, export the graph as JSON.

npx nx graph --focus=payments-core

npx nx graph --focus=payments-core --exclude=shared-utils

npx nx graph --groupByFolder

npx nx graph --affected --base=origin/main --head=HEAD

npx nx show projects                    # list all project names
npx nx show project payments-core      # one project's resolved configuration

npx nx graph --file=project-graph.json

Common nx graph invocations for focused, decluttered and branch-scoped exploration, the lighter nx show commands, and exporting the graph to JSON for repeatable checks.

How do you export and query the project graph JSON?

When a check needs to be repeated, export the graph instead. Running nx graph --file=graph.json writes the project graph to disk without opening the browser view. The result is plain data you can diff between commits, query in CI, and attach to a ticket as evidence.

In the versions most teams run, the file holds two broad structures. Nodes are keyed by project name and carry metadata such as project type, root path, and tags. Dependencies are keyed by source project and list edges with source, target, and type (static, dynamic, or implicit). Field names and nesting have changed between Nx releases, so open your own file before writing anything against it. Every audit script should first check that the keys it expects exist and exit non-zero if they don't. A query that silently returns an empty list looks the same as a clean workspace.

With the shape confirmed, a few short jq filters or a small Node script cover the common audit questions:

Query How to compute What it suggests
Highest inbound dependents Count edges per target Large blast radius for changes
Zero dependents Libraries never appearing as a target Possible removal candidates
App → app edges Edges where both ends have type app Deployables coupled at build time
Layer violations Match tags or root paths of source against target Libraries reaching across boundaries

Treat these counts as signals, not verdicts. A widely imported utility library with a stable API can be perfectly healthy. A project with almost no edges can still be tightly coupled through shared runtime state such as a database schema, environment variables, or a message topic, none of which the graph sees.

// audit-graph.js — run after: nx graph --file=graph.json
// Usage: node audit-graph.js graph.json
const fs = require('fs');
const raw = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));

// Many Nx versions wrap the data in a top-level "graph" key. Check your own file.
const g = raw.graph ?? raw;
if (typeof g.nodes !== 'object' || typeof g.dependencies !== 'object') {
  console.error('Unexpected graph shape: missing nodes/dependencies. Inspect the file.');
  process.exit(1); // fail loudly instead of reporting an empty, "clean" result
}

const nodes = g.nodes;
const edges = Object.values(g.dependencies).flat()
  .filter((e) => nodes[e.target]); // drop edges to npm packages and other non-project targets

// Fan-in: dependents per project. A signal of blast radius, not a verdict.
const fanIn = {};
for (const e of edges) fanIn[e.target] = (fanIn[e.target] ?? 0) + 1;
const top = Object.entries(fanIn).sort((a, b) => b[1] - a[1]).slice(0, 10);
console.log('Most dependents:', top);

// Libraries nothing depends on: candidates to review, not to delete blindly.
const unused = Object.keys(nodes)
  .filter((n) => nodes[n].type === 'lib' && !fanIn[n]);
console.log('No dependents:', unused);

// App -> app edges couple deployables at build time.
const appToApp = edges.filter(
  (e) => nodes[e.source].type === 'app' && nodes[e.target].type === 'app');
console.log('App -> app:', appToApp.map((e) => `${e.source} -> ${e.target}`));

// Layer rule example: libs tagged type:ui must not depend on libs tagged type:data-access.
const tags = (n) => nodes[n].data?.tags ?? [];
const violations = edges.filter(
  (e) => tags(e.source).includes('type:ui') && tags(e.target).includes('type:data-access'));
console.log('Layer violations:', violations.map((e) => `${e.source} -> ${e.target}`));

A small Node script that validates the exported graph.json shape, exits non-zero if it is unexpected, and then lists high fan-in projects, libraries with no dependents, app-to-app edges, and a sample tag-based layer violation.

How do you find and break circular dependencies?

A cycle exists when project A depends on B and B, directly or through intermediate projects, depends back on A. In the exported JSON, each project lists its outgoing edges under dependencies, so a depth-first walk that tracks the current path will surface every loop. In day-to-day work, cycles usually appear first as errors from the @nx/enforce-module-boundaries lint rule, which reports circular imports between projects and names the projects on the path. Treat that path as the starting point. The edge that closes the loop is rarely the one that introduced the design problem.

There are two standard fixes:

  • Extract shared code. Move the types, constants, or helpers that both projects need into a new, lower-level library that depends on neither. This works well when the shared code is stable and has a clear name.
  • Invert the dependency. Have the lower-level project define an interface or injection point, and let the higher-level project supply the implementation. The edge then runs in one direction only.

Extraction is easy to do mechanically, which is its weakness. Each new library adds its own configuration, build and test targets, and a node in the graph. A workspace that resolves every cycle by extraction can end up with dozens of single-file libraries whose boundaries mean nothing. Prefer inversion when the coupling reflects a real layering decision.

During cleanup, also review implicitDependencies. They are declared by hand and are not checked against imports, so they drift over time. Stale or excessive entries inflate affected sets and slow CI. Missing entries let changes skip rebuilds and tests that should have run.

// find-cycles.js: list project-level cycles in an exported Nx graph.
// Export first: npx nx graph --file=graph.json
// Run: node find-cycles.js graph.json
const fs = require('fs');

const { graph } = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
const deps = graph.dependencies; // { project: [{ source, target, type }] }

const state = {}; // undefined = unvisited, 1 = on current path, 2 = done
const path = [];
const cycles = [];

function visit(project) {
  state[project] = 1;
  path.push(project);
  for (const edge of deps[project] || []) {
    // Skip edges to npm packages and other non-project nodes.
    if (!graph.nodes[edge.target]) continue;
    if (state[edge.target] === 1) {
      // Target is already on the path, so this edge closes a loop.
      // The type ('static', 'dynamic', 'implicit') shows whether a
      // hand-declared implicitDependencies entry is part of it.
      const loop = path.slice(path.indexOf(edge.target));
      cycles.push(`${[...loop, edge.target].join(' -> ')}  (closing edge: ${edge.type})`);
    } else if (!state[edge.target]) {
      visit(edge.target);
    }
  }
  path.pop();
  state[project] = 2;
}

for (const project of Object.keys(graph.nodes)) {
  if (!state[project]) visit(project);
}

console.log(cycles.length ? cycles.join('\n') : 'No project cycles found.');
process.exitCode = cycles.length ? 1 : 0;

A depth-first walk over the JSON from nx graph --file that prints each cycle it finds and the type of the edge that closes it, so implicit edges can be checked during cleanup. Loops that share an already-visited node may be reported once.

How do you enforce audit findings with tags and module boundaries?

Audit findings only last if the next violation fails a build. Nx handles this with tags on each project and a lint rule that checks imports against those tags.

Tag by scope and type

Add a tags array to each project's configuration, usually with two dimensions. scope: (for example scope:billing, scope:shared) says which domain owns the code. type: (for example type:feature, type:data-access, type:util) says which layer it is. Two dimensions let one rule say "billing may use shared" while another says "utilities may not import features."

Encode allowed edges

The Nx enforce-module-boundaries ESLint rule reads a list of dependency constraints. Each constraint maps a source tag to the tags it may depend on. Any import that breaks a constraint becomes a lint error. Because the rule checks real imports, it catches drift as soon as it happens. Run lint in CI on affected projects, and a forbidden edge cannot merge.

Rolling out to an existing workspace

Turning on strict constraints in a mature repository can surface a large backlog of violations at once. There are two common responses:

Approach Upfront cost Risk When it fits
Big-bang cleanup High; blocks feature work Large, hard-to-review refactors Small backlog, clear ownership
Temporary exceptions Low; rule ships immediately Exceptions quietly become permanent Large backlog, many teams

Exceptions are usually the practical choice. In that case, treat each suppression as debt:

  • Give it an owner and a ticket reference in the suppression comment.
  • Count suppressions in CI so the number can only go down.

Without that tracking, the next audit will find the same edges, now marked as allowed.

How can a repeatable audit save engineering time, and what are the alternatives?

That tracking works best as one step in a pipeline that runs on every merge to the main branch. CI exports the project graph JSON with nx graph --file=graph.json. A short script then reads the nodes and dependencies maps and fails the build on forbidden edges or threshold breaches, such as a library whose fan-in exceeds an agreed limit. The script also stores its result as an artifact. Diffing that artifact against the previous run shows drift edge by edge, so reviewers see "billing now depends on auth-internal" while the change is still small enough to revert.

The costs are a one-time setup and ongoing maintenance. The graph JSON is an internal format, so Nx upgrades can change its shape. Pin the parsing logic in one place and test it against a fixture graph. The payoff is fewer manual audits, faster reviews, and smaller affected sets in CI as coupling stops growing.

Illustrative estimate (assumed numbers, not a benchmark)

Net hours saved per year = (manual audits avoided × hours per audit) − setup hours − (upgrades per year × hours per upgrade fix)

Assumed inputs: 4 quarterly audits avoided at 16 h each, 24 h setup, and 2 upgrades at 4 h each. Calculation: (4 × 16) − 24 − (2 × 4) = 32 h in the first year. From the second year, without the setup cost, the saving is 56 h.

Approach Catches Misses
Interactive graph only Structure that is visible to someone looking at it Drift between the times someone looks
Lint rules only Tag violations at the import site Trends such as rising fan-in
nx show project Answers to ad hoc, single-project questions The workspace-wide view
Runtime tracing Coupling over HTTP or queues Build-time edges

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 graph dependencies, 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.