What is the nx gradle plugin and how does it build the Gradle project graph?
The nx gradle plugin is a thin orchestration layer that sits on top of an existing Gradle build. It does not replace Gradle, re-implement its task model, or try to read your build scripts itself. Instead, Nx asks Gradle to describe the multi-project build. Gradle evaluates its own configuration and reports back which projects exist, which tasks each one exposes, and how they depend on each other.
This design matters because Gradle build scripts are programs. Plugins, convention plugins in buildSrc or included builds, and Kotlin DSL logic can add tasks and dependencies at configuration time. A static parser would miss these. Asking Gradle means Nx sees the build as Gradle actually configures it.
settings.gradle (or settings.gradle.kts) remains the source of truth for which Gradle projects exist. If a subproject is not included there, Nx will not discover it. When one Gradle project declares a project dependency on another, that relationship becomes an edge in the Nx graph. Nx places these edges in the same graph as the JavaScript and TypeScript projects it discovers from package.json files.
Who owns what
| Concern | Owner |
|---|---|
| Compilation, testing, packaging | Gradle (and Node tooling for TS projects) |
| Maven/artifact dependency resolution | Gradle |
| Workspace-wide project graph across languages | Nx |
| Affected detection from changed files | Nx |
| Caching | Nx at the target level; Gradle's build cache at the task level, inside a target |
Treat Nx as the layer that decides what to run, and Gradle as the layer that decides how to build a JVM project.
+--------------------------------------------------------------------+
| Nx (orchestration: decides WHAT to run) |
| - one project graph: Gradle + JS/TS projects |
| - Gradle project dep :api --> :core = Nx edge |
| - affected detection from changed files |
| - cache at the target level |
+--------------------------------------------------------------------+
| ^ | ^
query | | projects, tasks, targets | | package.json
build | | deps (= edges) | | projects
v | v |
+--------------------------------+ +--------------------------------+
| Gradle: decides HOW to build | | Node tooling (JS/TS projects) |
| settings.gradle(.kts) | | package.json = project list |
| = which projects exist | | compile / test / bundle |
| compile / test / package | | |
| Maven artifact resolution | | |
| build cache (task level) | | |
+--------------------------------+ +--------------------------------+
Nx asks Gradle to describe the multi-project build and reads package.json files for JS/TS projects, then merges both into one project graph for affected detection and target-level caching. Gradle and Node tooling still compile, test and resolve dependencies.
Who should use Nx with Gradle, and when should you avoid it?
The case for Nx over Gradle is strongest when the repository is genuinely polyglot. Picture Spring Boot services next to a TypeScript frontend, with an API client generated from the services' OpenAPI specs. Here no single build tool sees the whole dependency chain. Gradle knows nothing about the frontend, and the Node toolchain knows nothing about the services. Nx can model the chain from service to generated client to UI as one graph. A change to a controller then marks the downstream frontend as affected, and CI runs one command instead of two pipelines that each have to be kept in sync.
The case is weak when the repository is almost entirely JVM. Gradle already handles up-to-date checks, task-level caching and parallel execution across subprojects. Putting Nx on top adds a second graph that mostly mirrors the first. It also adds another configuration surface and a Node toolchain that every Java developer has to install.
The bigger cost is that engineers now need two mental models. When a build is skipped or fails, they have to work out which layer made the decision:
- Did Nx skip the target because of its cache or its affected logic?
- Or did Gradle skip the task because it was up to date?
Debugging means checking both, and that takes longer for engineers who only know one of the tools.
IDE workflows also stay Gradle-centric. IntelliJ imports, runs and debugs through Gradle directly and bypasses Nx. Day-to-day local work therefore never touches the Nx layer, which leaves Nx-specific problems to surface in CI, where they are slower to diagnose. Include this in onboarding: new hires need to learn when to run a target through Nx and when it is fine to run it directly through Gradle.
How do you set up the nx gradle plugin in an existing repository?
Before any of that matters, the repository needs three things in place.
Prerequisites
- A Gradle wrapper at the workspace root. The plugin invokes Gradle to read the build, and the wrapper ensures it uses the Gradle version you have pinned rather than whatever happens to be installed on a developer laptop or CI agent.
- A single root multi-project build. The root
settings.gradle(orsettings.gradle.kts) should include each Spring Boot service as a subproject. - An Nx workspace in the same repository, with
nx.jsonand apackage.jsonat the root.
One Gradle root integrates more easily because the plugin reads one build model, and inter-project dependencies such as implementation project(':shared-lib') already appear in it. Several independent roots produce disconnected islands, and Nx cannot see dependencies that cross them.
If you have several roots, you have two options. You can consolidate them by adding include entries to a single root settings file, which is usually straightforward when the builds share conventions. The other option is to accept that each root is handled separately and that edges between roots will not be inferred.
Installation
Run nx add @nx/gradle from the root. This installs the package and registers the plugin in nx.json. Pin the plugin to the same version as your nx package. A mismatch between the two is a common source of confusing inference errors.
Next, open nx graph and run nx show project <service-name> for each service. Every Spring Boot service should appear in the graph with its inferred targets before you change any CI configuration.
#!/usr/bin/env bash
# Run from the repository root. Assumes Node.js and an existing Nx workspace.
set -euo pipefail
# 1. Confirm the prerequisites are in place.
test -x ./gradlew || { echo "Missing Gradle wrapper at root"; exit 1; }
test -f settings.gradle.kts || test -f settings.gradle || { echo "Missing root settings file"; exit 1; }
test -f nx.json || { echo "Missing nx.json"; exit 1; }
# The root settings file should include every service as a subproject, e.g.
# include("orders-service", "billing-service", "shared-lib")
# Gradle prints the subprojects it actually sees.
./gradlew projects
# 2. Install the plugin at the same version as the installed nx package,
# so the plugin and the Nx core do not drift apart.
NX_VERSION=$(node -p "require('./node_modules/nx/package.json').version")
npx nx add @nx/gradle@"$NX_VERSION"
# Check that both packages resolve to the same version.
npm ls nx @nx/gradle
# 3. Verify inference before changing CI.
# List every project Nx knows about. Each Gradle service should appear.
npx nx show projects
# Print each service's configuration, including its inferred targets.
for svc in orders-service billing-service; do
npx nx show project "$svc" --json
done
# Open the project graph to check edges such as orders-service -> shared-lib.
npx nx graph
A shell walkthrough that checks the Gradle wrapper and root settings, installs @nx/gradle at the same version as nx, and confirms each Spring Boot service appears with inferred targets before you change any CI configuration.
How do inferred Nx targets map to Gradle tasks for Spring Boot services?
The plugin reads each Gradle project's task list and exposes tasks as Nx targets with matching names. Running nx run orders-service:test invokes that project's Gradle test task. Inputs, outputs and task ordering still come from Gradle; Nx adds a consistent name and a place in the project graph.
Overriding without touching Gradle scripts
To change orchestration, edit nx.json (targetDefaults) for workspace-wide rules, or a service's project.json for one service. These files can set caching, dependsOn and extra inputs. Keep the actual work, such as compiler flags, test filters and plugin settings, in build.gradle(.kts). If you put task logic in Nx, a developer who runs ./gradlew directly gets a different build than CI does.
Spring Boot targets
| Target | Gradle task | Nx cache | Reason |
|---|---|---|---|
build |
build |
Yes | Deterministic outputs |
test / check |
test / check |
Yes | Reports and results are reproducible |
serve |
bootRun |
No | Long-running process with no completed output to restore |
bootJar |
bootJar |
Yes, scoped | Keep it separate so a jar change doesn't invalidate build |
image |
Image-building task | Usually no | Pushes to a registry are side effects |
A serve target should only delegate to bootRun. Set it to non-cacheable, because a cached "success" would skip starting the service.
Gradle invocations
Each Nx task can start its own Gradle invocation. This loses the parallelism Gradle gets when it schedules many tasks in a single build. Keep the Gradle daemon enabled, and avoid --no-daemon in CI, so later invocations reuse a warm JVM instead of paying full startup cost every time.
{
"name": "orders-service",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"targets": {
"serve": {
"executor": "nx:run-commands",
"cache": false,
"options": {
"command": "./gradlew :orders-service:bootRun"
}
},
"bootJar": {
"cache": true,
"outputs": ["{projectRoot}/build/libs"]
},
"image": {
"executor": "nx:run-commands",
"cache": false,
"dependsOn": ["bootJar"],
"options": {
"command": "./gradlew :orders-service:bootBuildImage"
}
}
}
}
A project.json for orders-service that adds serve and image targets delegating to Spring Boot's bootRun and bootBuildImage Gradle tasks with caching disabled, and scopes the inferred bootJar target's cached outputs to build/libs, while all build logic stays in Gradle.
How do you declare cross-language dependencies between Java and TypeScript projects?
The Gradle plugin builds edges from what Gradle knows: project(...) dependencies, included builds, and the configurations that connect them. It cannot see relationships that cross into the JavaScript side of the repository. One example is a TypeScript client generated from the OpenAPI spec of a Spring Boot service. Another is a frontend that assumes the shape of a backend's JSON responses. Neither appears in a Gradle file or a package.json dependency, so Nx has no reason to connect the two projects.
You have two ways to declare these edges. The coarse option is implicitDependencies in the TypeScript project's configuration. It names the Java project and creates a graph edge, so any change to the service marks the client as affected. The precise option adds a task input to the client's generation target that points at the spec file itself, for example a {workspaceRoot}/... path to the service's openapi.yaml. Only spec changes then invalidate the cache and trigger regeneration. Many teams use both: the edge for affected detection and the input for caching. After you add them, run nx graph and confirm the edges appear.
An undeclared edge is dangerous because it fails without any signal. A breaking API change passes CI, the client is never rebuilt, and the green build gives false confidence. That outcome is worse than running every target.
To keep these declarations current, put them in the same pull request that introduces the contract, and add a review checklist item that asks "does this change produce or consume a cross-language artifact?" Also have the owners of contract files review any change to them.
{
"name": "orders-client",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "libs/orders-client/src",
"projectType": "library",
"implicitDependencies": ["orders-service"],
"targets": {
"generate-client": {
"executor": "nx:run-commands",
"cache": true,
"inputs": [
"{workspaceRoot}/services/orders-service/src/main/resources/openapi.yaml"
],
"outputs": ["{projectRoot}/src/generated"],
"options": {
"command": "npx @openapitools/openapi-generator-cli generate -i services/orders-service/src/main/resources/openapi.yaml -g typescript-fetch -o libs/orders-client/src/generated"
}
},
"build": {
"dependsOn": ["generate-client"]
}
}
}
A project.json for a generated TypeScript client. implicitDependencies adds a graph edge to the Gradle project orders-service for affected detection. The spec-file input limits cache invalidation to changes in openapi.yaml.
How should Nx caching and the Gradle build cache work together?
Nx and Gradle cache at different granularities, and the two layers only cooperate when Nx's view of a target's inputs is at least as wide as what Gradle reads.
| Layer | Unit cached | Keyed on | Best at |
|---|---|---|---|
| Nx cache | Whole target (e.g. build, test) |
Declared inputs, hashed by Nx | Skipping Gradle entirely, sharing results across machines |
| Gradle build cache | Individual task outputs | Task inputs Gradle tracks itself | Partial rebuilds when only some tasks changed |
| Gradle incremental compilation | Classes within a task | Changed source files | Small edits in a warm local workspace |
If a Nx target's inputs miss a file that Gradle actually reads, Nx replays an old jar or test result after a real change. That is a stale output, and nothing warns you. Include these in the inputs:
- Sources and resources
build.gradle(.kts)andsettings.gradle(.kts)gradle.properties- The version catalog
buildSrcor included convention-plugin builds- The wrapper properties
Declare the project's build directory as the output so a replay restores what downstream targets consume.
Use Nx caching for coarse wins: unchanged services in CI, where a hit avoids starting a JVM at all. Keep the Gradle build cache enabled for partial changes inside a project, where Gradle's per-task tracking is more precise than any glob you write.
Project graph computation calls into Gradle. On a cold daemon this is slow, and any build-script change invalidates it. Warm the daemon early in CI jobs.
Illustrative estimate: assume 12 services, 3 changed per PR, and 90 seconds per full build. Without replay, building all 12 takes 18 minutes. With replay of the 9 unchanged services, at roughly 5 seconds each, the job takes about 5 minutes.
Running affected Gradle and Node targets in CI, plus a verification checklist
The CI job needs one change-detection step that covers both languages. Fetch enough Git history to reach the base commit, usually the merge base with the main branch. Then call nx affected with explicit --base and --head values and one target list such as build and test. Nx computes the affected set from a single project graph, so Gradle tasks and Node tasks are selected by the same rules. Nx then runs them in dependency order.
Persist three things between runs:
- Gradle's dependency and wrapper caches. These avoid downloading dependencies and the Gradle distribution on every run.
- The Nx cache. This can be a restored directory or a remote cache.
- The Gradle build cache, if you enabled it.
An ephemeral runner cannot keep the Gradle daemon between jobs. Within one job, though, the Gradle tasks Nx invokes reuse the same daemon. Avoid passing --no-daemon unless you have a specific reason.
Without a shared graph, each language needs its own detection system, such as path filters for Gradle modules and a separate tool for Node packages. Every new cross-language dependency must then be added to both by hand, and the two drift apart. Missed edges show up as untested breakage after merge. A single graph removes that maintenance work and those failures.
Verification checklist
- Change a shared Java library. Every Spring Boot service that depends on it appears in
nx show projects --affected. - Change only a frontend file. The affected run starts no Gradle tasks.
- Re-run an unchanged commit with a warm cache. Test targets report cache hits and replay their output instead of executing.
- After every Nx upgrade, run
nx show projecton a few Gradle projects and compare the inferred targets and their inputs with the previous version.
What are the alternatives to the nx gradle plugin for a polyglot monorepo?
Three alternatives come up in practice. Each removes the Nx layer but shifts work somewhere else.
Gradle alone. If the repository is mostly JVM code, Gradle's up-to-date checks, task configuration avoidance and build cache already skip unchanged work. IDEs import the build directly, so onboarding is minimal. The cost appears when TypeScript projects matter. Gradle does not understand a package.json dependency graph, so you either wrap Node builds in Gradle tasks or maintain the Java-to-TypeScript edges by hand.
Per-language tools plus CI change detection. Gradle builds Java and the package manager builds Node. A script maps git diff paths to the projects that need rebuilding. This is cheap to start and keeps each ecosystem's native tooling and IDE support. However, the script becomes a second, undocumented project graph. Every new shared contract or generated client adds a path rule someone must remember. Missed rules fail silently: CI goes green while it skips a project that should have been rebuilt.
One build system for every language. A hermetic, polyglot build tool gives a single graph and strong cache correctness. The price is rewriting every build definition, retraining the team and accepting weaker IDE integration for Java than native Gradle import provides.
| Option | Setup cost | Onboarding | Cross-language edges | IDE fit |
|---|---|---|---|---|
| Gradle alone | Low | Low | Manual or wrapped | Native |
| Per-language + scripts | Low | Low | Hand-maintained path rules | Native |
| Single build system | High | High | First-class | Often weaker |
| Nx gradle plugin | Moderate | Moderate | Declared in one graph | Native (Gradle unchanged) |
Nx pays for itself when cross-language edges are numerous and change often. If they are few and stable, Gradle alone or simple path rules are usually enough.
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.