What is dependsOn in Nx and how does it turn the project graph into a task graph?

Nx builds a project graph from your workspace: which projects import or declare dependencies on which. That graph says nothing about execution order. libs/db being a dependency of apps/api does not, by itself, tell Nx to build db before api. The dependsOn setting on a target is what converts project relationships into ordered edges between tasks. The resulting structure is the task pipeline, or task graph.

Each entry in dependsOn takes one of two forms:

Entry Meaning Edge created for api:build
"^build" Run build on every project this one depends on, first db:build → api:build, auth:build → api:build
"codegen" Run codegen on the same project, first api:codegen → api:build

Take apps/api, which depends on libs/auth, which depends on libs/db. Configure build with dependsOn: ["^build", "codegen"]:

Project graph              Task graph for "nx build api"

 api                        db:codegen
  └─> auth                     │
       └─> db                db:build ──> auth:codegen
                                              │
                                         auth:build ──> api:codegen
                                                             │
                                                        api:build

The caret walks the dependency edges. The bare name stays inside one project. Here each build must wait for its own codegen and for its dependencies' build tasks. Tasks with no edge between them can still run in parallel.

A hardcoded CI script such as "build db, then auth, then api" encodes the same order by hand. It stops matching reality once someone adds an import. Because Nx derives the order from the project graph, a new dependency changes the pipeline automatically, and nx affected can schedule only the tasks that the change actually touches, in a valid order.

# Write workspace-wide defaults so every project's build target gets the same pipeline.
# Assumes each project (api, auth, db) defines its own "codegen" target.
cat > nx.json <<'EOF'
{
  "targetDefaults": {
    "build": {
      "dependsOn": ["^build", "codegen"],
      "cache": true
    },
    "test": {
      "dependsOn": ["build"]
    }
  }
}
EOF

# "^build": first run build on every project api depends on (auth, then db).
# "codegen": first run codegen on the same project.
# Order comes from the project graph, so no script lists db -> auth -> api.
npx nx build api

# Open the task graph for this command without running it.
npx nx build api --graph

# test depends on the same project's build, which pulls in the chain above.
npx nx test api

An nx.json targetDefaults block where "^build" orders builds across dependent projects and "codegen" orders a target within the same project, followed by commands that run and visualize the resulting task graph.

Why put dependsOn rules in nx.json targetDefaults?

That scheduling only works if the edges are defined consistently. You can write dependsOn inside every project's configuration, but in a workspace with dozens of services and libraries those copies drift. One library gets ^build, a newer one is created without it, and nothing fails until a CI run builds a consumer before its dependency.

targetDefaults in nx.json avoids that drift. A rule declared there applies to every project that has a target with that name, including projects added later. The minimal setup has two entries. Under build, set dependsOn to ["^build"], which means "build all of this project's dependencies first." Under test, set dependsOn to either ["build"], to build the project itself before testing it, or ["^build"], to build only its dependencies. Section 4 covers how to choose between them. With these two lines, a new package inherits the correct order as soon as it defines a build or test target.

The rule also lives in one file, so reviewing it is easy. A change to build order is a diff to nx.json, and it goes through review like any other infrastructure change. Nobody has to grep through project files to reconstruct the pipeline.

Platform teams that support many backend projects in one repository benefit most. They answer questions like "why did this test run before that build?" and enforce conventions across teams, and with targetDefaults there is one place to read and one place to fix. Project-level overrides are still possible, but they become visible exceptions to the default rather than the norm.

{
  "$schema": "./node_modules/nx/schemas/nx-schema.json",
  "targetDefaults": {
    "build": {
      "dependsOn": ["^build"]
    },
    "test": {
      "dependsOn": ["build"]
    }
  }
}

A minimal nx.json where every project's build first builds its dependencies (^build), and every project's test first builds the project itself (build). Use ["^build"] for test instead if tests only need dependencies built.

When should a project override targetDefaults, and what does it cost?

A project's own configuration (a target in project.json, or the nx section of package.json) is applied on top of the matching targetDefaults entry. Options are generally merged. A dependsOn array declared at the project level usually replaces the default array instead of appending to it. As a result, a project that adds one extra prerequisite has to restate every default edge it still wants, or it silently loses them. Merge rules have changed across Nx releases, so check the exact behavior against the docs for your installed version before you rely on it.

An override is justified when the project actually behaves differently from its peers:

  • It runs a codegen target before build.
  • Its integration tests need another project's build artifact, but nothing in the source code imports that project, so the project graph has no edge to it. A typical example is a service that calls another service over HTTP.

Wanting a faster local loop, or working around a flaky target, is not a valid reason. Those problems belong in the default or in the target itself.

For cases the ^build string shorthand cannot express, dependsOn accepts an object form. You name a target and then scope it in one of two ways:

  • projects: an explicit list of project names or patterns. This covers the runtime-only dependency described above.
  • dependencies: a flag that applies the target across the project's graph dependencies.

Confirm the accepted keys for your version.

Every override has a cost. Once a few projects carry their own dependsOn, nx.json stops being the complete pipeline definition. If you later fix an edge in the default, that fix never reaches the projects that replaced it. Keep overrides rare, and add a comment to each one stating why the project differs.

// apps/orders-service/project.json
// Nx reads project.json with comments allowed. Check this for your Nx version.
{
  "name": "orders-service",
  "targets": {
    "integration-test": {
      // WHY THIS OVERRIDE EXISTS: orders-service calls payments-service over HTTP
      // in its integration tests. No source import links them, so the project
      // graph has no edge to payments-service.
      // This array REPLACES the default from nx.json, so the default edge is restated.
      "dependsOn": [
        // Restated from targetDefaults. Without it, this project's
        // own dependencies would no longer be built first.
        "^build",
        // Object form: build one named project that is not in the graph.
        { "target": "build", "projects": ["payments-service"] }
      ]
    },
    "build": {
      // This project really differs: it generates API clients before compiling.
      "dependsOn": [
        "codegen",
        // Equivalent to "^build": run build on all graph dependencies.
        { "target": "build", "dependencies": true }
      ]
    }
  }
}

A project.json override that restates the default ^build edge, uses the object form of dependsOn for a runtime-only dependency and a codegen step, and records why each override exists.

Do your tests need build, ^build, or neither?

The right edge depends on what the test runner actually loads from disk. There are three common cases.

Tests that execute their own compiled output. Examples are integration tests that start the built server or run assertions against files in dist. These need build, the same project's build target. Without that edge, the tests can pass against a stale artifact from an earlier run.

Tests that import dependencies through their built packages. This happens when a library's package.json entry point resolves to compiled files rather than source. These tests need ^build, which builds every upstream project first. The project's own build is not required.

Tests that run against source through a transpiler. A runner that compiles TypeScript on the fly, with path mappings resolving workspace imports to source, reads nothing from any dist directory. These tests need no build edge.

Option Safety CI time Parallelism
build Covers own artifacts only Adds one build per project Test waits on its own build
^build Covers upstream artifacts Builds the whole dependency subtree Test waits on every upstream build
neither Correct only if nothing reads dist Lowest Tests start immediately and run side by side

Unnecessary edges are not free, even when builds are cached. An unneeded ^build makes a leaf library's tests wait behind a chain of upstream builds that could otherwise run alongside them. On a cache miss, that waiting becomes the critical path of the CI run.

A broad test: ["^build"] default is worth the cost when you cannot say with confidence how each project resolves its imports. It is also worth it when a missed edge would ship a broken artifact. Avoid the broad rule once module resolution is uniform and points at source. At that point it only adds latency.

How do dependsOn, outputs, and caching interact?

At that point, the edges that remain carry more weight, because dependsOn only orders tasks. It does not move files. What makes an upstream artifact available to a downstream task is the combination of an ordering edge and a declared outputs list.

When Nx gets a cache hit for a target, it replays the terminal output and restores only the paths listed in outputs. If build writes to dist/libs/auth but outputs points somewhere else, or Nx cannot infer the location, the cache hit is still treated as a success. On a fresh CI checkout this means build is reported as complete, no dist directory exists, and the downstream test or bundle task fails on a missing file. This is hard to diagnose because the failure appears only on a warm cache. A cold run executes build for real, writes the files, and passes.

The target configuration in the example below sets this up in targetDefaults. build gets dependsOn: ["^build"], cache: true, and outputs set to {workspaceRoot}/dist/{projectRoot}. With all three in place, a downstream task that reads a dependency's compiled output receives it whether that output was built or restored.

This is where the time saving comes from. As an illustrative estimate, assume 40 CI runs a day, a 6-minute library build, and a 70% cache hit rate. Restoring outputs instead of rebuilding saves about 168 minutes of runner time per day. That saving depends on the restored files actually being present.

// nx.json (Nx parses this file as JSONC, so comments are allowed)
{
  "namedInputs": {
    "default": ["{projectRoot}/**/*"],
    "production": ["default", "!{projectRoot}/**/*.spec.ts"]
  },
  "targetDefaults": {
    "build": {
      // Ordering only: build every dependency project before this one
      "dependsOn": ["^build"],
      "cache": true,
      // Hash this project's sources plus its dependencies' production sources
      "inputs": ["production", "^production"],
      // Must match where the build tool actually writes files.
      // On a cache hit, Nx restores only these paths.
      "outputs": ["{workspaceRoot}/dist/{projectRoot}"]
    },
    "test": {
      // Tests read compiled dependency output, so the upstream build
      // must have run or been restored before tests start
      "dependsOn": ["^build"],
      "cache": true,
      "inputs": ["default", "^production"],
      // Declared so coverage reports also come back on a cache hit
      "outputs": ["{workspaceRoot}/coverage/{projectRoot}"]
    }
  }
}

An nx.json targetDefaults block that pairs dependsOn with outputs, so a cache hit on build restores dist/ files before downstream test tasks read them.

How can you verify the task graph and catch missing edges?

Being correct matters more than the time saved, and you only know the outputs are correct if the task graph has every edge it needs. The quickest check is to render it. Running nx graph shows project-level dependencies. Adding --graph to a task command, such as nx run-many -t test --graph, shows the task graph Nx will actually execute, with each dependsOn edge drawn between targets. If api:test has no arrow to shared-utils:build, Nx will not order them.

Missing edges rarely fail on a laptop. A warm cache restores the library's outputs before anyone notices, and a dist directory left over from yesterday's build satisfies the import anyway. The ordering is wrong, but the files happen to be there. CI starts clean and runs many tasks at once. A test may then start before the build it needs, or while that build is still writing files. Whether it passes depends on scheduling, so the failure looks intermittent.

To reproduce CI conditions on purpose:

  • Delete every build output directory.
  • Run with --skip-nx-cache so nothing is restored.
  • Set --parallel higher than CI uses, so a missing ordering edge shows up as a failure.

Running with --verbose prints the details for each task as it runs, which helps you see which task started too early.

Edges can also appear that you did not expect. Entries in implicitDependencies, plugin-inferred targets, and import analysis all add project relationships, and ^build follows every one of them. The result can be long chains, or a cycle the graph view will show you. Trace each edge back to the file or setting that created it. Remove stale implicitDependencies entries. If two projects import each other, move the shared code into a third library so the dependency runs in one direction.

How do you migrate from hardcoded CI scripts to targetDefaults, and what are the alternatives?

Start with the CI scripts themselves. Every hand-written sequence encodes an ordering assumption.

  1. List the order the scripts enforce. Write down each step, such as "build shared-types, then api, then run tests", and note why each step comes before the next. Some orderings reflect real dependencies. Others are habits nobody questioned.
  2. Encode the real ones in targetDefaults. Most of the list usually collapses into a few rules in nx.json, such as build depending on ^build. Add per-project dependsOn only for the exceptions.
  3. Remove the manual sequencing. Replace the chained steps with a single nx run-many -t build test or nx affected invocation, and let the task graph schedule the work.
  4. Compare on clean runs. Disable or clear the cache, run both pipelines, and diff the outputs and test results. A warm cache can hide a missing edge, because a stale artifact satisfies the step that should have rebuilt it.
Approach Maintenance cost CI time Risk of ordering bugs
Hand-ordered scripts High: every new project needs a script edit Longest: steps run serially High: order drifts from imports
Per-project dependsOn only Medium: rules repeated per project Parallel, but inconsistent Medium: easy to forget a project
Broad targetDefaults Low May over-serialize Low
Narrow targetDefaults plus overrides Low to medium Best parallelism Low, if the overrides are reviewed

Illustrative estimate. These inputs are assumed, not measured:

  • 12 projects, each taking 3 minutes to build and test, run serially: 36 minutes.
  • A graph of depth 3 with an agent running four tasks in parallel.
  • The critical path is roughly 3 levels × 3 minutes, plus queueing for the widest level.

Under those assumptions, the pipeline finishes in about 12–15 minutes.

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 dependsOn targetDefaults, 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.