What is an Nx Rust Cargo setup, and who should use it?

An Nx Rust Cargo setup puts a single root Cargo workspace inside an Nx polyglot monorepo, next to your existing JavaScript and TypeScript projects. The root Cargo.toml lists its members explicitly, so every crate shares one Cargo.lock and one target directory. That gives you consistent dependency resolution and lets crates reuse each other's compiled artifacts instead of rebuilding them.

The two tools have separate jobs:

  • Cargo builds Rust. It resolves dependencies, compiles, tests, and lints.
  • Nx coordinates. Through the community monodon plugin, it handles the project graph, affected detection, caching, and task wiring across languages.

Nx never replaces cargo build. It decides when Cargo needs to run and in what order.

┌──────────────────────── Nx task graph ────────────────────────┐
│   build/test/lint across Rust and TS projects, cached,        │
│   filtered by "affected"                                      │
│        ▲                                   ▲                  │
│        │ graph edges                       │ graph edges      │
│ ┌──────┴──────────────┐          ┌─────────┴──────────┐       │
│ │   monodon plugin    │          │  JS/TS projects    │       │
│ │ reads Cargo.toml,   │          │  (package.json,    │       │
│ │ path deps -> edges  │          │   tsconfig)        │       │
│ └──────▲──────────────┘          └────────────────────┘       │
└────────┼──────────────────────────────────────────────────────┘
┌────────┴───────────────── Cargo workspace ────────────────────┐
│  crates/*   │   one Cargo.lock   │   one target/ directory    │
└───────────────────────────────────────────────────────────────┘

Teams usually adopt this setup to get one affected-aware CI pipeline and one task graph. Without it, they maintain a Rust pipeline and a TypeScript pipeline that cannot see each other. For example, a change to a shared crate should trigger the services and tools that consume it, and nothing else.

The setup fits platform and backend teams that already have a substantial TypeScript footprint in Nx and are adding Rust services. If Rust is your main language, the benefits shrink. Section 7 covers when to avoid this setup and what to use instead.

┌───────────────────────────── Nx task graph ──────────────────────────────┐
│  build/test/lint for Rust and TS projects, cached, filtered by affected  │
│  cross-language edge: web depends on api (implicitDependencies)          │
│                                                                          │
│  ┌──────────┐   ┌──────────┐      ┌──────────┐   ┌──────────┐            │
│  │ api Rust │──▶│ core Rust│      │ web TS   │──▶│ ui TS    │            │
│  └────┬─────┘   └────┬─────┘      └────┬─────┘   └──────────┘            │
│       │              │                 │                                 │
│  ┌────┴──────────────┴─────┐      ┌────┴─────────────┐                   │
│  │ monodon (Nx plugin)     │      │ Nx JS/TS plugins │                   │
│  │ reads Cargo.toml        │      │ package.json,    │                   │
│  │ path deps ─▶ graph edges│      │ tsconfig paths   │                   │
│  └────────────┬────────────┘      └──────────────────┘                   │
│               ▲                                                          │
└───────────────┼──────────────────────────────────────────────────────────┘
┌───────────────┴──────────────────── Cargo workspace ─────────────────────┐
│ root Cargo.toml: [workspace] members = ["crates/api", "crates/core"]     │
│ crates/api ──▶ crates/core  (path dependency)                            │
│ one Cargo.lock   │   one target/ directory   │   cargo build/test/clippy │
└──────────────────────────────────────────────────────────────────────────┘

Cargo owns the Rust workspace (members, one lockfile, one target directory), monodon turns Cargo path dependencies into Nx graph edges, and Nx schedules cached, affected-filtered tasks across Rust and TypeScript projects.

How does the monodon Rust Nx plugin work?

The plugin doesn't replace Cargo. It reads Cargo's view of the workspace and translates it into concepts Nx already understands. That division of labour explains both what it does well and where it stops.

Crate discovery

The plugin starts from the root Cargo.toml and its workspace member list. Each member crate becomes an Nx project, named after the crate. Because Cargo stays the source of truth, adding a crate to the workspace members is enough for Nx to see it. You don't maintain a second list of projects that can drift from the first.

Dependency edges

When one crate declares a path dependency on another workspace crate, the plugin records an edge in the Nx project graph. This is what makes nx graph show your Rust crates connected correctly. It also lets nx affected work out that a change to a shared domain crate touches every service binary that depends on it. Dependencies pulled from a registry don't become edges, because they aren't projects in your repository.

Targets

Each crate gets targets such as build, test and lint. These call cargo build, cargo test and cargo clippy scoped to that crate. Nx handles orchestration, ordering and caching. Cargo still handles compilation, so build behaviour matches what developers get running Cargo directly.

Maintenance status

The plugin is maintained by the community, not shipped as part of Nx core. Follow its README for installation steps and generator names. Pin the version explicitly, and upgrade it on purpose alongside Nx itself rather than assuming any version is compatible.

How do you lay out a Cargo workspace inside an Nx monorepo?

Put Rust crates beside the TypeScript apps rather than in a separate top-level tree. A typical layout has apps/web (TypeScript), apps/orders-service (a Rust binary crate), and libs/orders-domain (a Rust library crate), with a single Cargo.toml and Cargo.lock at the repo root. That root manifest declares a [workspace] with an explicit members list naming both crate paths. Explicit members cost a line per crate, but they keep crate discovery predictable. A stray Cargo.toml in a fixture or vendored directory won't silently join the build the way it might under a broad glob.

The service depends on the domain library through an ordinary path dependency in apps/orders-service/Cargo.toml, with orders-domain pointing at ../../libs/orders-domain. Add nothing on the Nx side. The plugin reads the dependency graph from Cargo's metadata, so nx graph should show an edge from orders-service to orders-domain. If you also declare that edge in project.json or implicitDependencies, you create two sources of truth that will eventually disagree. If the edge is missing, fix the Cargo manifest or the plugin registration, not the Nx config.

Then verify the setup without Nx. From the repo root, cargo build --workspace and cargo test --workspace should succeed on a clean checkout. This guarantees that Nx is an orchestration and caching layer, never a requirement for compiling Rust.

Editors should follow the same rule. Open the repo root so rust-analyzer finds the root Cargo.toml and loads every member as one workspace. One shared target/ directory and one lockfile mean the editor, Cargo, and Nx all resolve the same dependency versions.

# Layout: Rust crates sit beside TS apps, with one Cargo workspace at the root.
#   apps/web/                    (TypeScript)
#   apps/orders-service/         (Rust binary crate)
#   libs/orders-domain/          (Rust library crate)
#   Cargo.toml, Cargo.lock       (single workspace and lockfile)

# Root manifest: explicit members so stray Cargo.toml files never join the build.
cat > Cargo.toml <<'EOF'
[workspace]
resolver = "2"
members = [
  "apps/orders-service",
  "libs/orders-domain",
]
EOF

# Service crate: a normal Cargo path dependency is the only place the edge is declared.
cat > apps/orders-service/Cargo.toml <<'EOF'
[package]
name = "orders-service"
version = "0.1.0"
edition = "2021"

[dependencies]
orders-domain = { path = "../../libs/orders-domain" }
EOF

# Plain Cargo must build and test everything from the root, with no Nx involved.
cargo build --workspace
cargo test --workspace

# Nx only reads what Cargo already knows; expect an orders-service -> orders-domain edge.
# Do not add the edge to project.json or implicitDependencies.
npx nx graph

Shows a root Cargo workspace with explicit members, a service crate that depends on a shared domain library through a path dependency, a plain-Cargo build and test from the repo root, and an nx graph check that adds no Nx-side dependency config.

How should you configure Nx cache inputs and outputs for Rust targets?

A Rust target's inputs should include the crate's src/ tree, its own Cargo.toml, the root Cargo.toml and Cargo.lock, any rust-toolchain.toml, and build.rs. If you leave out the lockfile, a cargo update that changes a transitive dependency produces the same hash as before, and Nx replays the old binary. If you leave out the toolchain file, a compiler bump replays artifacts from the previous compiler.

Nx only hashes what you declare. Environment variables read through env! or by a build script, files a build.rs opens outside the crate, and system libraries such as OpenSSL found through pkg-config are all invisible to it. On a single laptop that causes occasional confusion. With a remote cache it is worse: a CI agent with a different system library or RUSTFLAGS can upload an artifact that every other machine then trusts. Declare these with env and runtime inputs, for example the output of rustc --version.

Cargo also unifies features across everything built in one invocation. A crate compiled alongside a sibling that enables serde/derive produces different output than the same crate compiled alone. This means a crate's inputs should cover any workspace member that can change the feature set it is built with, which in practice means broad inputs.

On outputs, do not declare the shared target/ directory per project. Every project would claim the same directory, so each restore overwrites the others' state and breaks Cargo's own fingerprints.

Strategy Cache hit restores Trade-off
Final artifacts only Release binary under target/release/ Fast deploys; hashing must be strict
Nothing cached Nothing; Cargo incremental does the work Safe, but cold CI agents rebuild everything
Test and lint results only Terminal output, no files Skips repeat cargo test/clippy runs with no artifact risk
// nx.json (Nx parses comments in this file)
{
  "namedInputs": {
    "rust": [
      "{projectRoot}/src/**/*",
      "{projectRoot}/Cargo.toml",
      "{projectRoot}/build.rs",
      // Root manifest and lockfile: a cargo update must change the hash
      "{workspaceRoot}/Cargo.toml",
      "{workspaceRoot}/Cargo.lock",
      // Every member manifest can change unified features
      "{workspaceRoot}/**/Cargo.toml",
      "{workspaceRoot}/rust-toolchain.toml",
      // Things Nx cannot see unless declared
      { "env": "RUSTFLAGS" },
      { "env": "OPENSSL_DIR" },
      { "runtime": "rustc --version" },
      { "runtime": "pkg-config --modversion openssl" }
    ]
  },
  "targetDefaults": {
    "build": {
      "cache": true,
      "inputs": ["rust", "^rust"],
      // Final binary only, never the shared target/ directory
      "outputs": ["{workspaceRoot}/target/release/{projectName}"]
    },
    "test": {
      "cache": true,
      "inputs": ["rust", "^rust"],
      // Cache the pass/fail result and logs, restore no files
      "outputs": []
    },
    "lint": {
      "cache": true,
      "inputs": ["rust", "^rust"],
      "outputs": []
    }
  }
}

An nx.json with broad Rust cache inputs, including env and runtime inputs. Build caches only the release binary. Test and lint cache results without restoring files.

How do you wire cross-language dependencies Cargo cannot see?

Cargo resolves dependencies only from Cargo.toml, and monodon builds the Nx project graph from that same metadata. Any relationship that crosses a language boundary is invisible to both unless you declare it. Two cases come up in almost every polyglot monorepo.

A TypeScript client generated from the Rust API schema

Say the orders-service crate emits an OpenAPI document, and the orders-client TypeScript library runs a generator over it. No Cargo.toml or package.json links the two, so nx affected will not rebuild or test the client when a Rust handler changes its response shape.

Add orders-service to the client's implicitDependencies in its project.json. That edge enters the project graph, so a change to the service marks the client as affected.

Ordering is a separate concern. Give the client's generate target a dependsOn of ^build (or whichever target writes the schema). The ^ prefix means "this target on my dependencies," and it now includes the implicit edge. The schema then exists before generation starts.

A Docker image built from the release binary

An image target on the Rust project should declare dependsOn on that project's own build target, with no ^ prefix, and pass the release configuration. Without that declaration, nx run-many -t image can start docker build before the binary exists, or copy a stale debug artifact. List the binary path in the target's inputs, so a cached image is invalidated whenever the binary changes.

implicitDependencies keeps affected accurate. dependsOn keeps execution order accurate. In most cross-language cases you need both.

// libs/orders-client/project.json
{
  "name": "orders-client",
  // Cargo and package.json never link these projects, so declare the edge.
  // A change to orders-service now marks orders-client as affected.
  "implicitDependencies": ["orders-service"],
  "targets": {
    "generate": {
      // "^build" runs build on this project's dependencies first, including
      // the implicit orders-service edge, so the OpenAPI file exists.
      "dependsOn": ["^build"],
      "executor": "nx:run-commands",
      "options": {
        "command": "node tools/generate-client.mjs dist/orders-service/openapi.json libs/orders-client/src/generated"
      }
    }
  }
}

// apps/orders-service/project.json (excerpt)
{
  "targets": {
    "image": {
      // No "^": run this same project's build target first.
      // Make that build target produce the release binary (for example via
      // its defaultConfiguration) so docker never copies a debug artifact.
      "dependsOn": ["build"],
      // Rebuild a cached image whenever the binary or the Dockerfile changes.
      "inputs": [
        "{projectRoot}/Dockerfile",
        "{workspaceRoot}/dist/target/orders-service/release/orders-service"
      ],
      "executor": "nx:run-commands",
      "options": {
        "command": "docker build -f apps/orders-service/Dockerfile -t orders-service:local ."
      }
    }
  }
}

Two project.json excerpts (JSON with comments, which Nx accepts): implicitDependencies adds the Rust-to-TypeScript edge so nx affected sees it, and dependsOn makes schema generation and the Docker image wait for the Rust build.

How do you run affected-only CI for Rust and TypeScript together?

A single nx affected -t build test lint --base=origin/main call covers both languages. Nx computes the affected set from the project graph and runs each target only where it is defined, so a TypeScript-only change never invokes cargo. Granularity is per crate: editing one library marks that crate and its dependents (inferred from Cargo plus your implicitDependencies), not the whole Rust tree.

The root Cargo.lock and Cargo.toml are inputs to every Rust project, and that is correct. A lockfile bump can change any crate's resolved dependencies, so every Rust project is marked affected. Routine dependency updates will rebuild all Rust code. Plan CI capacity around that case and don't try to exclude the lockfile from inputs.

Parallelism is limited by Cargo itself. Concurrent cargo invocations that share a target directory wait on its build lock ("Blocking waiting for file lock"), so --parallel=4 mostly queues Rust tasks behind each other. When many crates are affected, one workspace-level cargo build/cargo test with -p flags for the affected crates is usually faster, because Cargo schedules its own compilation across cores. Giving each project its own CARGO_TARGET_DIR removes the lock contention. The cost is that shared dependencies are compiled once per directory, which multiplies disk use and total CPU time.

Illustrative estimate. Assume 40 PRs/day, a full pipeline of 20 minutes, and an affected-only run of 6 minutes. Assume also that 25% of PRs touch the lockfile and get no saving. The remaining 30 PRs each save 14 minutes, about 7 hours of reduced wait time per day.

When should you avoid Nx for Rust, and what are the alternatives?

That saving only holds if the orchestration layer costs less to run than it returns, and for many Rust-heavy repos it does not.

Nx adds a second build graph on top of Cargo's. Cargo already does incremental compilation in target/, and Nx caches task outputs on top of that, so you maintain two caching layers with different invalidation rules. If your Nx inputs leave out rust-toolchain.toml or the target triple, a cache hit can restore binaries built by a different compiler. If outputs point at whole target/ directories, the cache grows by gigabytes quickly. The monodon plugin is community-maintained, so expect a delay between new Nx or Cargo releases and plugin support.

Skip Nx when the repo is almost entirely Cargo. It also adds little when the TypeScript parts never consume Rust artifacts. In both cases Cargo's own dependency graph already covers most of what Nx would give you.

Approach Setup cost Cross-language awareness Caching Maintenance burden
Cargo workspace + CI path filters Low Manual, via path globs Cargo incremental plus CI cache Path filters drift as crates move
Cargo workspace + task runner script Low to medium Whatever you script Cargo incremental only You own the script
Nx with monodon Medium to high Project graph plus implicit dependencies Nx task cache over Cargo Plugin upgrades, input tuning

Pick Nx when Rust and TypeScript projects genuinely depend on each other and you need one affected graph across both.

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 cargo, 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.