Who should use dependsOn and targetDefaults?
This article is for teams that run an Nx monorepo where some projects generate code that other projects compile against. Common examples include GraphQL types, OpenAPI clients, protobuf stubs, and ORM clients. It is most useful if you are in one of these situations:
- Platform or build engineers who own
nx.jsonand want one rule for "generate, then build" instead of a copy in every project. - Service owners whose builds pass locally but fail on clean CI runners because generated files are missing or stale.
- Teams migrating from
prebuildscripts or hand-written CI step ordering who want Nx to schedule, parallelise and cache codegen as a separate task.
If your workspace has no generated code and every project builds from its own source, the defaults Nx generates for you are probably enough. Most of the guidance below can wait until you add a generator.
How does dependsOn work in an Nx task pipeline?
An Nx task pipeline is the set of rules that turns "run build on api" into an ordered graph of tasks. Each target can declare dependsOn, and Nx combines those rules with the project graph to decide what must finish first and what can run in parallel.
The string forms cover most cases:
"codegen"runs thecodegentarget on the same project first."^build"runsbuildon every project this one depends on first. The caret means "upstream."- Mixing both, as in
["^build", "codegen"], means two things: my dependencies' outputs exist, and my own generated sources are on disk. Nx needs both before it can start mybuild.
With api depending on contracts, running nx build api produces this graph:
contracts:codegen
│ (same project)
▼
contracts:build ─────────┐
│ (^build)
api:codegen │
│ (same project)│
▼ ▼
└──────► api:build ◄──┘
The two codegen tasks have no edge between them, so they can run concurrently.
The object form spells out the same edges with more control. target names the task. dependencies: true is equivalent to the caret. projects lists specific projects by name, which is useful when the dependency is not in the project graph. params: "forward" passes CLI arguments from the invoking task through to the dependency. Use the object form when you need forwarded parameters or an explicit project list. Otherwise the shorthand is easier to read and review.
// apps/api/project.json (Nx parses comments in project.json)
{
"name": "api",
"targets": {
"codegen": {
"command": "node tools/generate-client.js apps/api"
},
"build": {
"command": "tsc -p apps/api/tsconfig.app.json",
// Shorthand: upstream builds first (^build), then this project's codegen
"dependsOn": ["^build", "codegen"]
},
"build-release": {
"command": "tsc -p apps/api/tsconfig.app.json",
"dependsOn": [
// Same edge as "^build", but CLI args (e.g. --configuration) are
// forwarded to each dependency's build task
{ "target": "build", "dependencies": true, "params": "forward" },
// Explicitly run codegen on a named project
{ "target": "codegen", "projects": ["contracts"] },
// Plain string: codegen on this same project
"codegen"
]
}
}
}
An api project.json using the dependsOn shorthand for build, and the object form with dependencies, projects and params forwarding for a release build.
How does it work end to end when you run a target?
When you run nx build api, Nx goes through these steps in order:
- Build the project graph. Nx reads every project's configuration and analyses imports and package manifests to find which projects depend on which. It adds any
implicitDependenciesyou declared to those edges. - Resolve each target's configuration. For every target, Nx starts from the matching
targetDefaultsentry innx.jsonand applies the project's own configuration on top. A project-leveldependsOnreplaces the default array instead of merging with it. - Expand
dependsOninto a task graph. Starting fromapi:build, Nx follows eachdependsOnentry. Plain names add tasks on the same project. Caret entries add tasks on upstream projects found in the project graph. Nx repeats this until no new tasks appear. A target name that a project does not define produces no task for that project. - Hash and check the cache. For each task, Nx computes a hash from the task's
inputs, which can include files, named inputs, external dependency versions and the hashes of tasks it depends on. If a cacheable task's hash matches a previous run, locally or in a configured remote cache, Nx replays the terminal output and restores the declaredoutputsinstead of running the command. - Schedule. Nx runs a task only after all its prerequisites have finished. Tasks without an edge between them run concurrently, up to the parallelism limit (
--parallel).
So dependsOn and targetDefaults do not run anything themselves. They describe edges, and the scheduler and cache do the rest. The ordering is only as correct as those edges, and the cache is only as useful as the inputs and outputs attached to each task.
Why declare the pipeline once in nx.json targetDefaults?
If you run a monorepo where several services consume generated clients, schema types, or protobuf stubs, the order "generate, then build" is a rule for the whole repository. It is not specific to any one project. Putting that rule in targetDefaults in nx.json means it is written once, reviewed once, and applied to every project that has a matching target name. Two older approaches handle this worse:
| Approach | Where the ordering lives | Cacheable as a separate step | Drift risk |
|---|---|---|---|
prebuild package script |
Inside each project's build command | No, codegen reruns as part of build | High, each copy is edited by hand |
Per-project dependsOn |
Each project.json |
Yes | High, new projects copy whichever file they started from |
targetDefaults in nx.json |
One file at the root | Yes | Low, one definition |
A pre-script hides codegen inside the build. Nx sees one opaque task, so it cannot cache generation separately or schedule it in parallel with other work.
Precedence is simple but easy to misread. If a project's project.json declares dependsOn for a target, that array replaces the default. It does not merge with it. A project that adds one extra dependency must therefore restate the default entries, or it silently loses them.
Centralising the pipeline also has a cost: it is implicit. A new project inherits the pipeline the moment its target names match, whether or not its owners know this. Someone reading only that project's project.json will see no reason why codegen runs before build. Document the defaults where people will look for them, and treat changes to nx.json with the same review care as changes to shared CI configuration.
How do you model codegen as a first-class cacheable target?
Treat code generation as its own target rather than a pre-step buried inside build. A codegen target that declares its own inputs and outputs can be cached, skipped and ordered independently. build, test, lint and typecheck can then all list codegen in dependsOn, so none of them runs against missing or stale generated files.
The inputs should be the files that actually determine the generated code: the GraphQL schema, the .proto definitions, the OpenAPI document, and the generator's own configuration. The outputs should be the generated directories.
Outputs matter as much as ordering. When Nx gets a cache hit, it replays the terminal output and restores whatever paths the target declared as outputs. If outputs is empty or points at the wrong directory, the hit restores nothing. On your laptop the generated files are probably still on disk, so everything passes. On a clean CI runner, codegen reports success from cache, and then typecheck fails because the generated client does not exist.
Input breadth is a trade-off. If inputs are too narrow, a change to the generator config or a shared schema fragment does not invalidate the cache, and stale generated code ships. If inputs are too broad, such as the whole project, any unrelated edit invalidates the cache, and your hit rate collapses.
Generators must be deterministic. Some generators embed timestamps, absolute paths, or nondeterministic key ordering. With these, identical inputs produce different outputs, so downstream tasks that hash the generated files miss the cache every time. Machines sharing a remote cache also end up with diverging artifacts. Pin the generator version and strip volatile headers.
{
"namedInputs": {
"codegenSources": [
"{projectRoot}/schema/**/*.graphql",
"{projectRoot}/proto/**/*.proto",
"{projectRoot}/openapi/*.yaml",
"{projectRoot}/codegen.config.ts",
{ "externalDependencies": ["@graphql-codegen/cli"] }
]
},
"targetDefaults": {
"codegen": {
"cache": true,
"inputs": ["codegenSources"],
"outputs": ["{projectRoot}/src/generated"]
},
"build": {
"cache": true,
"dependsOn": ["codegen", "^build"]
},
"test": {
"cache": true,
"dependsOn": ["codegen"]
},
"lint": {
"cache": true,
"dependsOn": ["codegen"]
},
"typecheck": {
"cache": true,
"dependsOn": ["codegen"]
}
}
}
An nx.json sketch where codegen hashes only schema, proto, OpenAPI, generator config and generator version, declares src/generated as its output so cache hits restore files, and build, test, lint and typecheck depend on it.
How should codegen be ordered across projects that share an API contract?
Consider a typical layout: a contract library owns an OpenAPI or protobuf definition and has a codegen target that writes a typed client into its own source tree. Several services import that client. Each service's build and typecheck need those generated files on disk before the compiler runs.
The obvious rule, ^build, often fails to guarantee this. In many workspaces the contract library isn't built separately. Services compile its source directly through TypeScript path mappings, so the library may have no build target at all. Even when it does, ^build only helps if the contract's own build lists codegen as a prerequisite. If it does, you are also running a full compile of the library just to get files that already existed one step earlier. The consumer needs the producer's generated output to exist, not its compiled output. ^codegen states that requirement exactly: before this project runs, run codegen in every project it depends on.
The caret has a limit. It walks the project graph and nothing else. Nx infers edges from imports and package manifests it can analyze. A service that reads the spec file at build time, loads the client through a dynamically computed path, or is written in a language Nx's analysis doesn't cover will have no edge to the contract. ^codegen then resolves to nothing, and the task fails only on a cold checkout or a clean CI runner.
In those cases, add the contract to the consumer's implicitDependencies in its project configuration. Keep that list limited to dependencies you have confirmed Nx misses. If you also list dependencies Nx already detects, the list becomes stale when imports change.
cat > nx.json <<'EOF'
{
"targetDefaults": {
"codegen": {
"cache": true,
"outputs": ["{projectRoot}/src/generated"]
},
"build": {
"dependsOn": ["^codegen", "^build"]
},
"typecheck": {
"dependsOn": ["^codegen"]
}
}
}
EOF
cat > apps/billing-service/project.json <<'EOF'
{
"name": "billing-service",
"implicitDependencies": ["contract"]
}
EOF
npx nx show project billing-service
npx nx run billing-service:build
Sets ^codegen as a prerequisite for build and typecheck in nx.json targetDefaults, then adds an implicit dependency for one consumer whose link to the contract library Nx cannot detect.
A worked nx.json targetDefaults example with one project override
The example below uses four targets. In nx.json, targetDefaults declares codegen as cacheable, with inputs limited to the schema or contract files and outputs pointing at the generated directory. build depends on ["codegen", "^build"]. typecheck depends on the same pair, because type errors in a consumer often come from a dependency's declarations being stale. test depends only on ["codegen"]. Most test runners resolve workspace dependencies from source, so a full upstream build would add latency without adding correctness. If your runner resolves dependencies from built output, add ^build to test as well.
The override is for a project whose generator reads protobuf definitions through a custom plugin. That project defines its own codegen-proto target, and its project.json sets build.dependsOn to ["codegen-proto", "^build"]. Keep the second entry. A project-level dependsOn replaces the default array instead of merging with it. If you write only ["codegen-proto"], the project builds before its dependencies. The build can still pass locally because stale dist folders are present, and then fail in a clean CI checkout.
To verify the result, open nx graph and switch to the task view for build. The codegen-proto → build edge should appear next to the upstream build edges. For a text check, nx run-many -t build --graph and nx affected -t build --graph show the planned task graph without running anything. Flag names and output formats have changed across releases, so confirm them with --help on your installed Nx version.
cat > nx.json <<'EOF'
{
"targetDefaults": {
"codegen": {
"cache": true,
"inputs": ["{projectRoot}/schema/**/*"],
"outputs": ["{projectRoot}/src/generated"]
},
"build": { "dependsOn": ["codegen", "^build"] },
"typecheck": { "dependsOn": ["codegen", "^build"] },
"test": { "dependsOn": ["codegen"] }
}
}
EOF
cat > libs/proto-client/project.json <<'EOF'
{
"name": "proto-client",
"targets": {
"codegen-proto": {
"executor": "nx:run-commands",
"cache": true,
"inputs": ["{projectRoot}/proto/**/*.proto"],
"outputs": ["{projectRoot}/src/generated"],
"options": { "command": "node tools/proto-gen/generate.mjs libs/proto-client" }
},
"build": { "dependsOn": ["codegen-proto", "^build"] }
}
}
EOF
npx nx graph
npx nx run-many -t build --graph
npx nx affected -t build --graph
npx nx run-many --help
A targetDefaults block for codegen, build, typecheck and test, a project.json override that keeps '^build' next to its custom codegen-proto step, and the commands used to inspect the resulting task graph.
How can dependsOn and targetDefaults save engineering time?
The time savings come from removing manual steps and avoidable reruns.
- No hand-maintained step ordering. Without declared edges, someone has to encode "generate, then build" in CI scripts,
prebuildhooks or README instructions, and then keep every copy up to date. WithtargetDefaults, a new project that uses the standard target names gets the correct order without anyone editing CI. - Fewer "works locally, fails in CI" investigations. Missing-generated-file failures usually show up on clean runners and take time to reproduce. When every consumer declares
codegenor^codegenas a prerequisite, a cold checkout produces the same task order as a warm laptop, so this class of failure is mostly gone. - Codegen skipped when nothing relevant changed. Because
codegenis a separate cacheable target with narrowinputs, an edit to application code does not rerun the generator. Developers and CI restore the generated files from cache instead of waiting for them. - More parallelism. Independent codegen tasks have no edges between them, so Nx runs them concurrently. A chain of
prebuildscripts runs everything in sequence inside each build. - Cheaper review and onboarding. One
nx.jsonblock is easier to review than the same rule copied across dozens ofproject.jsonfiles, andnx graphshows newcomers the order instead of making them learn it from failures.
Illustrative estimate (assumed inputs, not measured): assume a team of 10 engineers, each running local builds 15 times a day, a 30-second generator, and changes that touch codegen inputs in 1 of every 5 runs. Without a cacheable codegen target, the generator runs on every build: 10 × 15 × 30 s = 75 minutes of generator time per day across the team. With caching, it runs on about 3 of each engineer's 15 runs: 10 × 3 × 30 s = 15 minutes. Under these assumptions that is roughly an hour of waiting removed per day, before counting CI. Replace the assumed numbers with your own generator timing and change frequency.
When should you avoid broad dependsOn rules, and what are the alternatives?
A rule that sends every build through codegen and ^codegen stops helping in three situations. The first is deep chains: a project that never imports generated types still waits on every upstream generator, so the scheduler has fewer tasks it can run in parallel. The second is a slow generator that misses the cache and reruns on each local edit, which then dominates the inner loop. The third is projects such as CLI tools or infra scripts that inherit steps they don't need.
| Approach | Ordering safety | Drift risk | Diff noise | Cacheability |
|---|---|---|---|---|
targetDefaults + per-project override |
High | Low | None | Full Nx caching |
Per-project dependsOn only |
High where declared, gaps elsewhere | Medium (rules diverge) | None | Full Nx caching |
| Commit generated code to git | Not needed at build time | High unless CI checks for regeneration | High | N/A (no task) |
| Package-manager pre-scripts | Implicit, runs outside the graph | Medium | None | None. Nx can't see or cache it |
| External orchestration | Depends on the tool | Medium | None | Separate from Nx cache |
Illustrative estimate (assumed inputs, not measured): take 12 projects, a 40-second generator, and enough CI agents to run independent tasks in parallel. If a broad rule chains codegen four levels deep, the critical path carries about 160 seconds of codegen. Scoped rules that keep one real dependency level carry about 40 seconds. That saves roughly two minutes of wall-clock time per cache-missing run. Across a team, those minutes add up as waiting time on every pull request.
How do you debug task ordering failures in Nx?
Ordering bugs rarely fail every time. When an upstream output is already sitting in the cache, a missing edge stays hidden. Nx restores the generated files, and the downstream build finds them by luck. On a fresh CI runner or a new laptop, nothing is restored, the tasks run in whatever order the scheduler picks, and the build breaks. That is why "works locally, fails in CI" is the usual symptom. Work through these checks in order:
- Match target names exactly.
dependsOnrefers to targets by name. If one project calls itcodegenand another calls itgenerate, Nx does not raise an error. It skips the dependency for projects that lack the named target, so the edge silently disappears. - Look for project-level overrides. A
dependsOnarray in a project's configuration replaces thetargetDefaultsvalue instead of merging with it. Check whether a local override dropped^buildorcodegenwhile someone was adding an unrelated entry. - Compare
outputsagainst what the generator writes. If the generator writes tosrc/generatedandoutputslistsgenerated, Nx caches an empty set. A later cache hit restores nothing, and the next task fails because the files it expects are missing. - Confirm the graph edge exists.
^dependencies follow project graph edges. Runnx graphand check that the consumer actually depends on the contract project. Contracts loaded at runtime, or referenced only through path aliases Nx cannot infer, need an explicitimplicitDependenciesentry. - Reproduce cold. Start from a clean checkout and run with
--skip-nx-cache, or runnx resetfirst. If the failure appears only under those conditions, the cause is a missing edge, not a flaky tool.
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.
- 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.