How does an Nx Rust monorepo divide work between Nx and Cargo?
An Nx Rust monorepo has two layers that each do one job. Cargo builds Rust. Nx decides which tasks run, in what order, and whether a result can be replayed from cache. Neither layer replaces the other.
| Concern | Owned by | Where it lives |
|---|---|---|
| Compilation and incremental builds | Cargo | target/ directory |
| Crate dependency resolution | Cargo | root Cargo.toml, Cargo.lock |
| JS/TS dependency resolution | Package manager | package.json, its lockfile |
| Task orchestration and ordering | Nx | nx.json, project.json |
| Computation cache | Nx | Nx cache directory (local or remote) |
| Project graph and affected detection | Nx | Built from workspace files and plugins |
A root Cargo.toml declares the workspace members. It sits next to package.json and nx.json. Each crate gets an Nx project definition whose targets call Cargo.
Here is how nx run api:build flows through the two layers:
- Nx hashes the task's declared inputs, such as source files,
Cargo.toml,Cargo.lock, and relevant environment variables. - If the hash matches a cached entry, Nx restores the outputs and terminal log without invoking Cargo.
- On a miss, Nx spawns something like
cargo build -p api. Cargo resolves crates, reuses its own incremental artifacts, and compiles. - Nx stores the declared outputs under the hash for next time.
Cargo stays the source of truth because it already understands features, build scripts, and the crate dependency graph. If you duplicate that logic in Nx config, the two will drift apart. You then get stale caches or builds that pass locally and fail in CI. Nx should only wrap Cargo and read Cargo's metadata. It should never redefine how a crate is built.
repo root: package.json nx.json Cargo.toml + Cargo.lock
(pkg manager) (Nx) (Cargo workspace)
$ nx run api:build
|
v
+------------------------- NX LAYER ---------------------------+
| project graph + affected detection (nx.json, project.json) |
| |
| 1. hash inputs: sources, Cargo.toml, Cargo.lock, env vars |
| | |
| v |
| +-------------+ 2. hit +-------------------------------+ |
| | cache check |--------->| restore outputs, terminal log | |
| +-------------+ | (Cargo is not invoked) | |
| | miss +-------------------------------+ |
| v |
| 3. spawn `cargo build -p api` 4. store outputs by hash |
| | ^ |
+--------|-------------------------------|---------------------+
v |
+------------------------ CARGO LAYER ---|---------------------+
| resolve: Cargo.toml + Cargo.lock | |
| features, build scripts, crate graph | |
| incremental compile -> target/ --------+ |
| Cargo is source of truth; Nx only wraps it |
+--------------------------------------------------------------+
Nx hashes inputs and replays cached outputs on a hit, and calls Cargo on a miss; Cargo resolves crates, compiles incrementally into target/, and Nx stores the declared outputs under the task hash.
Who should add Rust crates to an Nx monorepo, and when should you avoid it?
The reason to accept that constraint is what you get back: one CI pipeline, one task runner, and affected detection that crosses the language boundary. When a TypeScript package depends on a Rust crate, a change to that crate should rebuild and retest the package that consumes it. A polyglot monorepo with a shared project graph does this without hand-written path filters in your CI config.
Who benefits
The setup pays off for platform teams that maintain several crates alongside TypeScript services. It also fits teams whose Rust code ships into the JavaScript side, either as WebAssembly modules or as native Node addons. In those cases the dependency between Rust and TypeScript is real and changes often. Encoding it in the Nx graph replaces tribal knowledge about which builds to trigger. Caching also helps, because Rust compile times make skipped rebuilds worth having.
When to skip it
Avoid it if the repo has one or two small crates that rarely change. A standalone Cargo workspace called from a package script is easier to read, and nobody has to learn how Nx models Cargo targets.
Avoid it too when the Rust developers will keep running cargo directly and ignore Nx. The cache inputs, the targets and real usage will drift apart, and CI becomes the only place the Nx configuration is ever exercised.
Count the onboarding cost as well. Every TypeScript-only contributor who runs an affected build now needs rustup, a toolchain that matches the repo's pinned version, and possibly a WebAssembly target or a native build toolchain. Plan for that before you add the first crate.
How do you set up a Cargo workspace inside an Nx repo?
Put a single Cargo workspace at the repository root, beside package.json and nx.json. A typical layout:
Cargo.toml: the workspace manifestCargo.lock: one lockfile for every craterust-toolchain.toml: the pinned compilercrates/api-core/,crates/cli/: Rust members, each with its ownCargo.tomlandsrc/packages/orapps/: your existing TypeScript projectstarget/: shared build output, added to.gitignore
The root manifest has no [package] section. It contains only a [workspace] table that sets resolver = "2" and lists members, either explicitly or with a glob such as crates/*. Put common dependency versions in [workspace.dependencies] so member crates can inherit them with workspace = true. Each member manifest then needs only a name, an edition, and its dependencies. If you'd rather keep Rust out of the root, the same structure works under a subdirectory like rust/. In that case, Nx targets must run Cargo from that directory.
One workspace is usually better than many standalone crates. It gives you one dependency resolution, so two crates can't silently build against different versions of the same library. Cargo also reuses compiled dependencies across members in the shared target/ directory. Most importantly for Nx, you get one lockfile that represents the entire Rust dependency state, which makes cache inputs simple to declare.
Pin a specific release in rust-toolchain.toml instead of floating on stable. Include the components and targets you need, such as clippy, rustfmt, or a wasm target. rustup reads this file automatically, so laptops and CI use the same compiler. If compilers differ, cached artifacts from one machine aren't valid on another.
# Run from the repo root, next to package.json and nx.json.
mkdir -p crates/api-core/src
# Workspace manifest: no [package], one resolver, glob for members.
cat > Cargo.toml <<'EOF'
[workspace]
resolver = "2"
members = ["crates/*"]
# Shared versions; members opt in with `workspace = true`.
[workspace.dependencies]
serde = { version = "1", features = ["derive"] }
EOF
# Pin an exact release (example value) so laptops and CI use the same compiler.
cat > rust-toolchain.toml <<'EOF'
[toolchain]
channel = "1.82.0"
components = ["clippy", "rustfmt"]
targets = ["wasm32-unknown-unknown"]
EOF
# Minimal member manifest: name, version, edition, inherited deps.
cat > crates/api-core/Cargo.toml <<'EOF'
[package]
name = "api-core"
version = "0.1.0"
edition = "2021"
[dependencies]
serde = { workspace = true }
EOF
echo 'pub fn ping() -> &'"'"'static str { "pong" }' > crates/api-core/src/lib.rs
# Shared build output stays out of git; Cargo.lock is committed.
echo '/target' >> .gitignore
cargo build --workspace # creates the single root Cargo.lock and target/
A shell script that creates a root Cargo workspace with shared dependency versions, a pinned rust-toolchain.toml, and a minimal member crate. Building it produces one Cargo.lock and one target/ directory for the whole repository.
Should you use the @monodon Rust plugin or plain run-commands targets?
There are two practical ways to give Nx tasks for your crates. Pick one deliberately, because switching later means rewriting every project's configuration.
The @monodon/rust plugin is a community package, not part of the core Nx distribution. It can generate new crates and infer Nx projects by reading each crate's Cargo.toml. That inference is its main benefit: dependencies between workspace crates appear in the project graph without manual wiring. Generator and executor names have changed across releases, so check the plugin's README for the names your Nx version supports rather than copying them from older blog posts. The risk is maintenance. A small group of maintainers outside the Nx core team keeps the plugin compatible. When you upgrade Nx, the plugin may lag behind, and that can block the upgrade.
Hand-written project.json targets use nx:run-commands to call cargo build, cargo test, cargo clippy and cargo fmt --check directly. Nx core maintains nx:run-commands, so it rarely breaks on upgrade. The cost is that you declare cache inputs, outputs and cross-crate dependencies yourself.
| Criterion | @monodon/rust plugin |
nx:run-commands targets |
|---|---|---|
| Verbosity | Low; projects are inferred | Higher; every target is written by hand |
| Upgrade risk | Tied to third-party release timing | Low; core Nx executor |
| Graph inference | Automatic from Cargo.toml |
Manual, via implicitDependencies or dependsOn |
| Transparency | Behaviour lives in plugin code | The exact Cargo command is visible in config |
With a handful of stable crates, plain targets are easier to audit. As the number of crates grows, hand-maintained edges drift out of sync with Cargo.toml, which makes the plugin's inference more valuable.
{
"name": "api-core",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"projectType": "library",
"sourceRoot": "crates/api-core/src",
"implicitDependencies": ["shared-types"],
"targets": {
"build": {
"executor": "nx:run-commands",
"dependsOn": ["^build"],
"cache": true,
"inputs": ["{projectRoot}/Cargo.toml", "{projectRoot}/src/**/*", "{workspaceRoot}/Cargo.lock"],
"options": { "command": "cargo build -p api-core" }
},
"test": {
"executor": "nx:run-commands",
"cache": true,
"inputs": ["{projectRoot}/Cargo.toml", "{projectRoot}/src/**/*", "{workspaceRoot}/Cargo.lock"],
"options": { "command": "cargo test -p api-core" }
},
"lint": {
"executor": "nx:run-commands",
"cache": true,
"inputs": ["{projectRoot}/Cargo.toml", "{projectRoot}/src/**/*", "{workspaceRoot}/Cargo.lock"],
"options": { "command": "cargo clippy -p api-core -- -D warnings" }
},
"format-check": {
"executor": "nx:run-commands",
"cache": true,
"inputs": ["{projectRoot}/src/**/*"],
"options": { "command": "cargo fmt -p api-core --check" }
}
}
}
A hand-written crates/api-core/project.json using nx:run-commands for Cargo, with cache inputs and the dependency on the shared-types crate declared by hand because Nx cannot infer it from Cargo.toml without a plugin.
How do you configure Nx cache inputs and outputs for Rust tasks?
Start with a rust named input in nx.json that lists every file Cargo itself reads: {projectRoot}/Cargo.toml, {projectRoot}/src/**/*, {projectRoot}/build.rs, plus the workspace-level {workspaceRoot}/Cargo.toml, {workspaceRoot}/Cargo.lock and {workspaceRoot}/rust-toolchain.toml. The root files matter because a lockfile bump or a toolchain change alters the output of every crate, even though no file under the project directory changed. Reference the named input from targetDefaults for test, lint and build so each crate inherits it.
Cargo also reacts to state that does not live in files. Add env inputs for variables such as RUSTFLAGS and CARGO_PROFILE_*, along with anything your build.rs reads. Pass feature flags as target options or arguments, not through ad hoc environment variables, so they become part of the task hash.
Don't cache target/ by default
Declaring {projectRoot}/target (or the shared workspace target/) as an output looks thorough, but it usually backfires. target/ holds incremental state and dependency artifacts and can grow very large. Nx would archive and restore all of it, while Cargo's own fingerprinting already skips unchanged work on a warm runner. Cache test and lint (clippy) results instead. Their outputs are small, and a cache hit skips the whole run.
Diagnosing stale hits
When inputs are incomplete, the usual symptom is a test that passes from cache after a change to a file Nx doesn't track. To confirm it, rerun with --skip-nx-cache. If the results differ, compare the inputs Nx reports for the target with the files and variables Cargo actually reads.
{
"namedInputs": {
"rust": [
"{projectRoot}/Cargo.toml",
"{projectRoot}/src/**/*",
"{projectRoot}/build.rs",
"{workspaceRoot}/Cargo.toml",
"{workspaceRoot}/Cargo.lock",
"{workspaceRoot}/rust-toolchain.toml",
{ "env": "RUSTFLAGS" },
{ "env": "CARGO_PROFILE_RELEASE_LTO" },
{ "env": "MY_CRATE_BUILD_MODE" },
{ "runtime": "rustc --version" }
]
},
"targetDefaults": {
"test": {
"cache": true,
"inputs": ["rust", "^rust"],
"outputs": []
},
"lint": {
"cache": true,
"inputs": ["rust", "^rust"],
"outputs": []
},
"build": {
"cache": false,
"inputs": ["rust", "^rust"]
}
}
}
An nx.json fragment that hashes every file, env var and toolchain Cargo depends on, caches test and lint results with no file outputs, and leaves build uncached so target/ is never archived.
How do Rust crates and TypeScript packages depend on each other in the Nx graph?
When Nx knows how crates depend on each other, nx affected and dependsOn: ["^build"] work across Rust projects the same way they do for TypeScript. The @monodon plugin infers these edges from cargo metadata. A path dependency in one crate's Cargo.toml that points at another workspace crate becomes an edge in the Nx project graph. With plain run-commands targets, Nx sees none of this. You have to declare the edges yourself, and they drift whenever someone edits Cargo.toml without updating project.json.
TypeScript consumers of Rust artifacts
No inference crosses the language boundary. A TypeScript package that imports a WebAssembly bundle or a .node addon built from a crate has no package.json or Cargo.toml entry that Nx can read as a link to that crate. You need two declarations in the consumer's project.json:
implicitDependencieslists the crate's project name. This adds the graph edge, sonx affectedmarks the consumer as affected when the crate changes.dependsOnon the consumer'sbuild(andtest) targets runs the crate's build first. Use^buildif the crate's target is namedbuild, or the object form that names the specific project and target if it isn't. This makes sure the artifact exists before the TypeScript build reads it.
Without dependsOn, an affected run can still build the consumer against a stale or missing artifact.
Toolchain requirements
Cross-language targets add toolchain requirements that a Rust-only build doesn't have:
- WebAssembly: the
wasm32-unknown-unknowntarget must be installed. If you usewasm-bindgen, its CLI version must match the crate's dependency version. - Native addons: cross-compiling for another OS or architecture needs that target installed and a linker configured for it.
node-gypbuilds: these also need Node headers that match the runtime that will load the addon.
Pin all of these in rust-toolchain.toml and the CI image, and include the toolchain file in the crate's cache inputs.
How do you run nx affected for Rust in CI without wasting time?
Keep CI caching in three separate layers, because each one is invalidated by different changes:
| Cache | Contents | Key on | Invalidated by |
|---|---|---|---|
| Cargo registry | ~/.cargo/registry, ~/.cargo/git |
Cargo.lock |
Dependency changes |
| Cargo target dir | Compiled artifacts | Toolchain file + Cargo.lock + OS |
Toolchain bumps, dependency changes |
| Nx cache | Task outputs and terminal logs | Nx-computed hashes | Any declared input |
If you merge the registry and target directory into the Nx cache, every source edit rewrites a multi-gigabyte artifact. Keep them apart.
Define fmt (running cargo fmt --check) and clippy as Nx targets on each crate. That way nx affected -t fmt clippy test skips unchanged crates instead of linting the whole workspace on every PR.
There are two costs to plan for:
- Workspace-wide invalidation. Any edit to the root
Cargo.lockor the workspaceCargo.tomlmarks every crate as affected. - Lock contention. Parallel cargo processes that share a target directory block on its build-directory lock. Raising
--parallelbeyond a small number mostly adds waiting. Measure first, then tune.
Illustrative estimate (assumed numbers, not a benchmark). T = O + B × f, where O is fixed overhead, B is the full Rust task time, and f is the affected fraction. Assume O = 2 min, B = 18 min, a typical f = 0.25, and 15% of PRs touching the lockfile (f = 1):
- Typical PR: 2 + 4.5 = 6.5 min
- Lockfile PR: 20 min
- Expected: 0.85 × 6.5 + 0.15 × 20 ≈ 8.5 min, versus 20 min for full builds
Document these conventions for developers who call cargo directly:
- Dependency bumps go in dedicated PRs.
- Lint flags live in workspace config, not only in Nx targets.
- Run
nx affectedbefore pushing.
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 rust monorepo, 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
.envby 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.