What is an Nx Go monorepo and who should use one?
An Nx Go monorepo is a single Nx workspace where Go services and libraries sit next to TypeScript apps, such as a React frontend, a Node.js BFF, or a set of shared packages. The division of labor matters. The Go toolchain still owns everything Go-specific: go.mod resolution, compilation, go test, and vetting. Nx does not replace any of that. It wraps those commands as targets, then decides when to run them. It orders tasks through a single task graph, restores results from its cache, and skips projects that a change could not have affected.
Teams adopt this setup for three practical reasons:
- One pipeline instead of two. Without a shared orchestrator, a polyglot repo usually ends up with a Go-only CI path and a JavaScript-only CI path that drift apart. Nx gives both languages the same commands, the same cache, and the same notion of "affected."
- Contracts that change atomically. When a protobuf or OpenAPI definition changes, the Go server and the TypeScript client can be regenerated, built, and tested in the same commit and the same CI run.
- Less wasted CI time. A change to a frontend component should not rebuild every Go binary, and the reverse is also true.
The setup fits platform and backend teams whose Go and TypeScript code genuinely change together. If your Go services rarely touch the frontend, most of the benefit disappears.
The adoption cost is real. Every Go engineer now needs Node.js and a JavaScript package manager installed, along with a node_modules directory, just to run builds the standard way.
+--------------------------------------------------------------------------+
| Nx workspace: one repo, one task graph, one cache |
| |
| +--------------------------------------------------------------------+ |
| | Nx: task graph -> cache -> affected detection (orchestration only) | |
| | runs on Node.js + a JS package manager (prereq for Go engineers) | |
| +--------------------------------------------------------------------+ |
| | | | |
| v v v |
| +---------------+ +-----------------+ +--------------------------+ |
| | TypeScript | | Shared contract | | Go services and libs | |
| | apps |<--| protobuf or |-->| go.mod modules | |
| | React, BFF, | | OpenAPI spec | | go build / go test | |
| | shared pkgs | | (regen both) | | go vet (Go toolchain) | |
| +---------------+ +-----------------+ +--------------------------+ |
| |
| nx affected: rebuild/retest only projects a change can reach |
+--------------------------------------------------------------------------+
|
v
one CI pipeline for Go and TypeScript
Nx sits above the Go toolchain and the TypeScript apps as an orchestration, caching and affected-detection layer, while each language keeps its own build and test tools and both share contracts and a single CI pipeline.
Which Go module layout should you choose: one go.mod per service, a root go.mod, or go.work?
Go's module system and Nx's project model overlap but are not the same thing, and the layout you pick determines how accurately nx affected can reason about your Go code.
| Layout | Dependency isolation | Version drift | Effect of a go.mod/go.sum change |
How Nx infers edges |
|---|---|---|---|---|
One go.mod per service |
Strong; each service pins its own versions | High; the same library can sit at different versions | Only that project is affected | From replace directives or cross-module imports |
Single root go.mod |
None; one dependency set for everything | None | Every Go project is affected | From package import paths inside one module |
Multiple modules plus go.work |
Strong at release time, shared during development | Moderate; the workspace hides it locally | Only the module that changed | From go.work use entries plus imports |
A root go.mod is the simplest option, but for Nx to stay correct it must be an input to every Go project. A single dependency bump then rebuilds and retests all of them. Per-service modules keep the affected set small, but the cost moves to keeping shared libraries aligned.
go.work needs an explicit team decision. The Go documentation generally advises against committing it, because builds then resolve modules differently from how a consumer of the published module would. In a monorepo that never publishes modules, committing it is defensible, since CI then resolves dependencies the same way laptops do. If you leave it uncommitted, run CI with GOWORK=off so each module builds against its own go.mod.
Use this to decide:
- Pick a root
go.modif you have a few services, ship them together, and full rebuilds are cheap. - Pick one
go.modper service if teams deploy independently and you want the smallest possible affected set. - Add
go.workon top of per-service modules if you edit shared libraries often and want local changes picked up withoutreplacedirectives.
#!/usr/bin/env bash
set -euo pipefail
# --- Local development (run once per clone) ---
# Tie the per-service modules together so edits in libs/shared are
# visible to every service without publishing a new version.
go work init ./services/api ./services/billing ./libs/shared
# Register a module added later.
go work use ./services/notifier
# Print the active go.work path; empty output means workspace mode is off.
go env GOWORK
# If the team decides NOT to commit go.work, keep it out of git:
# echo 'go.work' >> .gitignore
# echo 'go.work.sum' >> .gitignore
# --- CI (go.work not committed) ---
# Build and test each module against its own go.mod and go.sum, the same
# way a consumer of that module would resolve dependencies. Any
# cross-module dependency must resolve through a replace directive or a
# published version, because the workspace no longer covers it.
for mod in services/api services/billing services/notifier libs/shared; do
(
cd "$mod"
GOWORK=off go mod tidy
# Fail if go.mod/go.sum were not tidy. A workspace can hide this locally.
git diff --exit-code -- go.mod go.sum
GOWORK=off go build ./...
GOWORK=off go test ./...
)
done
Sets up a go.work workspace for local development, then builds, tests and tidy-checks each module in CI with GOWORK=off so it resolves against its own go.mod.
How do you register a Go service as an Nx project by hand?
Before reaching for a plugin, it helps to wire one service up manually so you know exactly what Nx is doing. Create a project.json in the module root, for example apps/orders/project.json, next to that service's go.mod.
The top-level fields are small. name is the identifier you pass to nx run. root points at the service directory. projectType: "application" tells Nx this is a deployable, not a shared library. Each entry under targets uses the nx:run-commands executor, which simply shells out. That executor is the point of this exercise: there is no Go-specific logic hidden anywhere.
Set options.cwd to the module root on every target. Go resolves imports relative to the nearest go.mod, and Nx runs commands from the workspace root by default. If you leave cwd out, ./... matches the wrong packages or fails outright.
- build:
go build -o ../../dist/apps/orders/orders .. A fixed, project-scoped output path lets you declareoutputsprecisely, which matters for caching in the next section. - test:
go test ./...covers every package in the module. - lint:
go vet ./...followed by whatever linter the team already runs. Setparallel: falseso the steps run in order and the first failure stops the target. - serve:
go run .. Mark it as not cacheable, because a long-running process has no meaningful output to cache.
This setup is verbose and repeats itself across services. In exchange, it depends only on Nx core and the Go toolchain, so a stalled community plugin can't block an Nx upgrade.
{
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"name": "orders",
"root": "apps/orders",
"projectType": "application",
"targets": {
"build": {
"executor": "nx:run-commands",
"outputs": ["{workspaceRoot}/dist/apps/orders"],
"options": {
"cwd": "apps/orders",
"command": "go build -o ../../dist/apps/orders/orders ."
}
},
"test": {
"executor": "nx:run-commands",
"options": {
"cwd": "apps/orders",
"command": "go test ./..."
}
},
"lint": {
"executor": "nx:run-commands",
"options": {
"cwd": "apps/orders",
"parallel": false,
"commands": ["go vet ./...", "golangci-lint run ./..."]
}
},
"serve": {
"executor": "nx:run-commands",
"cache": false,
"options": {
"cwd": "apps/orders",
"command": "go run ."
}
}
}
}
A hand-written apps/orders/project.json that runs every Go target from the module root via nx:run-commands, with a fixed build output path, sequential vet-then-lint, and an uncached serve target.
How should you configure Nx cache inputs and outputs for Go?
Start with a go named input in nx.json so every Go project hashes the same file set: {projectRoot}/**/*.go, {projectRoot}/go.mod, {projectRoot}/go.sum, and {workspaceRoot}/go.work plus go.work.sum if you use a workspace. Then add what the compiler reads but the *.go glob misses. That means files pulled in by //go:embed (templates, SQL migrations, static assets), and cgo sources such as *.c, *.h, and *.s. Keep files with build-tag constraints like _linux.go or //go:build integration in the input set even if your local platform skips them, because CI may compile them. Add a runtime input that runs go version so a toolchain upgrade invalidates the cache.
These inputs need to be complete because Nx trusts the hash. If an embedded template is missing from the inputs, editing it leaves the hash unchanged. Nx then replays the earlier passing build and test result while the real binary is broken.
Set outputs to a fixed path such as {workspaceRoot}/dist/{projectRoot}/server. Write the binary there with go build -o so Nx can restore it.
Integration tests that talk to a live database depend on state that Nx cannot hash. Either set "cache": false on those tests, or declare env inputs such as the schema version.
Go already caches compilation and test results locally, so Nx adds little to a single build on one machine. The savings come from shared remote caching and from skipping unaffected projects.
Illustrative estimate. Assume 20 Go services, 3 minutes each to build and test on a cold CI runner, and a typical PR that touches 2 services. That comes to about 6 minutes of work instead of 60.
{
"namedInputs": {
"go": [
"{projectRoot}/**/*.go",
"{projectRoot}/go.mod",
"{projectRoot}/go.sum",
"{workspaceRoot}/go.work",
"{workspaceRoot}/go.work.sum",
"{projectRoot}/**/*.c",
"{projectRoot}/**/*.h",
"{projectRoot}/**/*.s",
"{projectRoot}/templates/**/*",
"{projectRoot}/migrations/**/*.sql",
"{projectRoot}/static/**/*",
{ "runtime": "go version" }
]
},
"targetDefaults": {
"build": {
"cache": true,
"inputs": ["go"],
"outputs": ["{workspaceRoot}/dist/{projectRoot}/server"],
"executor": "nx:run-commands",
"options": {
"cwd": "{projectRoot}",
"command": "go build -o {workspaceRoot}/dist/{projectRoot}/server ."
}
},
"test": {
"cache": true,
"inputs": ["go"]
},
"integration-test": {
"cache": false
}
}
}
An nx.json sketch with a shared go named input (sources, module files, cgo and embedded assets, go version), a fixed binary output path, and a non-cacheable database-backed integration-test target.
How does the project graph work for Go, and what does the nx-go plugin add?
Nx builds dependency edges from two sources: static analysis done by plugins, and declarations you write yourself. The built-in JavaScript/TypeScript support reads package.json dependencies and TypeScript imports, so edges between TS projects appear automatically. Nothing in core Nx parses .go files or go.mod, so when services/orders imports libs/go/auth, Nx has no edge between them. affected will then skip orders when auth changes, and that kind of miss is easy to overlook.
The community nx-go plugin fills this gap. It provides generators for Go applications and libraries, and it infers project-graph edges by reading Go imports. Generator names and options change between releases, so check the plugin's README for the current list. The plugin is community-maintained, which means it can lag behind new Nx releases. Before you upgrade Nx, pin the plugin version and confirm it is compatible.
Without the plugin, add implicitDependencies to each Go service's project.json and list the Go libraries it imports. Cross-language edges need the same treatment with or without the plugin. A TypeScript client generated from a Go service's OpenAPI spec has no import that points back to Go, so declare the service as an implicit dependency of the client. After any change, run nx graph and confirm that every expected edge appears.
| Aspect | nx-go plugin | Hand-written implicitDependencies |
|---|---|---|
| Go-to-Go edges | Inferred from imports | Declared manually, can drift from imports |
| Cross-language edges | Still manual | Manual |
| Scaffolding | Generators | None |
| Upgrade risk | Must track Nx compatibility | Only core Nx |
| Best fit | Many Go libraries that change often | Few, stable Go dependencies |
How do you share protobuf or OpenAPI contracts between Go and TypeScript?
Put the .proto or OpenAPI files in their own Nx project, for example libs/contracts, and give it two codegen targets: one that emits Go and one that emits TypeScript. Declare the spec files as the targets' inputs and the generated directories as their outputs. Nx then reruns codegen only when a contract actually changes, and restores the output from cache otherwise.
Consumers need two things. The first is a graph edge to the contracts project, added through implicitDependencies because Nx cannot infer it from Go imports or TypeScript paths. The second is a dependsOn entry on their build and test targets that points at the matching codegen target, so stubs are regenerated before compilation.
The edge is the part teams forget, and it fails silently. Without it, a change to a .proto file marks only the contracts project as affected. The Go service and the TypeScript client that consume it are skipped in CI, and the breakage appears after merge.
You also have to choose where generated code lives:
- Committed: Reviewers see the generated diff in pull requests.
gopls,go build, andgo test ./...work in a fresh checkout without running Nx. The risk is drift, because someone edits a spec and forgets to regenerate. Add a CI check that runs codegen and fails if the working tree changes. - Generated at build time: Drift cannot happen. The cost is that Go tooling is broken until someone runs the codegen target, which hurts editor setup and any workflow that bypasses Nx.
For Go, committing generated code is usually the better trade-off.
How do you run affected builds in CI and containerize Go services?
On pull requests, run nx affected with --base set to the merge base of the branch and main (from git merge-base origin/main HEAD) and --head set to the PR commit. Diffing against the tip of main instead pulls in unrelated changes merged since the branch was cut and inflates the affected set. On pushes to main, use the last commit that passed CI as the base, not HEAD~1, so a failed run's changes are not silently skipped. CI also needs enough git history for the merge base to exist, so a depth-1 shallow clone will not work.
Nx's cache only skips whole targets. When a target does run, Go still benefits from its own caches, so persist the directories reported by go env GOMODCACHE and go env GOCACHE alongside Nx's cache directory. Key the module cache on go.sum.
Affected detection only sees the edges and inputs you declared. An undeclared replace path, an embedded file outside the inputs, or a missing proto dependency means a change ships without a rebuild.
For images, use a multi-stage Dockerfile whose build context is the service's module root and nothing above it. Copy go.mod and go.sum first and download modules in their own layer, so dependency layers survive source edits. Build with GOWORK=off and CGO_ENABLED=0, then copy the binary into a minimal final stage. A narrow context means any replace directive pointing outside the module fails loudly rather than depending on whatever happens to be on the CI runner. Define an Nx docker target with dependsOn: ["build"] so compile and test failures stop the pipeline before an image is built.
When should you avoid Nx for Go, and what are the alternatives?
Nx earns its keep when Go and TypeScript share contracts, CI, and release cadence. If the repository is mostly Go with a small admin UI, the cost of project.json files, cache input tuning, and a Node toolchain on every CI runner can outweigh the savings. The same applies to teams that already run per-module CI pipelines and Go-native tooling: Nx would duplicate dependency knowledge that go list and the module graph already provide.
| Approach | Setup and maintenance cost | Where time is saved | Main weakness |
|---|---|---|---|
Plain Go tooling, go.work, path-filtered CI |
Low; uses only the Go toolchain | Go's build and test cache; CI skips unchanged paths | Path filters miss transitive changes unless kept in sync by hand |
| Makefiles or another task runner | Low to moderate | Consistent entry points across languages | No project graph, affected detection, or shared remote cache |
| Separate repositories | Low per repo, high coordination | Fully independent pipelines | Contract changes need versioned releases across repos |
| Other polyglot build systems | High; build files for every package | Fine-grained, hermetic caching | Steep learning curve and friction with standard go commands |
Guardrails if you adopt Nx
- Run Go commands from the module root. Set each target's working directory to the folder containing
go.mod, so module resolution matches what engineers see locally. - Configure gopls and editors for the layout. A root
go.worklets gopls resolve multiple modules from one editor window. Without it, gopls needs each module opened as its own workspace folder. - Keep
go test ./...working without Nx. Engineers who never touch TypeScript should be able to clone, run plain Go commands, and get correct results. Nx should orchestrate Go, not replace it.
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.
- Changing a route's URL or method automatically notifies the services that consume it — no hunting through repos for callers.
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.
- Consumers learn about a breaking change at review time rather than from production errors.
- 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.