What does it mean to cache generated code in Nx?

Caching generated code in Nx means treating codegen as its own target, usually named generate, rather than as a hidden first step inside each consumer's build. The target's cache key covers exactly three things: the schema files (.proto or OpenAPI specs), the generator configuration and templates, and the pinned toolchain version. Its declared outputs are exactly the generated directory. When the key matches a previous run, Nx restores that directory from the local or remote cache instead of running the generator.

 inputs (hashed)                       consumers
 ---------------                       ---------
 *.proto / openapi.yaml ─┐           ┌─> build
 generator config        ├─> generate ├─> test
 templates               │   target   └─> lint
 toolchain version ──────┘      │
                                v
                      outputs: generated dir
                    (restored from local/remote
                       cache on a hash match)

Each part of this design addresses a specific failure:

  • Precise inputs give correct hits. An unrelated file change does not trigger regeneration.
  • Including the toolchain gives correct invalidation. A generator upgrade cannot leave stale output in the cache.
  • A single target removes duplicate work. Codegen runs once per task graph instead of once per consumer.
  • Uncommitted output becomes practical. Because restoring from cache is cheap, many teams stop committing generated code.

This pattern is for backend and platform engineers running Nx monorepos that generate protobuf or OpenAPI clients and servers. It pays off when several projects consume the same generated code, when the generator is slow to start or run, or when CI logs show regeneration taking a noticeable share of build time.

+---------------------- schema project -----------------------+
|  schema files: *.proto, openapi.yaml                        |
|  generator config + templates                               |
|  pinned toolchain version                                   |
+------------------------------+------------------------------+
                               | inputs (hashed)
                               v
+---------------------- generate target ----------------------+
|  hash match -> restore outputs from local/remote cache      |
|  no match -> run generator, then store outputs in cache     |
+--------+---------------------+------------------------------+
         ^                     |
         |  restore/store      v  outputs
+------------------+  +-----------------+
| local cache      |  | generated dir   |
| remote cache     |  | (outputs only)  |
+------------------+  +--------+--------+
                               | consumers depend on generate
            +------------------+------------------+
            |                  |                  |
            v                  v                  v
        +-------+          +-------+          +-------+
        | build |          | test  |          | lint  |
        +-------+          +-------+          +-------+

Schema files, generator config and templates, and the pinned toolchain version form the generate target's hash; on a match Nx restores the generated directory from the local or remote cache, and build, test and lint consume that single output.

How do you set up a generate target with dependsOn?

Start by giving codegen its own target instead of folding it into build. In the protobuf project's project.json, add a generate target that uses the nx:run-commands executor to invoke buf generate or protoc with your plugins. In the OpenAPI client project, add a matching generate target that runs your OpenAPI generator against the spec. Mark both targets cacheable. Depending on your Nx version, you set this per target with "cache": true or through targetDefaults in nx.json. Config keys have moved between releases, so check the docs for the version you have installed.

Have the first step of each command delete the output directory, then regenerate into it. Generators write files but rarely remove them. Without the delete, a message dropped from a .proto file or an endpoint removed from the spec leaves a stale file behind. That file still compiles and still gets captured in cached outputs.

Next, wire the consumers. On build, test and lint, set dependsOn to include generate for the project's own codegen and ^generate for codegen in the projects it depends on. Lint needs this too: type-aware rules fail or give wrong results against missing types.

Why not just run the generator inside each consumer's build script? In that setup, five services importing the same client run the same generation five times. Nx also sees only one opaque build step, so it can't cache, skip or report the codegen separately. Any change to a consumer's source reruns the generator, even when the spec hasn't changed.

{
  "name": "payments-proto",
  "$schema": "../../node_modules/nx/schemas/project-schema.json",
  "sourceRoot": "libs/payments-proto/src",
  "targets": {
    "generate": {
      "executor": "nx:run-commands",
      "cache": true,
      "inputs": [
        "{projectRoot}/proto/**/*.proto",
        "{projectRoot}/buf.yaml",
        "{projectRoot}/buf.gen.yaml"
      ],
      "outputs": ["{projectRoot}/src/generated"],
      "options": {
        "cwd": "libs/payments-proto",
        "command": "rm -rf src/generated && buf generate --template buf.gen.yaml"
      }
    },
    "build": {
      "executor": "nx:run-commands",
      "dependsOn": ["generate", "^generate"],
      "options": { "cwd": "libs/payments-proto", "command": "tsc -p tsconfig.lib.json" }
    },
    "test": {
      "executor": "nx:run-commands",
      "dependsOn": ["generate", "^generate"],
      "options": { "cwd": "libs/payments-proto", "command": "jest" }
    },
    "lint": {
      "executor": "nx:run-commands",
      "dependsOn": ["generate", "^generate"],
      "options": { "cwd": "libs/payments-proto", "command": "eslint src" }
    }
  }
}

A project.json with a cacheable generate target that wipes src/generated before running buf generate. Build, test and lint depend on their own generate and on upstream projects' generate via ^generate. Check your Nx version's docs for exact keys.

How should you declare Nx inputs and outputs for codegen?

Start from the files that actually determine the generator's output. The common default named input, {projectRoot}/**/*, hashes everything in the project: READMEs, tests, and unrelated source. Each edit to any of those is a cache miss and a needless regeneration. If the generated directory lives inside the project root, it is hashed too. Running the generator then changes the input hash for the next run, so the target never stays cached.

Scope inputs to the generator's real dependencies, and exclude the output directory explicitly with a negated pattern such as !{projectRoot}/src/generated/**.

Input category Example pattern What goes wrong if omitted
Schema files {projectRoot}/proto/**/*.proto Schema edits don't regenerate code
OpenAPI spec {projectRoot}/openapi.yaml New endpoints missing from the client
buf configuration {projectRoot}/buf.yaml, {projectRoot}/buf.gen.yaml Plugin or option changes ignored
Generator config {projectRoot}/openapitools.json Changed generator options not applied
Custom templates {projectRoot}/templates/** Template fixes never reach output

Declare outputs as exactly the generated directory, for example {projectRoot}/src/generated. Nx restores only declared outputs on a cache hit. Anything the generator writes elsewhere is silently absent after a restore. Keep outputs disjoint between targets. If two targets claim the same path, each restore overwrites the other's files, and the result depends on which target ran last.

The asymmetry matters most. An input set that is too broad costs extra runs. One that is too narrow, such as a forgotten template or an imported .proto outside the glob, produces stale generated code with no error. When unsure, include the file.

{
  "name": "api-client",
  "namedInputs": {
    "protoSources": [
      "{projectRoot}/proto/**/*.proto",
      "{workspaceRoot}/libs/shared-protos/**/*.proto",
      "{projectRoot}/buf.yaml",
      "{projectRoot}/buf.gen.yaml",
      "!{projectRoot}/src/generated/**"
    ],
    "openapiSources": [
      "{projectRoot}/openapi.yaml",
      "{projectRoot}/openapitools.json",
      "{projectRoot}/templates/**",
      "!{projectRoot}/src/generated/**"
    ]
  },
  "targets": {
    "generate-proto": {
      "executor": "nx:run-commands",
      "cache": true,
      "inputs": ["protoSources"],
      "outputs": ["{projectRoot}/src/generated/proto"],
      "options": { "command": "buf generate", "cwd": "libs/api-client" }
    },
    "generate-openapi": {
      "executor": "nx:run-commands",
      "cache": true,
      "inputs": ["openapiSources"],
      "outputs": ["{projectRoot}/src/generated/openapi"],
      "options": {
        "command": "openapi-generator-cli generate -i openapi.yaml -g typescript-fetch -t templates -o src/generated/openapi",
        "cwd": "libs/api-client"
      }
    }
  }
}

A project.json that defines narrow named inputs for each generator. It includes imported shared protos and custom templates and excludes the generated directory. Each target declares its own output directory so the two targets' outputs do not overlap.

How do you make toolchain upgrades invalidate the cache?

The schema hash is only half the cache key. If you upgrade protoc, a plugin such as protoc-gen-go, or the OpenAPI generator and leave the .proto files and specs unchanged, Nx computes the same hash and restores output produced by the old tool. Nothing fails. The generated code is out of date, and you find out later from a diff, a changed method signature, or a runtime mismatch.

The fix is to make the tool version part of the hash. For a binary installed on the system, add a runtime input such as { "runtime": "protoc --version" }. Nx runs the command and hashes what it prints. Add one entry for each plugin that reports its version. If the generator runs in Docker, hash the image ID with docker image inspect --format '{{.Id}}' <image> instead of the tag, because a tag can be moved to a different image.

If the generator comes from npm, use { "externalDependencies": ["@openapitools/openapi-generator-cli"] }. Nx then reads the resolved version from the lockfile and does not need to spawn a process. That wrapper downloads a separate JAR, and the JAR version is set in openapitools.json, so also add that file as an input.

Nx cannot see tools installed outside the package manager. It only accounts for what you list. Every runtime input also starts a process each time the hash is computed, which adds up across many projects.

Pin every version in the repository, through the lockfile, a version file, or a digest-pinned image. Then every developer machine and CI agent computes the same key, and a version upgrade shows up as a reviewed commit.

{
  "name": "api-contracts",
  "targets": {
    "generate-proto": {
      "command": "protoc --go_out=generated/go --proto_path=proto proto/*.proto",
      "cache": true,
      "inputs": [
        "{projectRoot}/proto/**/*.proto",
        { "runtime": "protoc --version" },
        { "runtime": "protoc-gen-go --version" }
      ],
      "outputs": ["{projectRoot}/generated/go"]
    },
    "generate-proto-docker": {
      "command": "docker run --rm -v \"$PWD\":/work -w /work registry.example.com/codegen/protoc:1.4.0 make gen",
      "cache": true,
      "inputs": [
        "{projectRoot}/proto/**/*.proto",
        { "runtime": "docker image inspect --format '{{.Id}}' registry.example.com/codegen/protoc:1.4.0" }
      ],
      "outputs": ["{projectRoot}/generated/go"]
    },
    "generate-openapi": {
      "command": "openapi-generator-cli generate -i openapi/api.yaml -g typescript-fetch -o generated/ts",
      "cache": true,
      "inputs": [
        "{projectRoot}/openapi/**/*.yaml",
        { "externalDependencies": ["@openapitools/openapi-generator-cli"] },
        "{workspaceRoot}/openapitools.json"
      ],
      "outputs": ["{projectRoot}/generated/ts"]
    }
  }
}

A project.json that adds tool versions to the cache key: runtime inputs for system protoc and its plugin, a Docker image ID, and externalDependencies plus openapitools.json for the npm-installed OpenAPI generator.

How do you handle shared .proto files and specs across projects?

A shared schema works best as its own Nx project, for example libs/proto-common or libs/api-specs. It holds only .proto files or OpenAPI documents and defines a named input such as schema that matches them. Each consumer project then does two things. It declares a dependency on the schema project. Because Nx cannot infer that dependency from a .proto import, add it through implicitDependencies. The consumer also includes ^schema in its generate target's inputs. The caret tells Nx to hash the matching files of every dependency, so editing common/money.proto changes the cache key of each generator that consumes it. Projects outside that dependency chain keep their hits. If the schema project has its own step, such as linting or bundling a multi-file OpenAPI spec, add dependsOn: ["^generate"] so that step runs first.

Granularity decides how much an edit invalidates. A single schemas project holding every proto is simple to set up, but any edit, even a comment in an unrelated service definition, forces every consumer to regenerate. Splitting by proto package or by service raises hit rates because each consumer depends only on what it imports. The cost is more projects in the graph, more project.json files to maintain, and dependency edges that someone has to keep in sync with the actual imports.

Output size also argues for splitting. A cache hit is not free when the generated tree is large: restoring tens of thousands of files costs disk I/O, remote cache transfer, and storage. Several smaller generate targets, each with narrow outputs, mean a schema change restores or rewrites only the affected slice, not the whole tree.

When should you avoid caching generated code, and what are the alternatives?

Caching assumes identical inputs always produce identical bytes. Some generators break that by stamping a timestamp or tool version into file headers, embedding absolute paths from the build machine, or emitting map-backed fields in hash-iteration order. Fix these before you cache. Strip or disable generated headers, use stable ordering where the generator supports it, and pin generator and plugin versions. If you cannot fingerprint the toolchain reliably, the hash cannot distinguish two different toolchains. A protoc plugin installed globally on each laptop is a common example.

Skip caching when the generator finishes faster than Nx can hash its inputs and restore its outputs. A remote cache that any machine can write to needs the most care. One laptop with a misconfigured input set or a different local plugin can publish a wrong artifact, and every other machine then restores it as a cache hit. Restrict writes to CI so artifacts come from one controlled toolchain.

Approach IDEs Code review Fresh clones CI time
Commit generated code, CI drift check Works immediately Noisy diffs; generated changes are visible Ready without tooling Regeneration runs on every pipeline
Regenerate every build, no cache Broken until first build Schema diffs only Requires toolchain Full generation cost every run
Generate inside each consumer's build Per-consumer setup needed Schema diffs only Requires toolchain Duplicated work across consumers
Cached generate target Broken until first run Schema diffs only Fast if the remote cache hits Cost paid once per input change

If generated code is not committed, gitignore the output directory. If it is committed, regenerate it in CI and fail the job when the working tree shows a diff.

How do you verify the cache and estimate the time it saves?

Verification routine

Run these four checks against one codegen target, in this order. Together they show that the cache key covers what it should.

  1. Repeat run. Run the generate target twice with no changes. The second run should report a cache hit. If it doesn't, something non-deterministic is in the inputs, such as a timestamp in a generated header or an unpinned tool.
  2. Comment edit. Change a comment in one .proto or OpenAPI file. Expect a cache miss. Nx hashes file contents, not parsed semantics, so this confirms the schema files are actually in the inputs.
  3. Deleted output. Delete the output directory and rerun. Expect a hit that restores the files. If the directory stays empty, your outputs path doesn't match where the generator writes.
  4. Generator bump. Change the generator or plugin version. Expect a miss. A hit here means the toolchain input from section 4 isn't wired in.

If a miss surprises you, check whether your installed Nx version can show the hash inputs for a task. Confirm how it works in that version's documentation, then compare the hash inputs from two runs to find the input that changed.

Is it worth it?

Illustrative estimate (assumed numbers, not a benchmark):

Saved minutes per day = G × R × H

  • G = generation time per run
  • R = CI runs per day
  • H = share of runs with no schema change

Assume G = 3 minutes, R = 40 runs, and H = 0.8. That gives 3 × 40 × 0.8 = 96 CI minutes per day.

Weigh that against the initial setup time and the ongoing upkeep: keeping input globs in sync as schemas move, and debugging stale-output reports. If G is under a few seconds, or most commits touch schemas, the savings shrink and the configuration may cost more than it saves.

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 cache generated code, 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.