What is an Nx Go monorepo, and how does Nx work alongside Go's own tooling?

An Nx Go monorepo is a workspace where Nx schedules and caches tasks for Go projects, often next to TypeScript, Python or other code. Nx does not compile Go. It decides which tasks need to run and whether their results already exist. The Go toolchain still does the compiling, linking and testing.

nx affected -t build test
        │
        ▼
  project graph ──── which projects changed, and what depends on them
        │
        ▼
  Nx task cache ──── hash of declared inputs: hit → replay outputs and logs
        │ miss
        ▼
  go build / go test
        │
        ├──► GOCACHE     (compiled packages, cached test results)
        └──► GOMODCACHE  (downloaded module sources)

There are two cache layers, and they work at different levels of granularity.

The Nx task cache is keyed on whatever you declare as a target's inputs, such as source files, go.mod, go.sum, environment variables and dependent projects. On a hit, Nx replays the stored terminal output and restores the declared outputs without starting go at all. Because the key is computed from files and configuration, you can share this cache across machines. It is only correct if the declared inputs are complete.

Go's build cache lives in the directory reported by go env GOCACHE. It stores compiled packages and successful test results at the package level. When Nx does run a task, Go rebuilds only the packages whose inputs changed. Dependencies are read from GOMODCACHE instead of being downloaded again.

The two layers complement each other. Nx skips entire tasks when nothing relevant changed. When something did change, Go keeps the rebuild small.

go env GOCACHE GOMODCACHE

nx affected -t build test

nx affected -t build test

nx affected -t test --skip-nx-cache

go test -count=1 ./...

go clean -cache
go build ./...

A shell session that exercises each cache layer separately: the Nx task cache skips whole tasks, while GOCACHE and GOMODCACHE keep the Go builds Nx does run small.

How does it work? The lifecycle of a Go task under Nx

When you run a command such as nx affected -t build test or nx run api:build, Nx goes through the same sequence of steps for every Go target:

  1. Build the project graph. Nx reads each project.json, plus any projects and targets an installed plugin infers, and records the dependencies between projects. Dependencies come from plugin inference (for Go, usually import paths or require lines), from implicitDependencies and from dependsOn declarations.
  2. Select projects. For nx affected, Nx compares the changed files against a base commit, maps each file to its owning project, and adds every project that depends on it. For nx run-many or nx run, you name the projects directly.
  3. Order the tasks. dependsOn turns targets into a task graph. For example, a generate task in a schema project must finish before the Go service's build starts. Independent tasks can run in parallel.
  4. Compute a hash per task. The hash covers the target's declared inputs: matching files, env and runtime inputs, the target's options (including the command string), and the relevant hashes of the projects it depends on.
  5. Check the cache. Nx looks the hash up in the local cache, and in a remote cache if one is configured. On a hit, it restores the declared outputs and replays the stored terminal output and exit code.
  6. Run on a miss. Nx runs the command, which for Go is plain go build, go test, go vet or your linter. Go then uses GOCACHE and GOMODCACHE as it would outside Nx.
  7. Store the result. Cacheable tasks have their outputs and logs saved under the hash so the next identical run can skip them.

Go needs nothing special for this. The Go toolchain doesn't know Nx is there, so you can still run go build ./... or go test ./... directly in any module. Nx only decides when and whether those commands run.

Who should use an Nx Go monorepo?

The setup fits a few specific situations:

  • Polyglot product teams whose Go services sit next to TypeScript frontends, Node.js tooling or generated clients. A change to a shared API schema can affect a Go server and a TypeScript client together. One command and one graph cover both.
  • Teams already using Nx for JavaScript or TypeScript who are adding Go services. They already have the Node.js toolchain, CI integration and knowledge of how Nx targets work, so adding Go costs less.
  • Platform or developer-experience engineers responsible for CI duration in a repository with many Go services. For them, affected-only runs and a shared task cache are levers they can tune and measure.
  • Repositories with codegen pipelines (protobuf, OpenAPI) where the generation step has to run before builds in several languages, and in the right order.

A small Go-only repository is usually better served by Go's own tooling. The last section covers that trade-off.

Should you use a single go.mod or multiple modules with go.work?

The choice comes down to where the module boundary sits, because that boundary decides which files every Go project must treat as inputs.

Option A: one root module

  • go.mod and go.sum at the workspace root
  • services/orders/, services/billing/ and libs/auth/ each contain Go packages and a project.json, but no go.mod

Every Go project in this layout belongs to the same module. Nx still sees separate projects because each directory has its own project.json. How dependency edges get created depends on your plugin. Typically it reads import paths. The cost is in the inputs. Every project's build depends on the root go.mod and go.sum, so bumping one library used by a single service changes a hash that every Go project shares. The cache misses for all of them, and nx affected reports the whole Go side of the repo as affected.

Option B: multiple modules joined by go.work

  • go.work at the root, listing each module directory
  • services/orders/, services/billing/ and libs/auth/ each contain their own go.mod, go.sum and project.json

Each project's lockfile now covers only that project. A dependency bump in billing invalidates billing and anything that depends on it, and nothing else. Edges between modules show up as require lines, which a plugin can map to Nx dependencies. The cost is more files to maintain. You also need to think about builds that run without the workspace file, for example with GOWORK=off.

Aspect Single root go.mod Multiple modules + go.work
Nx project boundary project.json only project.json plus its own module
Effect of a lockfile change Invalidates every Go project Invalidates the owning module and its dependents
Affected detection Coarse after dependency bumps Precise per module
Maintenance One file to tidy One go mod tidy per module
Version skew between services Impossible Possible, so you have to manage it
repo/
├── nx.json
├── go.mod                # module example.com/acme (shared by all Go projects)
├── go.sum                # one change here invalidates every Go project's hash
├── libs/auth/            # project.json + .go files, no go.mod
└── services/
    ├── orders/           # project.json + .go files, no go.mod
    └── billing/          # project.json + .go files, no go.mod

repo/
├── nx.json
├── go.work               # local dev: resolves example.com/acme/* from disk
├── libs/auth/            # project.json, go.mod, go.sum
└── services/
    ├── orders/           # project.json, go.mod, go.sum
    └── billing/          # project.json, go.mod, go.sum (scoped to billing only)

go 1.22

use (
    ./libs/auth
    ./services/billing
    ./services/orders
)

module example.com/acme/services/billing

go 1.22

require example.com/acme/libs/auth v0.0.0

Directory layouts for a single root go.mod versus per-project modules joined by go.work, with the go.work file and a service go.mod whose require line expresses the dependency edge.

What does an nx-go plugin provide, and how do you verify what yours actually does?

Community nx-go plugins generally cover three things. First, project detection: they scan for go.mod files (or packages within a single module) and register each one as an Nx project, so you don't hand-write a project.json for every service. Second, targets: build, test, lint and sometimes tidy or generate targets that wrap go build, go test and a linter, usually with default inputs and outputs that make them cacheable. Third, dependency inference: the plugin reads Go import paths and maps them to other projects in the workspace. That mapping is what makes nx affected useful, because a change to a shared package marks its importers as affected.

Plugins differ on every one of these points, and the same plugin can change between releases, so check what yours does before you rely on it. Run nx show project <name> (add --json for machine-readable output) to see the targets, commands, inputs and outputs Nx resolved for that project. Run nx graph to confirm that an import between two services appears as a dependency edge. If an edge is missing, affected will skip projects that should rebuild. Then read the plugin's documentation for the version in your lockfile, not the latest docs.

Community plugins are maintained separately from Nx core. They can lag behind a major Nx release, rely on plugin APIs that have since changed, or alter their inference rules without much notice. Pin the plugin version, upgrade it on its own rather than alongside Nx, and diff the nx show project output before and after each upgrade.

#!/usr/bin/env bash
set -euo pipefail

PLUGIN="<your-nx-go-plugin-package>"   # placeholder: the package name in your lockfile
PROJECT="orders-api"                    # a Go service detected by the plugin
SHARED="pkg-money"                      # a shared Go package that orders-api imports

npm ls "$PLUGIN"

nx show projects

nx show project "$PROJECT" --json > before.json
jq '.targets | map_values({executor, command: .options.command, inputs, outputs, cache})' before.json

nx graph --file=graph.json
jq --arg p "$PROJECT" '.graph.dependencies[$p] | map(.target)' graph.json \
  | grep -q "\"$SHARED\"" \
  && echo "edge $PROJECT -> $SHARED present" \
  || echo "WARNING: edge $PROJECT -> $SHARED missing"

npm install --save-dev --save-exact "$PLUGIN@<new-version>"
nx reset   # clear the daemon and cache so inference is recomputed

nx show project "$PROJECT" --json > after.json
diff <(jq -S . before.json) <(jq -S . after.json) || echo "inferred config changed; review before merging"

A shell script that records the installed plugin version and snapshots the inferred project configuration. It checks that a Go import appears as a graph edge, then diffs the inferred configuration after a pinned, plugin-only upgrade.

How do you define Go build, test, lint and tidy targets in project.json?

Without a plugin, each target is an nx:run-commands entry that wraps a plain Go command. You write more configuration, but nothing is inferred behind your back, and the cache key is exactly what you declare.

Target Command Key inputs Outputs Cache?
build go build -o dist/... *.go, go.mod, go.sum, go.work, embedded files, GOOS/GOARCH/CGO_ENABLED env binary path Yes
test go test ./... build inputs plus *_test.go and testdata/ none Yes, if hermetic
lint go vet ./... or your linter source files, linter config none Yes
tidy go mod tidy go.mod, go.sum, imports rewrites files No

Declare inputs in a shared namedInputs entry and add env inputs such as { "env": "GOOS" }. Nx hashes the target's options, so build tags passed in the command string are covered. Tags or flags passed through GOFLAGS are not covered unless you also declare that variable.

Point outputs at the binary so a cache hit can restore it, not only replay the log. Test and lint targets have no file outputs, but Nx still caches their terminal output and exit code. An unchanged package can skip go test entirely.

Under-declared inputs cause false cache hits. For example, if a template loaded through //go:embed is missing from the inputs, editing it leaves the hash unchanged. Nx then restores a binary that still contains the old template. Generated code has the same risk, so include its paths explicitly.

Set cache: false for tests that touch databases, the network, the clock or unlisted environment. Their result depends on state the hash cannot see, so a cached pass is not evidence the tests still pass. Also leave tidy uncached, because it modifies the files it reads. For CI, consider a separate check variant that fails when go.mod or go.sum would change.

{
  "name": "api",
  "root": "apps/api",
  "namedInputs": {
    "goSource": [
      "{projectRoot}/**/*.go",
      "{projectRoot}/go.mod",
      "{projectRoot}/go.sum",
      "{workspaceRoot}/go.work",
      "{projectRoot}/templates/**/*",
      "{projectRoot}/internal/gen/**/*",
      { "env": "GOOS" },
      { "env": "GOARCH" },
      { "env": "CGO_ENABLED" },
      { "env": "GOFLAGS" }
    ],
    "goBuild": ["goSource", "!{projectRoot}/**/*_test.go", "!{projectRoot}/**/testdata/**/*"]
  },
  "targets": {
    "build": {
      "executor": "nx:run-commands",
      "inputs": ["goBuild"],
      "outputs": ["{workspaceRoot}/dist/apps/api"],
      "cache": true,
      "options": { "cwd": "apps/api", "command": "go build -tags prod -o ../../dist/apps/api/api ." }
    },
    "test": {
      "executor": "nx:run-commands",
      "inputs": ["goSource"],
      "cache": true,
      "options": { "cwd": "apps/api", "command": "go test ./..." }
    },
    "test-integration": {
      "executor": "nx:run-commands",
      "cache": false,
      "options": { "cwd": "apps/api", "command": "go test -tags integration ./..." }
    },
    "lint": {
      "executor": "nx:run-commands",
      "inputs": ["goSource"],
      "cache": true,
      "options": { "cwd": "apps/api", "command": "go vet ./..." }
    },
    "tidy": {
      "executor": "nx:run-commands",
      "cache": false,
      "options": { "cwd": "apps/api", "command": "go mod tidy" }
    }
  }
}

A project.json for one Go service. It declares embedded templates, generated code and GOOS/GOARCH/CGO_ENABLED/GOFLAGS as inputs, so build restores the binary from cache. Hermetic test and lint targets are cached, while integration tests and go mod tidy are not.

How do you wire a Go service to protobuf or OpenAPI codegen with dependsOn?

Treat the schema as its own Nx project, for example a proto or api-spec project that holds the .proto or OpenAPI files and owns a generate target. The Go service then lists that target in its build's dependsOn, either as ^generate (run generate on every dependency) or as an object naming the schema project and target explicitly. The explicit form is safer in a polyglot workspace, because ^generate only works if Nx already knows the schema project is a dependency.

Declare the generated directory in the generate target's outputs. This lets Nx restore the files from cache instead of rerunning protoc or the OpenAPI generator. On the Go side, add the schema files, or the dependent task's output files, to the build's inputs. If you skip this, editing a .proto file can produce a cache hit on a stale binary.

Nx can only infer edges it can see. A Go plugin may derive edges from imports, but nothing in a .proto file points at a Go package. Add implicitDependencies on the service so the edge is explicit.

Before you trust nx affected in CI, run nx graph and confirm the edge appears. Edges commonly go missing in three places:

  • go.work or replace directives that point at local paths the plugin doesn't map to projects.
  • Files behind build tags, whose imports static analysis may skip.
  • Gitignored generated code, which doesn't exist when the graph is computed, so imports of it are never detected.

How should CI cache Go and Nx results across machines?

On every pull request, run nx affected against the merge base instead of running every target. Nx compares changed files to the project graph and skips any Go service whose inputs and dependencies are unchanged. This only works as well as the graph does, so the gaps from the previous section, such as build tags and gitignored generated code, apply here too.

Persist three caches between CI runs:

  • The Nx cache, which stores task outputs.
  • GOCACHE, which holds compiled packages and test results.
  • GOMODCACHE, which holds downloaded modules.

Key the module cache on go.sum files so it is invalidated only when dependencies change. Run go env GOCACHE GOMODCACHE to find the paths instead of hardcoding them.

Remote cache and platform mismatches

A shared remote Nx cache restores outputs by hash. Assume a macOS arm64 laptop builds a binary and uploads it. If a Linux amd64 runner computes the same hash, it downloads a binary it cannot execute. To prevent this, add GOOS and GOARCH to the build target's inputs, either as env inputs or as a runtime input that runs go env GOOS GOARCH. If you cross-compile in CI, include CGO_ENABLED and any -tags values as well.

Illustrative estimate

Assume 20 services, each with a 90-second build-plus-test target, and a typical PR that touches 3 of them. A full run takes 30 minutes. An affected run takes 4.5 minutes, which saves about 25 minutes per PR.

Measure before you credit Nx with gains over a warm GOCACHE. Go already skips recompiling unchanged packages, so most of the speedup comes from skipping whole tasks and reusing results across machines.

How can an Nx Go monorepo save engineering time?

The savings come from work that doesn't get repeated, and from coordination steps people no longer do by hand:

  • Shorter CI feedback loops. nx affected limits a PR's pipeline to the Go services it can actually influence, and the Nx cache lets a re-run after a flaky failure skip tasks that already passed. Engineers wait less for each push.
  • Fewer redundant builds across people and machines. With a remote cache, a task that CI already ran for a commit can be restored on a developer's machine, or on another CI job, when the hash matches. Without it, each machine repeats the same go build and go test work.
  • Faster branch switching locally. Returning to a branch whose inputs you already built gives local cache hits, so you don't wait for builds and tests that already passed.
  • Codegen ordering handled by the task graph. dependsOn makes generate run before dependent Go and TypeScript builds. Nobody has to remember to rerun protoc before building, and fewer CI failures come from stale generated code.
  • One entry point across languages. nx affected -t build test lint covers Go and non-Go projects, so CI configuration and onboarding docs stay short and contributors don't need a per-language command list.
  • Faster impact analysis. nx graph shows which services depend on a shared library or schema before you change it, so you don't have to grep across modules.

These savings have costs. Someone has to keep inputs complete, debug the occasional false cache hit, and upgrade the plugin. Illustrative estimate: assume a team of 10 engineers who each push 4 times a day, and assume affected-only runs and cache hits cut 10 minutes of waiting from each push. That is about 400 engineer-minutes a day recovered. If keeping Nx configured takes an assumed half a day per week of one engineer's time, the trade is favourable. If your measured per-push saving is closer to a minute, it may not be. Replace the assumed inputs with numbers from your own CI history. Most of the time saved comes from reusing results across tasks and machines, not from making any single Go compile faster.

When should you avoid Nx for Go, and what are the alternatives?

That cache reuse across tasks and machines is the core of the trade. If your repository can't benefit from it, Nx is mostly overhead.

Nx earns its place when three conditions overlap: you have enough Go services that nx affected meaningfully narrows each CI run, Go code is coupled to TypeScript clients or shared schemas so that one change crosses language boundaries, and several machines would reuse each other's task results. A Go-only repository with a handful of services rarely meets these conditions. Every contributor then needs a Node.js toolchain and a lockfile they wouldn't otherwise have. They also have to learn a second mental model, Nx targets and inputs layered over go build and go test. When a cached result looks wrong, someone has to work out which of the two caches caused it.

Approach Setup cost Ongoing maintenance Time saved
Makefiles or scripts with Go tooling Low Low; scripts grow ad hoc Relies on GOCACHE; no task skipping
go.work alone Very low Low Local multi-module editing only; no orchestration
Nx Moderate Plugin upgrades, Node.js dependency, input definitions Affected-only runs and shared task cache across languages
Bazel High BUILD files, rule maintenance, specialist knowledge Hermetic builds, fine-grained remote caching and execution

Start with Makefiles and go.work. Adopt Nx once cross-language coordination or CI duration becomes a recurring cost you can measure. Consider Bazel only if you need hermeticity and can staff its upkeep.

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 go monorepo, 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.