What is cached Nx OpenAPI codegen and who should use it?

Cached Nx OpenAPI codegen means treating generated clients as build outputs, not as hand-maintained source. Each OpenAPI spec or set of .proto files lives in its own project. A generate target on that project runs the generator, declares the spec files as its inputs, and declares the generated directory as its outputs. Consuming apps depend on that project. This lets Nx decide when regeneration is needed, so you no longer rely on a README step or a postinstall script that someone forgets to run.

Why teams use it

  • Fewer stale clients. The generated code is derived from the contract on every build that needs it. A spec change can't silently drift from the client that apps compile against.
  • No redundant regeneration. Nx hashes the declared inputs. If the spec and generator configuration haven't changed, Nx restores the outputs from cache instead of rerunning the generator. With a large spec or a slow toolchain, that saves real time on every build.
  • Correct affected scoping. The contract project sits in the project graph, so nx affected traces a spec change through the client library to every app that imports it. The same mechanism keeps an unrelated change from triggering regeneration.

Who benefits most

This approach suits backend and platform engineers running Nx monorepos with several service contracts and many consuming apps. In that setup, manual regeneration is error-prone and full rebuilds are expensive.

When it fits poorly

It adds little in a small repo with one stable spec that rarely changes. A committed client and an occasional manual regeneration are simpler there. It also doesn't fit teams that don't use Nx for build orchestration, because the caching and affected logic depend on Nx running the tasks.

How does the Nx task graph rebuild generated client libraries only when a contract changes?

Before running a target, Nx computes a hash from everything the task declares as an input: the files matched by its inputs patterns (the OpenAPI or .proto files, generator config, custom templates), the target's command and options, any runtime inputs such as the output of a command that prints the generator version, and any named environment variables. Pinning the generator version and listing it as an input matters because a template change inside a new generator release alters the output even when the spec has not changed. If the hash matches a stored entry in the local cache, or in a remote cache, Nx restores the declared outputs and replays the terminal log without running the generator. On a miss, Nx runs the generator and stores the result under the new hash.

One library per contract

Give each contract its own project, for example libs/contracts/billing. It holds openapi.yaml and the generated client in that library's source folder. Services that call the billing API import from this library, so the project graph contains an edge from each consumer to contracts-billing and nowhere else. When someone edits the billing spec, nx affected marks contracts-billing and its dependents. The inventory and auth clients keep their cached outputs, and so do the services that use them.

Compare this with a single shared-codegen library that holds every spec. Every consumer depends on that one project. An edit to any spec changes the project, so every consumer becomes affected. Every downstream build and test that depends on its inputs then runs again, including services that never call the API that changed.

 ┌───────────────────────────────┐   ┌───────────┐
 │ spec, generator config,       │──▶│ task hash │─hit─▶ restore outputs
 │ templates, version pin, env   │   └─────┬─────┘       + replay log
 └───────────────────────────────┘    miss │
                                           ▼
                     run generator, store outputs under new hash

 ONE LIBRARY PER CONTRACT: edit billing spec
 ┌────────────────────┐ ┌────────────────────┐ ┌────────────────────┐
 │contracts-billing * │ │contracts-inventory │ │contracts-auth      │
 │openapi.yaml+client │ │openapi.yaml+client │ │openapi.yaml+client │
 └─────────┬──────────┘ └─────────┬──────────┘ └─────────┬──────────┘
           ▲                      ▲                      ▲
 ┌─────────┴──────────┐ ┌─────────┴──────────┐ ┌─────────┴──────────┐
 │ billing-svc *      │ │ inventory-svc      │ │ auth-svc           │
 └────────────────────┘ └────────────────────┘ └────────────────────┘

 SINGLE SHARED-CODEGEN LIBRARY: edit any spec
 ┌────────────────────────────────────────────────────────────────────┐
 │ shared-codegen *   billing.yaml   inventory.yaml   auth.yaml       │
 └─────────┬──────────────────────┬──────────────────────┬────────────┘
           ▲                      ▲                      ▲
 ┌─────────┴──────────┐ ┌─────────┴──────────┐ ┌─────────┴──────────┐
 │ billing-svc *      │ │ inventory-svc *    │ │ auth-svc *         │
 └────────────────────┘ └────────────────────┘ └────────────────────┘
 * affected: runs again; unmarked projects restore outputs from cache

Nx hashes each codegen task's declared inputs and restores cached outputs on a hit. With one library per contract, a billing spec edit affects only contracts-billing and its consumers, while a shared codegen library makes every consumer affected.

How do you implement a cacheable 'generate' target with inputs, outputs and dependsOn?

The fix is to give generation its own target, one per contract project, so Nx can hash it, cache it, and skip it when nothing relevant changed.

Step 1: Define the target

Add a generate target to the contract library's project.json. Use the nx:run-commands executor with a command that calls your generator, or point at a package.json script. Either way, the target needs cache: true. You can set this per target or once under targetDefaults in nx.json.

Step 2: Declare what affects the output

In nx.json, define a named input such as contracts that lists three things:

  • The spec files, for example {projectRoot}/**/*.yaml.
  • The generator config file.
  • Any custom template directory.

Templates are often missed. Editing a template changes every generated file even though no spec moved.

Step 3: Pin the generator and hash it

Pin the generator to an exact version in your lockfile or toolchain. Then add it to the hash:

  • If the generator is an npm package, use an externalDependencies input.
  • Otherwise, use a runtime input that prints the tool's version.

Also add an env input for any variable that changes the output. Without these inputs, upgrading the generator silently reuses stale artifacts.

Step 4: Declare outputs exactly

Set outputs to the generated directory, for example {projectRoot}/src/generated. On a cache hit, Nx restores only the declared outputs.

If the path is wrong or missing, you get the classic bug: Nx reports a cache hit, but no files appear and the consumer's compile fails. If the path is too broad, a cache hit can overwrite hand-written source.

Step 5: Wire dependsOn

In each consuming library, add ^generate to dependsOn for build, test, lint and typecheck. You can do this once in targetDefaults. The ^ prefix tells Nx to run generate in the project's dependencies first. As a result, every consumer task sees fresh clients or restored cached ones, never a missing directory.

{
  "namedInputs": {
    "default": ["{projectRoot}/**/*"],
    "contracts": [
      "{projectRoot}/**/*.yaml",
      "{projectRoot}/**/*.proto",
      "{projectRoot}/codegen.config.json",
      "{projectRoot}/templates/**/*",
      { "externalDependencies": ["@openapitools/openapi-generator-cli"] },
      { "runtime": "buf --version" },
      { "env": "CODEGEN_TARGET_LANG" }
    ]
  },
  "targetDefaults": {
    "generate": {
      "cache": true,
      "inputs": ["contracts"],
      "outputs": ["{projectRoot}/src/generated"]
    },
    "build": {
      "dependsOn": ["^generate", "^build"]
    },
    "test": {
      "dependsOn": ["^generate"]
    },
    "lint": {
      "dependsOn": ["^generate"]
    },
    "typecheck": {
      "dependsOn": ["^generate"]
    }
  }
}

An nx.json sketch that caches 'generate' using a 'contracts' named input (specs, config, templates, pinned tool version, env), restores only src/generated, and makes consumers' build, test, lint and typecheck run ^generate first.

How do you handle protobuf generation in Nx with imports and a deterministic toolchain?

Protobuf adds a problem that OpenAPI rarely has: one .proto file can import others, and Nx does not parse those imports. If a service's generate inputs list only its own files, a change to a shared common/money.proto will not change the hash, and Nx will restore stale clients from cache. The inputs must cover the full import closure. You can glob the entire proto root, or you can model shared protos as their own Nx project and pull its files in through a ^-prefixed named input.

Layout Cache granularity Risk
One shared proto root, one generate target Coarse: any edit regenerates everything Low; imports are covered by default
Per-service protos plus a shared-types project Fine: only affected services regenerate Missed imports if the dependency edge is not declared

The toolchain must be part of the cache key as well. A globally installed protoc is invisible to Nx. If two machines have different versions, they produce different output under the same hash, and whichever one populates the remote cache wins. You can pin plugins as workspace dev dependencies and reference them through externalDependencies. You can also pin remote plugin versions in buf.gen.yaml and include buf.lock and that file in the inputs. If protoc must stay a system binary, add a runtime input that runs protoc --version.

Finally, make the output byte-stable. Turn off any plugin option that writes generation timestamps or tool banners. Call protoc with paths relative to the workspace root so absolute paths do not get embedded in the output. Pass input files in sorted order, because file order can affect the ordering of the emitted code.

// libs/orders-client/project.json (Nx accepts comments in project.json)
{
  "name": "orders-client",
  // implicit edge so the ^ input below sees shared-protos' files
  "implicitDependencies": ["shared-protos"],
  "targets": {
    "generate": {
      "executor": "nx:run-commands",
      "cache": true,
      "inputs": [
        // this service's own protos
        "{workspaceRoot}/protos/orders/**/*.proto",
        // transitive imports: the 'protos' named input of dependencies
        // (shared-protos must define namedInputs.protos)
        "^protos",
        // pinned plugin from package.json / lockfile
        { "externalDependencies": ["ts-proto"] },
        // system protoc is invisible to Nx, so hash its version string
        { "runtime": "protoc --version" }
      ],
      "outputs": ["{projectRoot}/src/gen"],
      "options": {
        // run from the workspace root, use relative paths, sort file order
        "cwd": "{workspaceRoot}",
        "command": "find protos/orders -name '*.proto' | LC_ALL=C sort | xargs protoc -I protos --plugin=protoc-gen-ts_proto=./node_modules/.bin/protoc-gen-ts_proto --ts_proto_out=libs/orders-client/src/gen"
      }
    }
  }
}

An Nx generate target that hashes its own protos, the shared protos from a dependency, the pinned ts-proto plugin and the system protoc version, then runs protoc on sorted, workspace-relative paths.

What breaks caching in OpenAPI codegen and when should you avoid it?

The cache key is only as complete as the inputs you declare, and OpenAPI specs rarely live in a single file. If openapi.yaml pulls schemas from components/*.yaml through $ref, every one of those files must match an input glob. Otherwise, editing a shared schema leaves the root file's hash unchanged, Nx restores the old client, and you ship types that no longer match the API.

The generator itself is also an input. Pin its exact version and any custom template directory, and include both in the hash. An npm-installed generator is covered when its lockfile entry is part of the inputs. A Java-based generator installed globally or through a system package manager is a different case. Nx cannot see it, so upgrading it changes the output without changing the hash. Close that gap by vendoring the generator into the workspace, or by adding a runtime input that prints the generator version.

Fetching the spec from a running service's /openapi.json during the build cannot be cached. The content is unknown until the request completes, and the build fails whenever that service is down or not yet deployed. Accept that cost only when you need the live contract, for example in a contract test against a staging environment. Even then, keep it as a separate target from the normal build.

Inputs can fail in two directions. Inputs that are too narrow cause stale hits, which are silent and dangerous. Inputs that are too broad, such as the whole project directory or {workspaceRoot}/**, cause constant misses, so you pay for caching without getting any benefit from it.

// libs/api-client/project.json (Nx parses project.json as JSONC, so comments are allowed)
{
  "name": "api-client",
  "targets": {
    "generate": {
      "executor": "nx:run-commands",
      "cache": true,
      "inputs": [
        // Root spec plus every file it reaches through $ref; omit one and edits produce stale hits
        "{projectRoot}/spec/openapi.yaml",
        "{projectRoot}/spec/components/**/*.yaml",
        // Custom templates shape the output, so they belong in the key
        "{projectRoot}/templates/**/*",
        // The Java generator is installed outside the workspace, so hash the version it reports
        { "runtime": "openapi-generator version" }
        // Deliberately NOT "{workspaceRoot}/**": unrelated changes would cause constant misses
      ],
      "outputs": ["{projectRoot}/src/generated"],
      "options": {
        "cwd": "libs/api-client",
        "command": "openapi-generator generate -i spec/openapi.yaml -g typescript-fetch -t templates -o src/generated"
      }
    },
    "contract-check": {
      // Fetches the live spec from staging; the result is unknown until the request runs, so never cache it
      "executor": "nx:run-commands",
      "cache": false,
      "options": {
        "cwd": "libs/api-client",
        "command": "curl -fsS  -o tmp/live-openapi.json && node scripts/compare-spec.mjs spec/openapi.yaml tmp/live-openapi.json"
      }
    }
  }
}

A project.json that declares every $ref'd spec file, the custom templates, and an externally installed generator's version as cache inputs. The live-spec contract check sits in its own uncached target so the normal build never depends on a running service.

Should you commit generated code or gitignore it?

Where the output lives determines what reviewers see and what a fresh clone needs before the IDE resolves imports.

Approach API change visible in review Fresh clone types resolve Diff noise and conflicts CI requirement
Commit generated output Yes, as a client diff Immediately High: regenerated files conflict when two branches touch the spec Drift check: regenerate, fail on any uncommitted difference
Gitignore, rely on Nx cache Only through the spec diff After the first generate run None Correct inputs and outputs, since the cache is the only source of output
Hybrid (commit a small typed surface, ignore the rest) Partial Partially Moderate Drift check on the committed part

Committing output lets reviewers see a renamed field turn into a broken method signature, which a YAML diff hides. It costs noisy pull requests and merge conflicts in files nobody should hand-edit. Resolve those conflicts by regenerating, not by merging lines. Without a drift check, someone eventually edits generated code or forgets to regenerate, and the committed client stops matching the spec.

Gitignoring keeps history clean. The trade-off is that contributors need a bootstrap step. Make dependsOn handle it so serve, test and build trigger generation automatically. A manual pre-step script does the same job without caching or dependency awareness, so it gets skipped.

When consumers sit outside the monorepo, publish a versioned client package per service. Versioning then replaces the drift check.

How do you verify the cache and run it safely in CI with a remote cache?

Verifying the cache locally

Run the generate target twice without changes. The second run should report a local cache hit and finish in roughly the time it takes to restore files. Then make a trivial edit to the spec, such as a description field. The next run should miss, which proves the spec is a declared input. Delete the output directory and run again. A hit that recreates the files confirms outputs is correct. If files don't reappear, Nx cached the terminal output but not the artifacts.

When a run misses unexpectedly, compare what went into the task hash across the two runs. The usual causes are an undeclared environment variable, a timestamp written into a generated header, or a broad input glob that picks up unrelated files. --skip-nx-cache forces a real run when you need a clean baseline.

Running it in CI

Point CI at a shared remote cache so that a contract generated on one branch is restored everywhere else instead of being rebuilt. Restrict who can write to it. Pipelines on the main branch and on trusted release branches get read-write credentials. Pull requests, especially from forks, get read-only access. Without that split, an untrusted branch could upload a tampered client under a hash that trusted builds later restore.

Illustrative estimate (assumed inputs): 12 contracts, 90 seconds of generation each, 40 CI runs per day, and contracts changing in 10% of runs. Generation drops from 18 minutes to under 2 minutes per run, which saves about 10 CI hours per day. The cost is about two engineer-days of setup and 12 extra projects to maintain.

Impact on development cost

The CI-hours figure is the easiest saving to measure, but it is often not the largest. Local regeneration happens more often than CI runs and puts an engineer in a wait loop. A slow generate step also pushes people to skip regeneration and work against stale clients, which leads to failures later. A cache hit removes that wait and makes regeneration cheap enough that nobody skips it.

Illustrative estimate (assumed numbers, not a benchmark)

Assumed inputs:

  • 40 engineers, each triggering client generation 6 times per working day
  • Uncached local generation: 3 minutes. Restored from cache: 10 seconds (≈0.17 min)
  • Cache hit rate: 85%
  • Loaded engineering cost: $100/hour

Formula:

hours saved per day = engineers × runs × hit rate × (uncached min − cached min) ÷ 60

40 × 6 × 0.85 × (3 − 0.17) ÷ 60 ≈ 9.6 engineer-hours/day, or about $960/day at the assumed rate.

Some of that waiting would have overlapped with other work, so discount it by your own judgment. Even a 50% discount usually recovers the setup effort within days.

Offsetting costs to include:

  • Remote cache storage and transfer. Generated clients are small compared with build outputs, but frequent contract churn adds up.
  • Cold-cache events. Bumping a pinned generator or protoc version invalidates every entry at once. Schedule these bumps rather than letting them land at random.
  • Maintenance time. Budget time to review inputs whenever the toolchain or file layout changes. A stale input list costs far more than the cache saves, because it produces a correct-looking but wrong client.

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 openapi codegen, 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.