What is the Nx Gradle plugin and how does it build the Gradle project graph?

The Nx Gradle plugin (@nx/gradle) lets Nx treat a Gradle build as a set of Nx projects without you rewriting anything. It does not parse your build.gradle.kts files. Instead, Nx runs Gradle through the wrapper (./gradlew) and asks it to report its projects, tasks and dependencies. Gradle's configuration phase already resolves plugins, conventions and dynamic logic, so its answer is more reliable than any static parser could be.

The mapping is direct. Every project included in settings.gradle(.kts) becomes a node in the Nx project graph. Every project(":libs:billing-core") dependency becomes an edge. Gradle tasks become Nx targets. A Spring Boot service typically shows build, test and bootJar, along with whatever other tasks its applied plugins register. Run nx show project orders-service to see exactly which targets were inferred and what each one maps to. Check this before you wire anything into CI.

Calling nx run orders-service:bootJar still executes the Gradle task. Nx adds work around that call:

  • It consults its cache before running the task.
  • It schedules dependent work from the graph.
  • It can run the task alongside non-Gradle targets, such as a frontend build.

Calling ./gradlew :orders-service:bootJar directly skips that layer, which is fine for local iteration.

The guiding principle is that Gradle remains the source of truth for how code is built, and Nx coordinates across the repo. If you find yourself redefining compile logic in Nx configuration, you are working against the design.

Inferred target names and plugin behavior have changed between Nx releases. Verify them against the version pinned in your repo.

# Assumed settings.gradle.kts (Gradle is the source of truth):
#   include(":orders-service", ":libs:billing-core")
# and in orders-service/build.gradle.kts:
#   dependencies { implementation(project(":libs:billing-core")) }

# Register the plugin so Nx infers projects and targets from Gradle.
npx nx add @nx/gradle

# Ask Gradle what it sees. Nx gets the same information through the wrapper.
./gradlew projects

# List the targets Nx inferred for the service, such as build, test and bootJar.
# Check these names against your pinned Nx version before wiring CI.
npx nx show project orders-service --json

# Open the project graph. The project(...) dependency appears as an edge
# from orders-service to the billing-core project.
npx nx graph

# Run through Nx. It checks the cache and schedules dependent work from the graph,
# then invokes the Gradle task.
npx nx run orders-service:bootJar

# Run Gradle directly. This skips Nx caching and orchestration,
# which is fine for local iteration.
./gradlew :orders-service:bootJar

Adding @nx/gradle to an existing Spring Boot build, inspecting the inferred projects and targets, and comparing an Nx-orchestrated run with a direct Gradle wrapper call.

Who should use Nx with Gradle, and when should you avoid it?

Nx earns its place when the repo is mixed. A Spring Boot monorepo that also holds a React or Angular frontend, a Node BFF, or shared TypeScript contracts benefits from one project graph that spans both worlds. nx affected can then skip the frontend build when only a Java service changed, and task ordering can express that the UI's end-to-end tests depend on a running backend. Gradle alone cannot see across that language boundary.

In a Java-only repo the case is weaker. Gradle already has a dependency-aware task graph, a local and remote build cache, and configuration options that keep incremental work cheap. Adding Nx there mostly duplicates what you have.

Also avoid Nx when your Gradle configuration phase is slow. Nx invokes Gradle to compute the graph, so every second of configuration time shows up in each Nx command and in each CI job's startup. Fix configuration performance first, or the extra layer makes things feel worse.

Team fit matters too. Nx brings a Node runtime, a package.json, and JavaScript tooling into the repo. JVM-only teams often resist that, and with good reason: engineers now need two mental models. When a build misbehaves, they have to work out whether the cause is Nx's inference, Nx's cache, or Gradle itself.

Repo shape Recommendation Main reason
Spring Boot + frontend/Node projects Use Nx Unified graph, cross-language affected runs
Java/Kotlin only Stay with Gradle Build cache and task graph already cover it
Slow Gradle configuration Defer Nx Configuration cost added to every Nx command
Team rejects Node tooling Avoid Ongoing friction and split debugging

How should you structure a Spring Boot monorepo so Nx sees a clean graph?

Use a single Gradle build with one settings.gradle.kts at the repository root. Put deployable Spring Boot applications under services/ and shared code under libs/, for example services/orders, services/billing, libs/common-domain and libs/web-support. The settings file includes each one explicitly, such as include(":services:orders", ":libs:common-domain"). Every included path becomes a Gradle subproject, and the Nx Gradle plugin turns each subproject into an Nx project node.

Edges come from how services consume libraries. In services/orders/build.gradle.kts, declare implementation(project(":libs:common-domain")) rather than a Maven coordinate like com.example:common-domain:1.4.0. A project(...) dependency is visible in Gradle's own model, so Nx records it as an edge from orders to common-domain. A coordinate dependency resolves to a JAR from a repository. Nx treats it as external, so changing the library's source has no effect on orders in the graph. That gap is what makes nx affected skip services that actually need rebuilding.

Avoid composite builds (includeBuild) and dependency substitution as ways to stitch the repo together. They work for Gradle, but they hide the relationship behind a substitution rule instead of declaring it directly, and they split one logical repository into several builds.

Keep the rest of the layout simple:

  • Apply the Spring Boot plugin only in services/*. Libraries should produce plain JARs.
  • Put shared build conventions in buildSrc or a convention plugin, not in library projects. This keeps tooling out of the dependency graph.
  • Keep project paths stable. Renaming :libs:common-domain changes the Nx project name and breaks any targets or CI filters that reference it.
// settings.gradle.kts (repository root): one build, every module included explicitly
rootProject.name = "shop-platform"

include(
    ":services:orders",     // deployable Spring Boot app -> Nx node "orders"
    ":services:billing",    // deployable Spring Boot app -> Nx node "billing"
    ":libs:common-domain",  // plain JAR library -> Nx node "common-domain"
    ":libs:web-support"     // plain JAR library -> Nx node "web-support"
)
// No includeBuild(...) and no dependencySubstitution: all relationships stay in one model.

// services/orders/build.gradle.kts
plugins {
    java
    // Plugin versions are declared once in buildSrc or a convention plugin, not here.
    id("org.springframework.boot")
    id("io.spring.dependency-management")
}

dependencies {
    // project(...) dependencies are visible in Gradle's model,
    // so Nx records edges orders -> common-domain and orders -> web-support.
    implementation(project(":libs:common-domain"))
    implementation(project(":libs:web-support"))

    // Avoid this: a published coordinate is treated as external,
    // so source changes in libs/common-domain would not mark orders as affected.
    // implementation("com.example:common-domain:1.4.0")

    // Third-party dependencies stay external in the graph, which is expected.
    implementation("org.springframework.boot:spring-boot-starter-web")
    testImplementation("org.springframework.boot:spring-boot-starter-test")
}

A root settings.gradle.kts that includes services and libraries as subprojects, and an orders service build file that consumes shared libraries through project(...) dependencies so each becomes an edge in the Nx graph.

How do you add the Nx Gradle plugin to an existing repo incrementally?

Adopt Nx as a layer on top of Gradle, not a replacement for it. Developers should keep running ./gradlew exactly as before, and nothing in settings.gradle(.kts) or the build scripts should need to change for Nx to work.

  1. Install with pinned versions. Add nx and @nx/gradle as dev dependencies at exact versions, without ^ or ~ ranges, and commit the lockfile. The plugin infers projects and targets by asking Gradle about the build. A floating version can change that inference without anyone noticing. nx add @nx/gradle registers the plugin in nx.json. Pin it afterward if the installer wrote a range.

  2. Verify the graph before trusting it. Open nx graph and check that each Spring Boot service and shared library appears with the edges you expect. Then run nx show project <name> on a few projects to see which targets were inferred and what inputs and outputs they declare. A missing edge here means a missed rebuild later.

  3. Run targets side by side. Run nx run <project>:build and nx run <project>:test, then run the same tasks directly with ./gradlew. Compare test counts, the produced JARs, and which tasks ran. They should match.

  4. Move CI last. Switch CI to nx affected only after the graph checks out. At that point CI uses a different entry point than developers do locally, so a project that Nx misreads will fail only in CI, or go untested there. Keep a scheduled full ./gradlew build running as a backstop.

After every Nx or plugin upgrade, repeat steps 2 and 3 before merging.

#!/usr/bin/env bash
# Incremental Nx adoption check for an existing Gradle/Spring Boot repo.
# ./gradlew workflows and settings.gradle(.kts) are left untouched.
set -euo pipefail

# 1. Install at exact versions (no ^ or ~) and commit the lockfile.
NX_VERSION="${NX_VERSION:?set NX_VERSION to the exact version you chose}"
npm install --save-dev --save-exact "nx@${NX_VERSION}" "@nx/gradle@${NX_VERSION}"
npx nx add @nx/gradle            # registers the plugin in nx.json
grep -E '"(nx|@nx/gradle)"' package.json   # confirm no range crept back in

# 2. Verify inferred projects, edges and targets before trusting them.
npx nx graph --file=graph.json   # write the project graph to disk for review
jq '.graph.dependencies["orders-service"]' graph.json   # expect shared-lib edges
npx nx show project orders-service --json | jq '.targets | keys'

# 3. Run the same work through Nx and through Gradle, then compare.
npx nx run orders-service:test --skip-nx-cache
nx_results=$(find orders-service/build/test-results -name '*.xml' | wc -l)

./gradlew :orders-service:test --rerun-tasks
gradle_results=$(find orders-service/build/test-results -name '*.xml' | wc -l)

echo "test result files: nx=${nx_results} gradle=${gradle_results}"
[ "${nx_results}" -eq "${gradle_results}" ] || { echo 'mismatch: inspect before switching CI'; exit 1; }

# 4. Only after steps 2-3 pass: the CI command, compared against the main branch.
#    Keep a scheduled full './gradlew build' job alongside it as a backstop.
# npx nx affected -t build test --base=origin/main --head=HEAD

# Re-run steps 2 and 3 after every Nx or @nx/gradle upgrade, before merging.

A script that pins Nx and @nx/gradle to exact versions, checks the inferred graph and targets for one service, compares an Nx test run with the equivalent ./gradlew run, and leaves the affected-based CI command as the final step.

How does nx affected work in CI for Spring Boot services?

nx affected compares two git refs, maps the changed files to projects, then walks the Gradle project graph to find every project that depends on them. In CI, set the refs explicitly with --base and --head. On a pull request, use the merge-base with the target branch as the base and the PR commit as the head. On the main branch, use the last commit that passed CI as the base. If you use the previous commit instead, a failed build drops its changes from the next comparison.

A change to a shared library such as libs/common-security marks every service that declares a project(...) dependency on it as affected. This is correct, because the services compile against that code.

Changes to root build logic should mark everything as affected. That includes build-logic, buildSrc, version catalogs, root build.gradle(.kts) and settings.gradle(.kts). Check that your setup treats these files that way, and add them to the shared inputs if it does not. A dependency upgrade in the catalog invalidates every project that uses it. Accept that as correct.

Neither tool can see runtime coupling such as HTTP contracts, shared database schemas or message formats. "Not affected" does not mean you can skip integration or contract tests.

Illustrative estimate (assumed inputs): 12 services, each taking 4 minutes to build and test serially, so 48 minutes in total. A typical PR touches 2 services, and Nx adds 1 minute of overhead, so the run takes about 9 minutes. At 30 PRs a day, that saves about 19.5 hours of wait time daily. The savings disappear on any PR that touches a version catalog, a convention plugin, or a library that every service depends on.

#!/usr/bin/env bash
# CI step: run build/test only for projects affected by this change.
# Assumes a full-history checkout; shallow clones break merge-base.
set -euo pipefail

TARGET_BRANCH="${TARGET_BRANCH:-main}"
CI_EVENT="${CI_EVENT:-push}"   # set by your pipeline: "pull_request" or "push"
HEAD_SHA="$(git rev-parse HEAD)"

git fetch --no-tags origin "$TARGET_BRANCH"

if [ "$CI_EVENT" = "pull_request" ]; then
  # PR: compare against where the branch forked from the target branch,
  # not the target's tip, so other people's merges are not counted.
  BASE_SHA="$(git merge-base "origin/$TARGET_BRANCH" HEAD)"
else
  # main: compare against the last commit that passed CI. Using HEAD~1 would
  # silently drop the changes from a failed build out of the next comparison.
  if git fetch origin "refs/tags/ci-last-green:refs/tags/ci-last-green" 2>/dev/null; then
    BASE_SHA="$(git rev-parse ci-last-green)"
  else
    echo "No last-green marker found; running everything."
    npx nx run-many -t build test
    exit 0
  fi
fi

echo "Affected range: $BASE_SHA..$HEAD_SHA"
npx nx show projects --affected --base="$BASE_SHA" --head="$HEAD_SHA"
npx nx affected -t build test --base="$BASE_SHA" --head="$HEAD_SHA"

# Advance the marker only after a green run on main.
if [ "$CI_EVENT" != "pull_request" ]; then
  git tag -f ci-last-green "$HEAD_SHA"
  git push -f origin ci-last-green
fi
# Integration and contract tests run in a separate, unconditional job:
# runtime coupling (HTTP, schemas, messages) is not in the project graph.

A CI script that computes the base ref from the PR merge-base or from the last green commit on main, then runs nx affected with explicit --base and --head, and falls back to building everything when no baseline exists.

Should you use Nx caching, Gradle's build cache, or both?

Nx and Gradle can both skip work, but they do it at different levels. Gradle hashes each task's declared inputs, such as source sets, classpaths, and plugin configuration, and restores outputs per task. Nx hashes the inputs configured for the whole target, such as files, environment variables, and dependent projects, and replays the target's terminal output and declared output directories. When you stack the two, a cache hit has two possible sources, and each layer only knows about its own inputs.

Concern Gradle build cache only Nx cache only Both
Granularity Per task Per target Mixed
Who defines inputs Plugin authors, mostly correct You, in Nx config Both, can disagree
Stale-hit risk Low Medium if inputs are incomplete Highest
Debugging cost One log to read One hash to inspect Two layers to rule out

Here is how a stale result happens. Suppose an Nx target's inputs leave out gradle/libs.versions.toml or a convention plugin under buildSrc. Nx replays an old bootJar even though Gradle would have rebuilt it. Your build logs say "cache hit", and the jar is wrong.

The safer default is to choose one layer:

  • Gradle cache plus incremental execution: use this for Java targets, and let Nx handle only graph ordering and affected.
  • Nx caching: use this only if you want one remote cache across Java and frontend work.

Before you trust a cache hit, verify the declared inputs:

  • Nx: inspect the resolved inputs and outputs with nx show project. Then run the target with --skip-nx-cache and compare the outputs.
  • Gradle: run with --info or -Dorg.gradle.caching.debug=true to see which input hashes changed.

How do you orchestrate Java and frontend tasks in one pipeline?

Nx's dependsOn lets you express "build the frontend before packaging the service" in the workspace layer instead of the build script. For example, the Spring Boot project's packaging target (say, bootJar as inferred by the plugin) can be overridden in that project's project.json. You add a dependsOn entry pointing at the build target of the frontend project, using the object form with projects and target. When anyone runs the packaging target through Nx, the frontend build runs first. If the frontend is unchanged, the frontend build is restored from cache.

The handoff between the two is a directory. The frontend writes its bundle to a known output path, and the backend's Gradle build reads static resources from a configurable location. That location should default to something that exists without the frontend, such as an empty or committed placeholder directory. Gradle never invokes npm, never knows a JavaScript project exists, and has no task that shells out to another toolchain.

This separation matters for three reasons:

  • ./gradlew stays usable on its own. A backend engineer can run ./gradlew test or ./gradlew bootRun without Node installed, and the build doesn't fail on a missing frontend.
  • The Gradle build stays portable. You can extract the service, run it under a different orchestrator, or build it in a JVM-only container image without touching the Gradle files.
  • Nx stays accurate. Cross-language edges live in one place, so the project graph shows them, and nx affected correctly marks the service as affected when frontend code changes.

For caching, declare the frontend's outputs as inputs to the packaging target, for example with dependentTasksOutputFiles. Without this, a cached jar can be restored that contains stale frontend assets.

Why is a project or dependency missing from the Nx graph?

The Nx graph is built from what Gradle reports during configuration. When a project or edge is missing, check what Gradle sees before changing anything in Nx.

Gradle configuration fails

If any build script throws during configuration, the plugin may get no data back. Graph computation then fails, or projects are missing. Common causes are an unresolvable plugin, a missing environment variable read at configuration time, or a JDK mismatch. Run ./gradlew projects from the root with the same JDK and environment Nx uses. If that command fails, fix it first. Nx cannot work around a build that Gradle itself cannot configure.

Plugin registered in the wrong place

Installing the package is not enough. The plugin must be listed in the plugins array of the root nx.json. Also check the plugin's include and exclude patterns, because a too-narrow pattern hides projects that Gradle reports correctly.

Dynamically created projects

Some settings.gradle files include projects based on properties, environment variables, or directory scans. Those projects appear only when those conditions hold during graph computation. If CI and local runs set them differently, the graphs will differ too.

Undeclared project dependencies

Nx draws an edge only when Gradle reports one. Suppose service A consumes library B through Maven coordinates resolved from a repository, rather than through project(":b"). Gradle treats B as an external artifact, so Nx shows no edge, and nx affected will skip A when B changes.

Stale graph cache

Nx caches the computed graph, and the daemon keeps it in memory. If settings.gradle changed and the graph still looks wrong, run nx reset. This clears the cache and stops the daemon, so the next command recomputes the graph from Gradle's current output.

What are the alternatives to Nx for a Gradle monorepo?

Nx is one way to make a Gradle monorepo change-aware, not the only one. Which option fits depends mostly on what your repo contains and how much tooling you want to own.

Gradle alone. Gradle already skips up-to-date tasks and can reuse outputs from its build cache, so a full ./gradlew build on an unchanged module is cheap. What it lacks is a built-in "only what changed since main" mode. Teams usually write a script that maps changed file paths to Gradle projects and then runs those projects plus their dependents, for example with the Java plugin's buildDependents task. This works well for JVM-only repos, but you maintain the mapping script yourself, and it knows nothing about a frontend or Python tooling.

CI path filtering. Most CI systems can trigger a job when files under a path change. Setup takes minutes, but the filters are static. If services/orders depends on libs/common, someone has to remember to add libs/common/** to the orders job. Missed transitive dependencies mean changes reach main untested.

Nx on top of Gradle. Nx reads the dependency graph from Gradle, so affected detection follows real project dependencies, and it handles non-JVM projects through the same graph. The cost is another tool, its daemon, and its configuration to learn and keep upgraded.

Option Setup cost Maintenance cost Change-detection accuracy Mixed-language support
Gradle + scripts Medium Medium (custom scripts) Good if the scripts use the Gradle graph Poor
CI path filtering Low High as the repo grows Misses transitive dependencies Per-path only
Nx + Gradle Medium Low to medium Graph-based Good

If the repo is all Gradle, start with Gradle and a small script. Add Nx when non-JVM projects share the pipeline.

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 gradle plugin, 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.