Nx Cloud CI is in private betaJoin the beta
‹ Blog
Juri Strumpflohner
Juri StrumpflohnerJuri Strumpflohner

Full-Stack Type Safety from Spring Boot to TanStack with Nx

Full-Stack Type Safety from Spring Boot to TanStack with Nx
Nx Polyglot Monorepos Series

This article is part of the Nx Polyglot Monorepos series:

I'm again seeing teams move the backend and frontend projects of the same product into a monorepo. The main reason I'm hearing is that a split no longer makes sense (did it ever?) and agents simply perform better when they have full visibility into all parts of the product.

In this series on polyglot monorepos with Nx, I'm exploring what such a setup looks like across different technologies, to give teams a practical starting point.

Today we're going to look into Spring Boot. This is a bit of a throwback for me, since I started using Spring back with its very first beta versions.

The idea is to have a nicely integrated full-stack setup, including type safety across the frontend and backend boundary, so when you rename a field on the API it's immediately reflected in the frontend types. To get there, we'll emit the OpenAPI spec, generate TypeScript types from it, and wire both into the Nx task graph.

The complete example is in juristr/nx-polyglot-java-spring.

Our example setup

For this example, we'll use a small coffee shop app: three Gradle modules for the backend and a TanStack Start storefront that renders products and orders from the API. The storefront UI lives in two feature libraries, and a Playwright project tests the whole stack end to end.

apps/
├── products-api/        # Spring Boot app (Gradle)
├── storefront/          # TanStack Start app
└── storefront-e2e/      # Playwright tests against the storefront and the API
libs/
├── backend/
│   ├── catalog-data/    # Product record and repository (Gradle)
│   └── orders/          # OrderService (Gradle)
├── frontend/
│   ├── products/        # ProductList, ProductCard
│   └── orders/          # OrderTable, OrderSummary
└── shared/
    └── api-types/       # Shared TypeScript types generated from the API's OpenAPI spec

Those are the folder paths. Here's how the projects depend on each other in the Nx project graph:

Nx project graph grouped by folder: apps contains storefront-e2e, storefront and products-api; libs is grouped into frontend (storefront-orders and storefront-products), shared (api-types) and backend (orders and catalog-data). storefront depends on both frontend libraries and api-types, api-types has an implicit edge to products-api, and products-api depends on orders and catalog-data.

The implicit edge between api-types and products-api is the interesting one, and we'll come back to it. The two feature libraries only import the generated types from api-types, never each other. The contract the storefront cares about is a plain Java record in the data layer:

libs/backend/catalog-data/src/main/java/com/example/shop/catalog/Product.java
/** A product in the catalog. This record is the contract the storefront sees. */
public record Product(long id, String name, String description, String category, BigDecimal price) {}

products-api exposes it through /products, together with a few order endpoints built on top of it in orders.

Product API contract

In a real-world setup, you might want an anti-corruption layer (ACL) to safeguard the boundary between backend and frontend. That changes the level at which you share data structures, not the fact that you want to share them. For this article I'll keep it simple and expose server-side data types directly to the frontend UI.

Here's the final storefront UI (you can clearly see the focus was not on a beautiful design):

The Nx Coffee Supply storefront showing order totals, five product cards and a table of recent orders, all served by the Spring Boot API

Bringing Gradle projects into Nx

To make Nx understand the Gradle build, add the Nx Gradle plugin:

nx add @nx/gradle

The plugin teaches Nx about the Gradle projects:

  • It reads the Gradle build starting from settings.gradle.kts.
  • Every Gradle project becomes an Nx project.
  • Every Gradle task becomes a target.
  • Any project(":x") dependencies become edges in the project graph.

In this workspace the Gradle modules live next to the TypeScript projects, so the settings file maps each one to its folder:

settings.gradle.kts
include("products-api", "catalog-data", "orders")
project(":products-api").projectDir = file("apps/products-api")
project(":catalog-data").projectDir = file("libs/backend/catalog-data")
project(":orders").projectDir = file("libs/backend/orders")

Nx gets that information from Gradle through a small Gradle plugin, dev.nx.gradle.project-graph, which nx add applies in the root build file:

build.gradle.kts
plugins {
    id("dev.nx.gradle.project-graph") version("0.1.27")
    id("org.springframework.boot") version "3.5.16" apply false
}

// ...

allprojects {
    apply {
        plugin("dev.nx.gradle.project-graph")
    }
}

The same plugin adds an nx {} block to every module's build file. That's where you set the Nx project name and tags (for the Nx boundary rules), right next to the regular Gradle dependencies that become graph edges:

libs/backend/orders/build.gradle.kts
nx {
    set("name", "orders")
    array("tags", "type:feature", "scope:api")
}

dependencies {
    api(project(":catalog-data"))
    implementation("org.springframework:spring-context")
}

On the Nx side, the plugin options in nx.json map Gradle tasks to standard Nx target names:

nx.json
{
  "plugins": [
    {
      "plugin": "@nx/gradle",
      "options": {
        "testTargetName": "test",
        "classesTargetName": "classes",
        "buildTargetName": "build"
      }
    }
  ]
}

Running nx graph now shows both the Java and TypeScript projects in a single graph.

Running tasks with Nx

If you're coming from Gradle and haven't used Nx before, it helps to think of Nx as an orchestration layer sitting on top of your existing tools rather than a replacement for them. Gradle still compiles your Java code and runs JUnit, and Vite and TypeScript still handle the frontend. What Nx adds is a single project graph and task runner across both stacks.

Instead of switching between ./gradlew :products-api:build on the backend and pnpm scripts on the frontend, every project exposes targets you invoke the same way:

nx build products-api         # runs Gradle's build for products-api (and its dependencies)
nx build storefront           # builds the TanStack Start app
nx run-many -t build test     # builds and tests both Java and TypeScript projects
nx affected -t build test     # runs only projects affected by your changes

You can also inspect any project's inferred targets and dependencies with nx show project products-api. Because Nx understands the full graph across languages, it runs prerequisites in order, caches task outputs locally and on CI, and can wire a Gradle task directly into a TypeScript task.

Already have a Spring Boot app?

The API in this workspace started as a standalone project and was brought in with nx import, which keeps its git history. We've also covered adding a Spring Boot app to an existing Nx workspace before.

Emitting the OpenAPI spec at build time

To generate TypeScript types, we need a machine-readable description of the API. springdoc-openapi produces an OpenAPI document for a Spring Boot app and serves it at /v3/api-docs. The catch is that it only does so at runtime.

springdoc has no build-time writer. The official springdoc Gradle plugin starts the application, waits for it to listen on a port and downloads the document over HTTP, which tends to be slow and fragile on CI.

In our demo I went with a different approach: a Gradle Test task boots the Spring context with a mock servlet environment, requests /v3/api-docs through MockMvc, and writes the response to a file. That avoids starting a real server altogether and gets us as close as Spring allows to build-time spec generation.

apps/products-api/build.gradle.kts
// The OpenAPI contract is written by a JUnit test in its own source set, so
// ordinary `test` runs stay fast and `generateOpenApi` can be cached on its own.
val openapi by sourceSets.creating {
    compileClasspath += sourceSets.main.get().output
    runtimeClasspath += sourceSets.main.get().output
}
configurations[openapi.implementationConfigurationName]
    .extendsFrom(configurations.testImplementation.get())
configurations[openapi.runtimeOnlyConfigurationName]
    .extendsFrom(configurations.testRuntimeOnly.get())

val generateOpenApi by tasks.registering(Test::class) {
    group = "documentation"
    description = "Write the OpenAPI contract without opening a server port"
    dependsOn(tasks.named(openapi.classesTaskName))
    testClassesDirs = openapi.output.classesDirs
    classpath = openapi.runtimeClasspath
    filter { includeTestsMatching("com.example.shop.api.OpenApiSpecTest") }
    workingDir(projectDir)
    systemProperty("openapi.output", "build/openapi/openapi.json")
    systemProperty("user.language", "en")
    systemProperty("user.country", "US")
    systemProperty("user.timezone", "UTC")
    outputs.file(layout.buildDirectory.file("openapi/openapi.json"))
        .withPropertyName("openApiSpec")
}

The separate source set keeps the regular test task fast and gives generateOpenApi its own inputs. The fixed locale and timezone keep the output deterministic when the spec contains dates or other localized values. Otherwise the cache could be invalidated between local and CI runs.

The test itself is minimal: it sorts the keys and pretty-prints the JSON so the same API always produces the exact same output:

apps/products-api/src/openapi/java/com/example/shop/api/OpenApiSpecTest.java
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, properties = {
    "springdoc.api-docs.enabled=true",
    "springdoc.writer-with-order-by-keys=true",
    "springdoc.writer-with-default-pretty-printer=true"
})
@AutoConfigureMockMvc
@ActiveProfiles("openapi")
class OpenApiSpecTest {
    // ...
        String json = mvc.perform(get("/v3/api-docs"))
            // ... assertions on the paths and schemas we expect
            .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8);
        Path output = Path.of(System.getProperty("openapi.output"));
        Files.createDirectories(output.getParent());
        Files.writeString(output, json + "\n", StandardCharsets.UTF_8);
}

There's one quirk to fix on the Spring side: by default, springdoc doesn't mark Java record components as required, so every generated TypeScript field would end up optional (name?: string). Since the records in this API never carry null fields, we add an OpenApiCustomizer to mark all of them as required:

apps/products-api/src/main/java/com/example/shop/api/ShopApplication.java
@Bean
OpenApiCustomizer requireRecordComponents() {
    return openApi -> {
        for (Schema<?> schema : openApi.getComponents().getSchemas().values()) {
            if (schema.getProperties() != null) {
                schema.setRequired(new ArrayList<>(new TreeSet<>(schema.getProperties().keySet())));
            }
        }
    };
}

How Nx sees the task

generateOpenApi is an ordinary Gradle task, so @nx/gradle picks it up as a target without any extra configuration. The outputs.file(...) declaration in Gradle becomes the Nx output {projectRoot}/build/openapi/openapi.json, and the target is cacheable.

❯ nx run products-api:generateOpenApi

 NX   Running 15 tasks with @nx/gradle:gradle

> Task :catalog-data:compileJava
> Task :catalog-data:classes
> Task :catalog-data:jar
> Task :orders:compileJava
> Task :orders:classes
> Task :orders:jar
> Task :products-api:compileJava
> Task :products-api:classes
> Task :products-api:compileOpenapiJava
> Task :products-api:openapiClasses
> Task :products-api:generateOpenApi

BUILD SUCCESSFUL in 3s

———————————————————————————————————————————————————————————————

 NX   Successfully ran target generateOpenApi for project products-api and 14 tasks it depends on (4s)

❯ ls apps/products-api/build/openapi
openapi.json

You don't have to configure task ordering or caching by hand either. @nx/gradle infers both directly from Gradle, which you can inspect with nx show project products-api:

  • Dependencies - compiling products-api plus the jar tasks of orders and catalog-data always run first.
  • Cache inputs - Nx hashes those compiled outputs along with the Gradle classpath (including Spring Boot and springdoc versions), so a code change or dependency upgrade invalidates the cached spec.

That directly controls how far a change propagates. If you rename a field on Product in catalog-data, the new jar changes the input hash of generateOpenApi, which then writes a fresh spec. If you only edit the Javadoc on Product, Gradle still recompiles, but the emitted spec stays identical, so everything downstream of it is a cache hit.

Generating the TypeScript types

On the TypeScript side, @hey-api/openapi-ts turns the spec into types. api-types is a regular TypeScript package, so the generator runs as a package.json script:

libs/shared/api-types/package.json
{
  "name": "@shop/api-types",
  "private": true,
  "scripts": {
    "codegen": "openapi-ts -i ../../../apps/products-api/build/openapi/openapi.json -o src/generated -p @hey-api/typescript"
  },
  "devDependencies": {
    "@hey-api/openapi-ts": "0.99.0"
  }
}

Nx infers a codegen target from that script. Because scripts run with the library folder as their working directory, the paths are relative to libs/shared/api-types.

The library re-exports whatever got generated, so consumers import from @shop/api-types and never reach into the generated folder:

libs/shared/api-types/src/index.ts
// ./generated is written by this project's `codegen` target from the OpenAPI
// document `products-api:generateOpenApi` emits at build time. Nx runs it for
// you before build, dev and typecheck; run `nx codegen api-types` to do it by hand.
export * from './generated/index.js';

The generated Product type mirrors the Java record, with every field required:

libs/shared/api-types/src/generated/types.gen.ts
export type Product = {
  category: string;
  description: string;
  id: number;
  name: string;
  price: number;
};

At this point nx codegen api-types works as long as the spec already exists, but Nx doesn't yet know it needs to run generateOpenApi first. Next, we need to wire that into the task graph.

Wiring codegen into the task graph

This is the pipeline we want:

Task pipeline running left to right: catalog-data:jar and orders:jar, then products-api:generateOpenApi which writes apps/products-api/build/openapi/openapi.json, then api-types:codegen which writes the TypeScript types, then api-types:typecheck, then the typecheck tasks of storefront-products and storefront-orders. The last edge needs no extra Nx config because the feature libraries depend on api-types through a workspace dependency.

@nx/gradle handles the Java side automatically. The right-hand side (api-types:typecheck and storefront-products / storefront-orders typecheck) is already covered by regular pnpm workspace dependencies. We only need to configure the bridge in the middle, in libs/shared/api-types/package.json:

libs/shared/api-types/package.json
{
  "name": "@shop/api-types",
  "private": true,
  "scripts": {
    "codegen": "openapi-ts -i ../../../apps/products-api/build/openapi/openapi.json -o src/generated -p @hey-api/typescript"
  },
  ...
  "nx": {
    "name": "api-types",
    "tags": ["type:types", "scope:shared"],
    "implicitDependencies": ["products-api"],
    "targets": {
      "codegen": {
        "dependsOn": ["^generateOpenApi"],
        "inputs": [
          { "dependentTasksOutputFiles": "**/build/openapi/openapi.json" },
          "{projectRoot}/package.json",
          "sharedGlobals"
        ],
        "outputs": ["{projectRoot}/src/generated"],
        "cache": true
      }
    }
  }
}

Here's what each setting does:

  • implicitDependencies - draws the edge from api-types to products-api by hand. Since we're crossing a language boundary, nothing on the frontend imports from the backend directly. Hence, we have to declare this dependency ourselves.
  • ^generateOpenApi - makes codegen depend on exactly the spec task of its dependencies. With ^build, the tests and the jar of products-api would end up in the chain too, even though codegen only needs the spec.
  • dependentTasksOutputFiles - hashes the spec file that generateOpenApi writes, rather than the Java sources. A Java change that leaves the contract untouched reuses the cached types. Listing inputs replaces the defaults on purpose. Extending them with "..." would inherit ^default and hash the Java sources again. That's why sharedGlobals is added back. The library's own package.json is in there because it pins the generator version.

Who triggers codegen?

You shouldn't have to remember to run codegen manually. Instead, we configure three target defaults in nx.json so consumers pull it in automatically:

nx.json
{
  "targetDefaults": {
    "typecheck": {
      "dependsOn": ["...", "codegen"],
      "inputs": [
        "...",
        { "dependentTasksOutputFiles": "**/*.ts", "transitive": true }
      ]
    },
    "build": { "dependsOn": ["...", "^codegen"] },
    "dev": { "dependsOn": ["...", "^codegen"] }
  }
}

typecheck on api-types depends on its own codegen, while build and dev depend on the codegen target of their dependencies (^codegen). That way nx dev storefront, nx build storefront, and nx typecheck storefront all run generateOpenApi and codegen first, and nx affected does the same on CI. Setting transitive: true on the typecheck input makes Nx track generated .ts files from indirect dependencies too, not just direct ones.

You can inspect the whole chain directly in the task graph with nx typecheck storefront --graph:

Nx task graph for storefront:typecheck grouped by project: storefront:typecheck depends on storefront-products:typecheck and storefront-orders:typecheck, both depend on api-types:typecheck and api-types:codegen, which depends on products-api:generateOpenApi and the upstream Gradle compile and jar tasks across products-api, orders and catalog-data.

Why the types can't go stale

Four pieces of the configuration work together here:

  1. Ordering - codegen always runs, or is restored from cache, before anything that consumes the types.
  2. Hashing - the input of codegen is the spec file itself, so a change to the API contract always invalidates the generated types.
  3. No committed copy - the generated folder is gitignored, so there is no checked-in version that could drift from the spec.
  4. Affected - the implicit dependency makes nx affected treat a change in any of the Java modules as affecting api-types and the storefront.

Keeping the storefront in sync

The TypeScript consumers need almost no Nx configuration. The storefront app and both feature libraries depend on @shop/api-types just like any other workspace package, and Nx picks up the graph edges automatically:

libs/frontend/products/package.json
{
  "name": "@shop/storefront-products",
  "dependencies": {
    "@shop/api-types": "workspace:*"
  }
}

The storefront app fetches data through a TanStack Start server function, typed with the generated types. The call to the Spring Boot API happens on the TanStack Start server, so the browser never talks to the API directly and there is no CORS setup to maintain:

apps/storefront/src/lib/shop-api.ts
import { createServerFn } from '@tanstack/react-start';
import type { Order, OrderSummary, Product } from '@shop/api-types';

// ...

export const getStorefront = createServerFn({ method: 'GET' }).handler(
  async () => {
    const [products, orders, summary] = await Promise.all([
      get<Array<Product>>('/products'),
      get<Array<Order>>('/orders'),
      get<OrderSummary>('/orders/summary'),
    ]);
    return { products, orders, summary };
  },
);

The route passes the data to the components from the feature libraries, which use the generated Product type directly:

libs/frontend/products/src/product-card.tsx
import type { Product } from '@shop/api-types';
import { formatPrice } from './format';

export function ProductCard({ product }: { product: Product }) {
  return (
    <li className="product-card">
      <span className="category">{product.category}</span>
      <h3>{product.name}</h3>
      <p>{product.description}</p>
      <strong>{formatPrice(product.price)}</strong>
    </li>
  );
}

Now let's rename name to title on the Java record:

libs/backend/catalog-data/src/main/java/com/example/shop/catalog/Product.java
-public record Product(long id, String name, String description, String category, BigDecimal price) {}
+public record Product(long id, String title, String description, String category, BigDecimal price) {}

Running nx run-many -t typecheck recompiles the Java modules, writes a new spec, regenerates the types and fails both feature libraries:

❯ nx run-many -t typecheck

# ... Java modules recompile, generateOpenApi writes the updated spec, api-types:codegen regenerates types ...

> nx run storefront-products:typecheck

> tsc -p tsconfig.typecheck.json

src/product-card.tsx:8:20 - error TS2339: Property 'name' does not exist on type 'Product'.

8       <h3>{product.name}</h3>
                     ~~~~

Found 1 error in src/product-card.tsx:8

> nx run storefront-orders:typecheck

> tsc -p tsconfig.typecheck.json

src/order-table.tsx:29:67 - error TS2339: Property 'name' does not exist on type 'Product'.

29                 .map((line) => `${line.quantity} × ${line.product.name}`)
                                                                     ~~~~

Found 1 error in src/order-table.tsx:29

———————————————————————————————————————————————————————————————

 NX   Running target typecheck for 5 projects and 16 tasks they depend on failed

Tasks not run because their dependencies failed:
- storefront:typecheck
- storefront-e2e:typecheck

Failed tasks:
- storefront-products:typecheck
- storefront-orders:typecheck

A backend change in Java breaks the TypeScript typecheck in the very same command, before you even start the dev server or open a browser.

Caching across both stacks

Since every step in the chain has declared inputs and outputs, Nx caches all of them, Java and TypeScript alike. Revert the rename and run the same command twice, and the second run restores all 21 tasks from the cache:

❯ nx run-many -t typecheck

✔  nx run catalog-data:compileJava  [existing outputs match the cache, left as is]
✔  nx run catalog-data:classes  [existing outputs match the cache, left as is]
✔  nx run catalog-data:jar  [existing outputs match the cache, left as is]
✔  nx run orders:compileJava  [existing outputs match the cache, left as is]
✔  nx run orders:classes  [existing outputs match the cache, left as is]
✔  nx run orders:jar  [existing outputs match the cache, left as is]
✔  nx run products-api:compileJava  [existing outputs match the cache, left as is]
✔  nx run products-api:classes  [existing outputs match the cache, left as is]
✔  nx run products-api:compileOpenapiJava  [existing outputs match the cache, left as is]
✔  nx run products-api:openapiClasses  [existing outputs match the cache, left as is]
✔  nx run products-api:generateOpenApi  [existing outputs match the cache, left as is]
✔  nx run api-types:codegen  [existing outputs match the cache, left as is]
✔  nx run api-types:typecheck  [existing outputs match the cache, left as is]
✔  nx run storefront-products:typecheck  [existing outputs match the cache, left as is]
✔  nx run storefront-orders:typecheck  [existing outputs match the cache, left as is]
✔  nx run storefront:typecheck  [existing outputs match the cache, left as is]
✔  nx run storefront-e2e:typecheck  [existing outputs match the cache, left as is]
# ... plus 4 cached processResources tasks

———————————————————————————————————————————————————————————————

 NX   Successfully ran target typecheck for 5 projects and 16 tasks they depend on (1s)

Nx read the output from the cache instead of running the command for 21 out of 21 tasks.

Remember the Javadoc example from earlier? That's where hashing the spec pays off. If you only change the Javadoc comment on Product and rerun typecheck, Gradle recompiles the Java modules and generateOpenApi runs again, producing the exact same spec file. Because codegen hashes that spec output rather than the Java sources, it hits the cache, and every downstream TypeScript typecheck does too:

❯ nx run-many -t typecheck

# Java compile tasks and generateOpenApi rerun, writing the exact same openapi.json
> nx run catalog-data:compileJava
> nx run catalog-data:classes
> nx run catalog-data:jar
> nx run orders:compileJava
> nx run orders:classes
> nx run orders:jar
> nx run products-api:compileJava
> nx run products-api:classes
> nx run products-api:compileOpenapiJava
> nx run products-api:openapiClasses
> nx run products-api:generateOpenApi

# Spec hash is unchanged, so codegen and every TypeScript typecheck hit the cache
✔  nx run api-types:codegen  [existing outputs match the cache, left as is]
✔  nx run api-types:typecheck  [existing outputs match the cache, left as is]
✔  nx run storefront-products:typecheck  [existing outputs match the cache, left as is]
✔  nx run storefront-orders:typecheck  [existing outputs match the cache, left as is]
✔  nx run storefront:typecheck  [existing outputs match the cache, left as is]
✔  nx run storefront-e2e:typecheck  [existing outputs match the cache, left as is]
# ... plus 4 cached processResources tasks

———————————————————————————————————————————————————————————————

 NX   Successfully ran target typecheck for 5 projects and 16 tasks they depend on (2s)

Nx read the output from the cache instead of running the command for 10 out of 21 tasks.

Nx caches the generated files too: if you delete apps/products-api/build/openapi/openapi.json and run nx run products-api:generateOpenApi, Nx restores it straight from the cache.

Wrapping up

We now have a Spring Boot API and a TanStack Start storefront that share their types through the Nx task graph:

  • @nx/gradle turns the Gradle build into Nx projects and targets, including a custom generateOpenApi task
  • a Gradle Test task writes the OpenAPI spec through MockMvc, without opening a port
  • openapi-ts turns the spec into TypeScript types in a codegen target
  • dependsOn, implicitDependencies and dependentTasksOutputFiles keep the types ordered, cached and in sync with the spec

None of this is tied to OpenAPI. Whenever a backend build emits a schema and a generator turns it into client code, the same task graph pattern applies, whether that's Protobuf or GraphQL, and regardless of the languages on either side.

Full example

The complete setup lives in juristr/nx-polyglot-java-spring. Clone it, run mise install and pnpm install, then pnpm nx run-many -t typecheck. Rename a field on the Product record, run typecheck again, and watch the storefront stop compiling.

Next up

The same task graph also drives CI. In a follow-up post, I'll show how CI works for this workspace and how to configure it on Nx Cloud CI, including Java on the CI machines, distributing tasks across workers and running the Playwright specs as separately cached tasks.

Learn more