What is Nx protobuf code generation with a shared proto library?

Nx protobuf code generation with a shared proto library means one Nx project, conventionally libs/proto, owns the contract. It holds buf.yaml and every .proto file. Each service's generated gRPC code lives in a separate project that depends on it. Services never read .proto files directly. They consume the generated output.

A typical layout looks like this:

  • libs/proto/ contains buf.yaml and directories such as billing/v1/ and orders/v1/, with .proto files declaring package billing.v1; and package orders.v1;.
  • libs/proto-gen/billing-client/, libs/proto-gen/orders-server/ and similar projects each hold the generated stubs for one consumer and declare an implicit dependency on libs/proto.
  • apps/orders-service/ imports orders-server and billing-client, and nothing else from the proto tree.

Dependencies flow in one direction: contract, then generated code, then service. Nx's project graph reflects this chain. When a .proto file changes, only the generation targets and services downstream of it are marked affected.

Package names should match directory paths: billing.v1 lives in billing/v1/. There are three reasons:

  • Lint. Buf's lint rules check this mapping (PACKAGE_DIRECTORY_MATCH) and require a version suffix (PACKAGE_VERSION_SUFFIX). Following the convention keeps lint passing without exceptions.
  • Imports. Import paths become predictable. import "billing/v1/invoice.proto" tells you the package without opening the file.
  • Path filtering. Generation targets can select a directory such as billing/v1 and be confident they get exactly one package and version, with nothing from other packages mixed in.
# libs/proto/buf.yaml
# The only buf.yaml in the repo. libs/proto owns the contract;
# generated-code projects read from here and never copy .proto files.
#
# Expected layout under libs/proto/:
#   billing/v1/invoice.proto   -> package billing.v1;
#   orders/v1/order.proto      -> package orders.v1;
version: v2

modules:
  # The module root is this directory, so the import path
  # "billing/v1/invoice.proto" resolves to billing/v1/ under libs/proto.
  - path: .

lint:
  use:
    # STANDARD includes PACKAGE_DIRECTORY_MATCH (billing.v1 must live in
    # billing/v1/) and PACKAGE_VERSION_SUFFIX (packages end in .v1, .v2, ...).
    # Following these rules keeps --path billing/v1 mapped to exactly one
    # package and version.
    - STANDARD

breaking:
  use:
    # Check compatibility per file, so generated clients in
    # libs/proto-gen/* stay compatible across releases.
    - FILE

The buf.yaml at the root of libs/proto declares the module and turns on Buf's STANDARD lint rules, which require package names such as billing.v1 to match their directory paths and to end with a version suffix.

Why use this pattern, and who should use it in a gRPC monorepo?

The main benefit is that one project owns the contract. The proto library has its own lint and breaking-change targets and its own reviewers, so a change to billing/v1 is reviewed once, in one place. It does not get copied into several service repos where each copy drifts.

Generation also runs only where it is needed. Each service's client project declares the proto library as a dependency, and its generate target lists only the proto paths it reads as inputs. When those files are unchanged, Nx restores the generated output from cache instead of running buf generate again.

nx affected uses the same project graph to scope CI. Keep in mind that it works at project granularity. If all protos live in one project, any proto edit marks every consumer as affected. Splitting the library into one project per package keeps the affected set small. If you keep a single project, narrowed target inputs still let the cache absorb most of the redundant work.

The graph also records who consumes which API. You can inspect and enforce those dependencies directly, so you don't depend on naming conventions or reviewers remembering them.

This setup fits these teams:

  • Platform teams running several services that share contracts in one repo.
  • Polyglot backends that generate Go, TypeScript, or Python clients from the same definitions.
  • Teams already on Nx, which can add these targets without adopting a second build tool.

Illustrative estimate (assumed inputs, not measured):

  • 12 services.
  • 4 minutes to regenerate, build, and test each one.
  • A proto change that touches one package consumed by 3 services.

A full rebuild costs about 48 CI minutes. Scoped to the affected projects, it is roughly 12 minutes for the 3 consumers plus a minute or two for lint and breaking checks.

How do you enforce the contract with buf lint and buf breaking as Nx targets?

Give the proto library two targets, lint and breaking, and make the generation target depend on both. A contract violation then stops the pipeline before any service sees new client code. Without that ordering, a bad change can regenerate clients, compile, and only fail later in an integration test, or not fail at all.

The lint target runs buf lint against the module. It is a pure function of its files, so declare its inputs precisely: every .proto file in the project plus buf.yaml and, if you use dependencies, buf.lock. Leave out unrelated files such as READMEs. Otherwise a docs edit invalidates the cache and reruns lint for nothing.

The breaking target runs buf breaking with --against pointed at the main branch of the repository. The git input format .git#branch=main is the common choice. Two details matter in CI:

  • Fetch history. Shallow clones often lack the main ref, so fetch it before the target runs.
  • Don't cache it. Its result depends on what is currently on main, which isn't part of the target's inputs. A cached pass can go stale after someone else merges a proto change, so mark the target non-cacheable. It runs quickly, so caching saves little.

Know the limit. buf breaking enforces only the rule set you configure (wire, wire JSON, or file-level source compatibility). It cannot tell when a field keeps its number and type but changes meaning, such as timeout switching from seconds to milliseconds. That change passes every check. Require a human reviewer on the proto project for exactly this reason.

{
  "name": "protos",
  "$schema": "../../node_modules/nx/schemas/project-schema.json",
  "projectType": "library",
  "sourceRoot": "libs/protos",
  "targets": {
    "lint": {
      "executor": "nx:run-commands",
      "cache": true,
      "inputs": [
        "{projectRoot}/**/*.proto",
        "{projectRoot}/buf.yaml",
        "{projectRoot}/buf.lock"
      ],
      "options": {
        "command": "buf lint libs/protos"
      }
    },
    "breaking": {
      "executor": "nx:run-commands",
      "cache": false,
      "options": {
        "command": "buf breaking libs/protos --against '.git#branch=main,subdir=libs/protos'"
      }
    },
    "generate": {
      "executor": "nx:run-commands",
      "dependsOn": ["lint", "breaking"],
      "options": {
        "command": "buf generate libs/protos --template libs/protos/buf.gen.yaml"
      }
    }
  }
}

A project.json for the proto library: lint is cached on only .proto and buf config inputs, breaking is non-cacheable because it compares against main (fetch main first in CI), and generate depends on both.

How do you generate a gRPC client per service with buf generate and Nx caching?

Give each consuming project its own buf.gen.yaml and restrict the input to the proto packages that service actually calls. Use the --path flag or the paths list on the template's input. If orders only talks to billing.v1, it should not get generated stubs for every package in the repo. Path filtering keeps the generated surface small and makes the dependency visible in one file.

Wrap generation in an nx:run-commands target and declare both sides of the cache key. Outputs are the generated directory. Inputs need more care:

  • the .proto files under the consumed packages
  • every package they import
  • the service's buf.gen.yaml
  • the shared buf.yaml
  • the plugin versions

Pin plugins in one of two ways. You can use remote plugins with an explicit version in the template. Or you can use local binaries whose version you feed to Nx as a runtime input, for example the output of protoc-gen-go --version. Then make the build order explicit with implicitDependencies on the proto project, or dependsOn pointing at its lint target.

For multiple languages, use one template and one output project per language. A TypeScript client lands in a web-facing library, and a Go server lands under the Go service. Each project caches independently, so a change to TypeScript plugin options does not invalidate the Go build.

The failure mode is quiet. If you leave an input out, Nx replays a cache hit, and the generated code still compiles while lagging the contract. Nx does not parse proto import statements, so it cannot infer edges between proto packages on its own. You have to maintain those edges by hand or write a custom project-graph plugin that reads the imports.

{
  "name": "orders-client",
  "projectType": "library",
  "implicitDependencies": ["proto"],
  "targets": {
    "generate": {
      "executor": "nx:run-commands",
      "options": {
        "command": "buf generate --template libs/orders-client/buf.gen.yaml --path proto/billing/v1"
      },
      "dependsOn": [{ "projects": ["proto"], "target": "lint" }],
      "inputs": [
        "{workspaceRoot}/proto/billing/v1/**/*.proto",
        "{workspaceRoot}/proto/common/v1/**/*.proto",
        "{projectRoot}/buf.gen.yaml",
        "{workspaceRoot}/buf.yaml",
        { "runtime": "buf --version" }
      ],
      "outputs": ["{projectRoot}/src/gen"],
      "cache": true
    }
  }
}

An Nx project.json generate target that filters buf generate to billing.v1, declares its imported common.v1 protos, buf configs and tool version as cache inputs, and orders the build after the proto project.

How do you stop services from importing each other's generated clients?

Tags turn ownership into something lint can check. Give every project two dimensions in its project.json: a type tag (type:proto, type:client, type:service) and a scope tag naming the owning domain (scope:billing, scope:orders). The Billing proto library, Billing's generated client library and the Billing service all carry scope:billing. They differ only in type.

Constraints that encode the rules

The @nx/enforce-module-boundaries ESLint rule reads these tags through depConstraints. Three constraints cover most of the policy:

  • Services consume clients, not other services. type:service may depend only on type:client and shared utility types. Services may never depend on type:service or type:proto. Importing raw proto packages would bypass the client library, which is the only supported surface.
  • Clients are leaves. type:client may depend only on runtime or shared libraries. Generated code should never pull in a service's internals.
  • Each scope lists the clients it may use. If Orders is allowed to call Billing and nothing else, give scope:orders an onlyDependOnLibsWithTags list of scope:orders and scope:shared, and add a tag such as client-of:orders to the Billing client. The allow-list then lives in one reviewable file, so adding a new caller becomes a visible change rather than a quiet import.

Where the rule stops

The rule checks import statements in files that ESLint lints. It has no visibility into services written in Go or Python. For those languages, run a small script in CI that walks the Nx project graph and checks each edge against the same tag rules. That way one policy applies to every language and violations fail the build.

// eslint.config.mjs (workspace root)
import nx from '@nx/eslint-plugin';

export default [
  ...nx.configs['flat/base'],
  ...nx.configs['flat/typescript'],
  {
    files: ['**/*.ts', '**/*.js'],
    rules: {
      '@nx/enforce-module-boundaries': [
        'error',
        {
          depConstraints: [
            // Services call generated clients only, never other services or raw protos
            { sourceTag: 'type:service', onlyDependOnLibsWithTags: ['type:client', 'type:util'] },
            // Generated clients are leaves: runtime/shared helpers only
            { sourceTag: 'type:client', onlyDependOnLibsWithTags: ['type:util'] },
            // Proto libraries may only import other protos (e.g. common types)
            { sourceTag: 'type:proto', onlyDependOnLibsWithTags: ['type:proto'] },
            { sourceTag: 'type:util', onlyDependOnLibsWithTags: ['type:util'] },

            // Per-scope allow-list: Orders may use its own libs, shared libs,
            // and any client tagged client-of:orders (here, the Billing client)
            {
              sourceTag: 'scope:orders',
              onlyDependOnLibsWithTags: ['scope:orders', 'scope:shared', 'client-of:orders'],
            },
            { sourceTag: 'scope:billing', onlyDependOnLibsWithTags: ['scope:billing', 'scope:shared'] },
            { sourceTag: 'scope:shared', onlyDependOnLibsWithTags: ['scope:shared'] },
          ],
        },
      ],
    },
  },
];

// Matching tags in libs/billing/client/project.json:
//   "tags": ["scope:billing", "type:client", "client-of:orders"]

A flat ESLint config where @nx/enforce-module-boundaries uses type and scope tags so Orders can import only the Billing client it is explicitly allowed to call, and any other cross-service import fails lint.

Should you commit generated code or generate it at build time?

Generating at build time keeps the repository smaller. Committing the output removes a setup step. The table compares the two.

Concern Commit generated code Generate at build time
Nx caching Little to cache; the code is already in the repository The generate target is cached on proto files and buf.gen.yaml, so it reruns only when those change
Review diffs Every proto change brings large generated diffs Reviewers see only the .proto change
Merge conflicts Common in generated files, which are resolved by regenerating Rare, because generated files are not tracked
Editor autocompletion Works right after cloning Needs a generate run before imports resolve
Toolchain on machines Only needed by people who edit protos Needed on every developer machine and CI runner
Reproducibility Drifts if someone generates with a different plugin version Deterministic if plugin versions are pinned

Generating at build time is usually the better default, but only if the plugins are pinned. That leads to the plugin choice:

  • Remote plugins avoid local installs. The cost is a network dependency and an external service in your build path, so an outage or rate limit can block CI.
  • Local pinned plugins keep builds offline and fully under your control. In exchange, you have to pin, distribute and upgrade the binaries for every OS and architecture your team uses.

Templates involve a similar trade-off:

  • Per-service buf.gen.yaml files generate only the stubs each service uses. Over time, their options and versions drift apart.
  • A shared template is one file to maintain, but every service receives clients it never calls.

Over time, each choice costs something different:

  • Committed code costs reviewer attention on every proto change.
  • Build-time generation costs onboarding time and plugin upkeep.
  • Per-service templates cost periodic audits to catch drift.

When should you avoid this setup, and what are the alternatives?

The pattern assumes the protos and their consumers live in the same workspace. When that stops being true, it adds work without solving the hard part.

Protos consumed outside the repo. If partner teams, mobile apps or other repositories depend on your contracts, they cannot rely on Nx targets they don't run. You will need a publishing step for versioned packages, or a schema registry, regardless of what happens inside the monorepo. At that point the published artifact is the real contract, and the in-repo generation largely duplicates it.

Very small repos. With two or three services, a single generate step that runs on any proto change finishes quickly. The project graph, tags and per-service templates cost more to maintain than they save.

One unscoped proto library. If every .proto file sits in one project, editing any message marks every consumer as affected. nx affected then rebuilds and retests almost everything, which removes the main reason to adopt the setup. Splitting protos into per-domain packages fixes this, but it takes ongoing discipline.

Alternative Fits when Main cost
Single global generation target Small repo, few services Every proto change invalidates all generated code
Separate proto repo with published packages Consumers span repos or languages Version bumps and release coordination
Schema registry Many external consumers, compatibility checks needed centrally Extra infrastructure to run and govern
Running protoc directly Minimal tooling, one language Manual plugin management, no built-in lint or breaking checks

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 protobuf code generation, 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.