Who should use dependsOn and targetDefaults?

Use them if you maintain an Nx workspace where some tasks can't run correctly until other tasks have finished. Typical signs:

  • Backend and platform engineers whose services build against shared libraries, generated API clients, Prisma or protobuf output, or schema packages in the same repo.
  • Teams whose CI has ordering rules in job definitions or chained scripts, such as "run codegen, then build libs, then build services," that nobody can verify locally.
  • Repos that see intermittent failures on a clean runner, like a missing dist folder, stale generated code, or a build that passes on a laptop but not in CI.
  • Maintainers of many similar projects who want one reviewed definition of what build, test and lint mean, instead of a copy in every project.json.

You probably don't need much of this if your repo has two or three packages with no generated code and builds that finish in seconds. A plain script chain is easier to read at that size. The trade-off is covered at the end of this article.

How does Nx turn dependsOn into a task graph and build order?

This guide is for backend and platform engineers running multi-project monorepos where a service can't build until its shared libraries, generated clients or schema packages exist. If you've seen a build pick up stale artifacts or fail on a missing dist folder, the cause is usually how the task pipeline is defined.

Nx works with two separate graphs. The project graph records which projects depend on which. Nx builds it by analyzing source imports, reading package.json dependencies between workspace packages, and adding any implicitDependencies you declare for links the code doesn't show, such as a service that reads another project's config files at runtime.

The task graph is derived from it. When you run a target, for example building one API, Nx creates a node for that task (project:target). It then reads the target's dependsOn rules and adds edges to the tasks those rules point at. Some rules point at the same target on upstream projects, and others at other targets on the same project. Nx repeats this for each new node until nothing new is added.

Execution order comes only from this graph. A task becomes eligible to run when every task it depends on has finished successfully. Nx runs eligible tasks in parallel, up to its configured concurrency limit. The order in which projects appear in the workspace, or targets appear in a config file, has no effect. If two tasks have no edge between them, Nx is free to run them in either order or at the same time. A missing dependsOn rule therefore shows up as an intermittent race rather than a consistent failure.

+-------------+   +-----------------+   +----------------------+
| source      |   | package.json    |   | implicitDependencies |
| imports     |   | workspace deps  |   | (declared links)     |
+------+------+   +--------+--------+   +----------+-----------+
       +-------------------+-----------------------+
                           v
  +-------------------------+   +--------------------------+
  | PROJECT GRAPH           |   | dependsOn rules          |
  | which project needs     |   | "^build": same target on |
  | which (no tasks yet)    |   | upstream projects        |
  +------------+------------+   | "codegen": other target  |
               |                | on the same project      |
               |                +-------------+------------+
               +--------------+--------------+
                              v
+--------------------------------------------------------------+
| TASK GRAPH for: nx run api:build (expand until no new nodes) |
|  shared-lib:build     api-client:build      api:codegen      |
|         |                    |                   |           |
|         +--------------------+-------------------+           |
|                              v                               |
|                          api:build                           |
+------------------------------+-------------------------------+
                               v
+--------------------------------------------------------------+
| SCHEDULER                                                    |
| Runs a task once every task it depends on has succeeded.     |
| Unlinked tasks may run in parallel (up to concurrency limit).|
| Order of projects/targets in config files has no effect.     |
+--------------------------------------------------------------+

Nx combines the project graph (from imports, package.json dependencies and implicitDependencies) with each target's dependsOn rules to build a task graph, and execution order and parallelism come only from that graph's edges.

How does it work, step by step, when you run a target?

The previous section describes the graphs. This is the sequence Nx goes through when you run something like nx run api:build:

  1. Resolve configuration. For each project, Nx merges targetDefaults from nx.json, settings inferred by plugins, and the project's own project.json or package.json nx block. The result is the effective dependsOn, inputs, outputs and cache for every target.
  2. Build the project graph. Imports, workspace package.json dependencies and implicitDependencies determine which projects depend on which.
  3. Expand the task graph. Starting from api:build, Nx applies each target's dependsOn rules. ^build adds build on upstream projects, and codegen adds a task on the same project. It repeats for every new task until the graph stops growing.
  4. Hash each task. For cacheable tasks, Nx computes a hash from the files matched by inputs, including dependency inputs such as ^production, along with other factors such as the command being run.
  5. Check the cache. If the hash matches a previous run, Nx replays the stored terminal output and restores the files listed in outputs instead of running the command. On a miss, it runs the command and stores the result.
  6. Schedule. A task starts only after all of its prerequisites have succeeded, whether they ran or were restored from cache. Independent tasks run concurrently. If a prerequisite fails, the tasks that depend on it do not run.

dependsOn controls step 3, inputs controls step 4, and outputs determines whether step 5 leaves the files the next task needs. Most pipeline bugs come from one of those three fields.

What is the difference between ^build and build in dependsOn?

The caret is the whole difference. "dependsOn": ["^build"] on a project's build target means "before building this project, run build on every project it depends on." Nx walks the project graph edges (imports and declared dependencies), so if api imports shared-db and shared-db imports shared-config, the build order becomes shared-config, then shared-db, then api. Without the caret, "dependsOn": ["build"] refers to the same project. A docker target on api with that rule guarantees the image is built from fresh dist output rather than whatever was left on disk.

In a typical worked setup, build declares ^build, and docker declares build. Running docker for api then pulls in the full upstream chain transitively, with no extra configuration.

Form Runs Typical use
^build build on each dependency project Libraries must compile before consumers
build build on the same project docker, deploy, e2e need local artifacts
Object form A named target on a chosen project set, optionally with params Mixed rules, forwarding CLI args

The string forms cover most needs. For finer control, dependsOn also accepts objects. An object names a target. It can also say which projects the rule applies to: the dependencies, the same project, or an explicit list. It can also control whether the parameters you passed on the command line are forwarded to the prerequisite task. The field names and accepted values have changed across Nx releases, so check the exact schema against the documentation for your installed version before relying on it.

{
  // nx.json (Nx parses this file as JSON with comments)
  "targetDefaults": {
    "build": {
      // Caret form: build every dependency project first.
      // api -> shared-db -> shared-config builds shared-config, then shared-db, then api.
      "dependsOn": ["^build"]
    },
    "docker": {
      // No caret: run this project's own build first, so the image uses fresh dist output.
      // Because build declares ^build, the whole upstream chain runs too.
      "dependsOn": ["build"]
    },
    "deploy": {
      "dependsOn": [
        // Object form of "^build": the build target on dependency projects.
        { "target": "build", "dependencies": true },
        // Object form scoped to the same project, forwarding CLI params
        // (e.g. --configuration=production) to the prerequisite build.
        { "target": "build", "params": "forward" }
      ]
    },
    "e2e": {
      "dependsOn": [
        // Object form with an explicit project list instead of graph edges.
        // Check these field names against the docs for your installed Nx version.
        { "target": "serve", "projects": ["api"] }
      ]
    }
  }
}

A worked nx.json showing ^build (dependency projects), plain build (same project), and the object form for forwarding params or targeting an explicit project list. Verify the object fields against the schema for your installed Nx version.

Why use targetDefaults in nx.json as the single source of truth?

Each target name, such as build, test or lint, means the same thing in every project. That makes the target name a natural key for pipeline rules. When targetDefaults in nx.json declares that every build depends on ^build, which inputs affect its hash, where its outputs land and whether it is cacheable, every project inherits that contract without restating it. A reviewer who wants to know how builds are ordered reads one block instead of dozens of project.json files.

Projects can still deviate. A project.json target, or the nx block in a package.json, can set the same fields for one project. The project-level value generally takes precedence over the default for that field. Treat arrays like dependsOn and inputs as replaced rather than appended. If a project redeclares dependsOn to add a codegen step, it must also restate ^build, or it silently drops the ordering. Inspect the resolved configuration, for example with nx show project <name>, rather than assuming how the merge behaves.

This is why overrides should be rare and explained. Leave a short note next to each one or in the project's README saying why the default does not fit. Then the next engineer can tell a deliberate exception from copy-paste drift.

The payoff is mostly in maintenance and debugging:

  • Less to review. You maintain one definition per target instead of per-project copies that slowly diverge.
  • One change, every project. Changing a cache input or adding a prerequisite is a single reviewed diff, not a sweep across the repo.
  • Faster diagnosis. When build order looks wrong, the cause is either the shared default or a known, documented override. That narrows the search considerably.
// nx.json: one pipeline contract, keyed by target name
{
  "namedInputs": {
    "default": ["{projectRoot}/**/*"],
    "production": ["default", "!{projectRoot}/**/*.spec.ts"]
  },
  "targetDefaults": {
    "build": {
      "dependsOn": ["^build"],
      "inputs": ["production", "^production"],
      "outputs": ["{projectRoot}/dist"],
      "cache": true
    },
    "test": { "inputs": ["default", "^production"], "cache": true },
    "lint": { "inputs": ["default"], "cache": true }
  }
}

// libs/api-client/project.json: the one documented exception
{
  "name": "api-client",
  "targets": {
    "codegen": { "command": "node tools/generate-client.mjs" },
    "build": {
      // WHY: client sources are generated from the OpenAPI spec before compiling.
      // dependsOn replaces the default array, so "^build" must be restated
      // or dependency builds stop running first.
      "dependsOn": ["codegen", "^build"]
    }
  }
}

nx show project api-client --json

Shared build, test and lint rules live in nx.json targetDefaults, and the single project override restates ^build because it replaces the inherited dependsOn array; nx show project confirms the resolved configuration.

How should you design a backend task pipeline with codegen, test and deploy?

Start from what each target actually consumes, not from what feels like a sensible sequence. A backend service usually breaks down like this:

Target dependsOn Reason
codegen none, or ^codegen Generates Prisma, protobuf or OpenAPI client code from checked-in schema files
build codegen, ^build Compiles against generated code and built libraries
test codegen, plus build only if tests import from dist Most unit tests run from source and gain nothing from waiting on a build
lint none Reads source only, so it can run in parallel with everything else
docker / deploy build (same project) Packages this project's artifacts. Upstream builds are already covered through build

Run codegen as a target, not as a postinstall hook. A hook runs on every install, Nx cannot cache it, and it is skipped in CI jobs that restore node_modules from cache. Generated code then silently goes stale.

Nx infers the project graph from imports, so it cannot see everything. A shared .proto directory, a root Prisma schema, or a project that only runs through a script all need implicitDependencies. Without them, ^ ordering skips those projects and affected misses changes to them.

Caching depends on accurate inputs and outputs. Declare every generated directory and dist path in outputs. A restored cache hit then writes those files back to disk, instead of reporting success while leaving dist empty. On the input side, add dependency inputs such as ^production to build so a change to an upstream library invalidates downstream hashes. Leave generated folders out of inputs so they aren't hashed twice.

// nx.json (Nx parses this file with comments allowed)
{
  "namedInputs": {
    "default": ["{projectRoot}/**/*"],
    // Generated code is an output of codegen, so keep it out of hashes
    "production": [
      "default",
      "!{projectRoot}/src/generated/**/*",
      "!{projectRoot}/**/*.spec.ts"
    ]
  },
  "targetDefaults": {
    "codegen": {
      "cache": true,
      // Hash only the checked-in schema files that drive generation
      "inputs": ["{projectRoot}/prisma/schema.prisma", "{workspaceRoot}/proto/**/*"],
      "outputs": ["{projectRoot}/src/generated"]
    },
    "build": {
      "cache": true,
      "dependsOn": ["codegen", "^build"],
      // ^production: an upstream library change invalidates this hash
      "inputs": ["production", "^production"],
      // A cache hit restores dist instead of leaving it empty
      "outputs": ["{projectRoot}/dist"]
    },
    "test": {
      "cache": true,
      // Unit tests run from source; they only need generated code
      "dependsOn": ["codegen"],
      "inputs": ["default", "^production"]
    },
    "lint": {
      "cache": true,
      "inputs": ["default"]
    },
    "docker": {
      // Package this project's own build; upstream builds come via build
      "dependsOn": ["build"]
    }
  }
}

An nx.json targetDefaults setup where codegen runs before build, test depends only on codegen, lint runs independently, and accurate inputs and outputs let cache hits restore generated code and dist.

When should you avoid broad dependsOn rules or shared targetDefaults?

Every ordering edge you add is a constraint the scheduler must honour, and each one has a cost that rarely shows up as a failure.

Rule pattern Why it looks safe Development cost
test depends on ^build Guarantees upstream artifacts exist Serializes the graph. Tests that could resolve source through TypeScript path mappings wait for every upstream build, which lengthens CI wall-clock time.
targetDefaults keyed by build One rule covers all projects build may run tsc in one project and produce a Docker image in another. The default silently applies the wrong dependsOn, inputs or outputs.
Many per-project overrides Fixes edge cases locally Recreates the inconsistency that targetDefaults was meant to remove. Reviewers can no longer predict the pipeline from nx.json.
Unneeded ordering Harmless, never breaks Nothing fails, so nobody removes it. Edges accumulate and parallelism quietly erodes.

Circular project dependencies are a harder limit. If lib-a imports lib-b and lib-b imports lib-a, then ^build has no valid order. No configuration change fixes this. You have to restructure, usually by extracting the shared code into a third library that both depend on.

Copied examples carry their own risk. The configuration surface and plugin-inferred targets have changed across Nx versions. A targetDefaults block taken from a blog post or another repo may merge with inferred settings in ways the author never saw. Before you trust the result, check the resolved configuration of a project with nx show project <name>.

How do you debug wrong build order in Nx?

Start with the graph, not the logs. nx graph opens a visualization of project dependencies, and its task view shows which tasks a target will pull in. If api:build has no edge to shared-types:build, Nx has no reason to order them, and no amount of rerunning will change that. A missing edge usually means one of two things: the project dependency was never detected (an import Nx doesn't infer, or a missing implicitDependencies entry), or dependsOn lacks the ^ prefix.

Next, run the failing target with --verbose. The output lists the tasks Nx scheduled and whether each one ran or was restored from cache. Compare that list against what you expected from the graph.

Then use nx show project <name> to see the fully resolved configuration. This is the target after targetDefaults, inferred plugin settings, and project.json have merged. It is the only reliable answer to "what dependsOn does this target actually have?"

Ordering bugs often hide locally. A warm cache or a leftover dist folder from last week lets a downstream build succeed even though its dependency never ran in this invocation. A clean CI runner has neither, so the bug appears there first. To reproduce it locally, delete build artifacts and bypass the cache.

Some failures that look like ordering bugs are actually caused by missing outputs. The order is correct, but Nx restores a cache hit without the files the next task needs. Check that every artifact path is declared.

Flags change between releases, so confirm them against nx --help for your installed version.

How can dependsOn and targetDefaults save engineering time?

The savings come from four places. Only the first is about machine time.

Skipped work. Because each task in the graph is a separate cacheable unit, a change to one service doesn't force a rebuild of libraries whose inputs didn't change. A script chain like codegen && build-libs && build-api reruns every step on every invocation. With nx affected, CI can also limit work to projects touched by the change and the projects that depend on them.

Parallelism you don't have to manage. Tasks with no edge between them, such as lint and test across unrelated projects, run concurrently without anyone hand-tuning CI job fan-out. Keeping edges minimal, as described above, preserves that.

Fewer flaky-build investigations. A missing ordering rule shows up as an intermittent race, and those are expensive to chase because they don't reproduce reliably. Declaring the order once in dependsOn turns "sometimes dist is missing in CI" into a deterministic graph you can inspect with nx graph.

Cheaper review and onboarding. With rules in targetDefaults, a new engineer learns what build means by reading one block in nx.json. A pipeline change becomes one diff instead of edits across every project.json and CI file.

An illustrative estimate shows how to reason about the machine-time part for your own repo. Every input here is assumed, not measured:

  • Assumed workspace: 8 shared libraries and 4 services.
  • Assumed build time: 1 minute per library build and 2 minutes per service build, run serially by a script chain, for 16 minutes per CI run.
  • Assumed typical change: a PR that touches one service and no libraries.

With a serial script chain, every PR pays the full 16 minutes. With dependsOn, accurate inputs/outputs and a populated cache, the 8 library builds would be cache hits, and only the changed service's build would run, about 2 minutes plus cache-restore overhead. Under these assumptions, that is roughly 14 minutes of build time saved per PR. A change to a widely used library would invalidate far more of the graph and save much less. To get real numbers, compare --verbose output from your own CI runs before and after migrating. Don't rely on this example.

The caveat matters as much as the estimate. Inaccurate inputs erase the savings in one of two ways: too broad and nothing hits the cache, too narrow and you get stale results that cost more time to debug than the cache saved.

What are the alternatives, and how do you migrate an existing repo to dependsOn?

Most repos that need dependsOn already encode ordering somewhere else. The common alternatives each give something up:

Approach Caching Parallelism Reviewability
Chained && in package.json scripts None per step; any change reruns the whole chain Serial only Ordering hidden inside script strings
npm pre/post lifecycle scripts None Serial, implicit Easy to miss; runs by naming convention
postinstall hooks None; runs on every install Blocks install Side effects on every install
Ordering in CI job definitions CI-level only, not local Coarse, per job Split from the code it orders
dependsOn + targetDefaults Per task, local and remote Scheduler runs independent tasks concurrently One declarative graph in nx.json

Migration checklist

  1. Inventory hidden ordering. Search for &&, pre*/post* scripts, postinstall, and CI steps that must run in a fixed sequence. Each one is an unstated dependency.
  2. Move ordering into dependsOn. Split chained commands into separate targets and connect them, for example codegen before build.
  3. Centralize in targetDefaults. Promote any rule that repeats across projects. Keep one-off rules local.
  4. Add implicit dependencies. Declare project links that Nx cannot infer from imports, such as a service that consumes generated schemas.
  5. Verify. Inspect nx graph, then run nx reset and do a full build to catch outputs or inputs that were never declared.

The time saved comes from cache hits on unchanged steps and from removing CI ordering that drifts away from the code. In a repo with two or three packages and a build that takes seconds, a plain script chain is easier to read, and keeping it is a reasonable choice.

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