What is an Nx Go monorepo and why would you run Go next to TypeScript?
An Nx Go monorepo is an Nx workspace where Go modules are registered as Nx projects next to TypeScript apps and libraries. Nx treats each Go module as another node in its project graph with targets like build, test, and lint. Underneath, the Go toolchain still compiles and tests the code. Nx only schedules those tasks, caches their results, and decides which ones to run.
The setup only works if you accept one constraint: Nx does not understand Go imports natively. Its core graph-building logic reads JavaScript and TypeScript sources, along with configuration such as package.json. It does not read go.mod or Go import statements. Two things follow from that:
nx affectedcan miss Go services that depend on a changed module.- The cache can replay stale output.
Both are only correct once you teach Nx the dependency edges and cache inputs. You can do that with a community nx-go plugin or with hand-written targets and explicit configuration.
When those edges are in place, teams get three concrete benefits:
- One affected computation across languages. A change to a shared API schema marks both the Go service and the TypeScript client that consume it as affected.
- One task runner and one cache. CI runs a single command instead of separate per-language pipelines that each guess what changed.
- Shared contracts in one place. Protobuf, OpenAPI, or JSON Schema definitions can live beside both the Go code and the TypeScript code generated from them, so breaking changes surface in the same pull request.
Platform teams gain the most when Go backends and TypeScript frontends or BFFs share contracts and ship together. If your Go services barely interact with the TypeScript side, be skeptical. You would take on graph maintenance for a coupling you don't have, and Go's own build cache already handles much of what Nx caching offers.
Who should use an Nx Go monorepo?
This setup fits teams that meet most of these conditions:
- You already run Nx for TypeScript. The workspace, CI conventions, and cache are in place, and the question is whether to bring Go services under the same runner. Adopting Nx from scratch only for Go is harder to justify.
- Go and TypeScript code share contracts. Go services expose APIs that TypeScript frontends, BFFs, or Node services consume through generated clients or shared schemas. A change on one side needs to trigger builds and tests on the other.
- CI time grows with the number of services. When every pull request rebuilds and retests every Go service, affected detection has real work to skip.
- Someone owns the build configuration. A platform or developer-experience engineer, or a team that accepts the duty, keeps dependency edges and cache inputs correct as modules are added and imports change.
It fits less well for teams that only write Go, for Go services with no TypeScript consumers, and for organizations where Go engineers strongly prefer to work without a Node toolchain installed. The last section of this article covers those signals in more detail.
How does an Nx Go monorepo work?
Nx does not replace the Go toolchain. It wraps it. The flow for any command such as nx affected -t build test looks like this:
- Project discovery. Nx finds projects through
project.jsonfiles (or through a plugin that infers projects fromgo.modfiles). Each Go module becomes a named project with a root directory and a set of targets. - Project graph construction. Nx builds a graph of projects and the dependencies between them. TypeScript edges come from Nx's own import analysis. Go edges come from a plugin that reads Go imports, or from
implicitDependenciesthat you declare by hand. - Affected calculation. For
nx affected, Nx diffs the base and head commits, maps each changed file to the project whose root contains it, and then walks the graph to add every project that depends on a changed one. - Task hashing. For each task to run, Nx computes a hash from the target's declared inputs: source file globs, environment variables, and the inputs of dependencies where configured.
- Cache lookup. If a matching hash exists in the local or remote cache, Nx restores the recorded terminal output and the files listed in
outputs, and skips the task. - Execution. On a cache miss, the
nx:run-commandsexecutor (or a plugin executor) runsgo build,go test, orgo vetwith the working directory set to the module root. Go's own build cache then reuses compiled packages inside that run. - Cache storage. Nx stores the task's output and declared artifacts under the computed hash for later runs.
The following sections cover each part: how to lay out modules, how to register targets, how to declare cache inputs, and how to give Nx the Go dependency edges it cannot infer by default.
How should you lay out Go modules in an Nx workspace?
Put Go code under the same apps/ and libs/ split the TypeScript side already uses. Nx cares about project roots, not languages, and engineers find a service faster when there is only one convention to learn.
apps/orders-api/: Go service, owngo.modbilling-worker/: Go service, owngo.modweb/: TypeScript frontend
libs/go-shared/: shared Go packages, owngo.modui/: TypeScript librarycontracts/: protobuf or OpenAPI definitions, generating Go and TS clients
go.worknx.json
One module or one per service?
| Concern | Single root go.mod |
One go.mod per project |
|---|---|---|
| Affected granularity | Coarse. go.mod and go.sum are inputs to every Go project, so any change touches all of them. |
Fine. Only the module whose files changed, plus its dependents. |
| Dependency bumps | One edit, applied everywhere at once. | Local to one module, so services can drift onto different versions. |
| Sync cost | None. | You must align shared versions and run go mod tidy in every module. |
Per-service modules give Nx something meaningful to compute. The price is version-alignment work that the single module handles for free.
go.work and GOWORK=off
go.work lets orders-api resolve libs/go-shared from disk without replace directives, which makes local development smooth. That same convenience can mislead you. A module can build inside the workspace while its own go.mod lacks the require or replace it needs, and the gap only shows up when the module is built alone.
Pick one rule for CI and apply it consistently:
- If modules are only ever built inside this repository, build with the workspace file.
- If any module must build on its own, run its CI build and tests with
GOWORK=off, because that exposes missing entries before a release does.
#!/usr/bin/env bash
set -euo pipefail
export GOWORK=off
modules=(apps/orders-api apps/billing-worker libs/go-shared)
for dir in "${modules[@]}"; do
echo "==> ${dir}"
(
cd "${dir}"
# Fail if go.mod/go.sum are not tidy for this module alone.
go mod tidy
git diff --exit-code -- go.mod go.sum
go vet ./...
go build ./...
go test ./...
)
done
A CI script that sets GOWORK=off and builds, vets, tests and tidy-checks each Go module separately, so a require or replace entry that go.work was covering for causes the build to fail.
How do you register a Go module as an Nx project with run-commands targets?
Each Go module gets a project.json at its root, next to go.mod. The service uses three targets, all with the nx:run-commands executor and cwd set to the module directory, for example apps/orders-api. The go tool resolves packages from the working directory, so a target that runs from the workspace root would either fail or pick up the wrong module.
buildrunsgo build -o ../../dist/apps/orders-api/server ./cmd/serverand declares{workspaceRoot}/dist/apps/orders-apiinoutputs. The binary goes to a fixed location outside the source tree, so Nx can restore it from cache, and stray binaries don't end up inside the module.testrunsgo test ./....lintrunsgo vet ./....
This setup relies only on the core nx:run-commands executor and the go toolchain. It doesn't depend on any plugin's version or generator behavior. If you adopt a plugin later, keep this pattern for anything the plugin doesn't model, such as code generation or a custom linker flag.
Run a single target with nx run orders-api:build. Run several targets across every project with nx run-many -t test lint, which includes TypeScript projects that define those same target names.
Register a shared Go package, such as libs/go/auth, as its own project with its own project.json. Give it test and lint targets but no build target. A library has no binary to produce, and the services that import it compile it as part of their own builds. Treating the library as a separate project lets Nx test it independently and track it as a dependency of the services that use it.
cat > apps/orders-api/project.json <<'EOF'
{
"name": "orders-api",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"projectType": "application",
"targets": {
"build": {
"executor": "nx:run-commands",
"outputs": ["{workspaceRoot}/dist/apps/orders-api"],
"options": {
"cwd": "apps/orders-api",
"command": "go build -o ../../dist/apps/orders-api/server ./cmd/server"
}
},
"test": {
"executor": "nx:run-commands",
"options": { "cwd": "apps/orders-api", "command": "go test ./..." }
},
"lint": {
"executor": "nx:run-commands",
"options": { "cwd": "apps/orders-api", "command": "go vet ./..." }
}
}
}
EOF
npx nx run orders-api:build
npx nx run-many -t test lint
Writes a plugin-free project.json for a Go service with build, test and lint targets that run from the module root, then runs them with nx run and nx run-many.
How do you configure Nx cache inputs and outputs for Go targets?
Nx hashes only what you declare, so a Go project needs its own named inputs. Define a go-sources input with {projectRoot}/**/*.go, go.mod, and go.sum, and add the exclusion pattern !{projectRoot}/**/*_test.go. Builds then ignore test edits. The test target uses the full set, test files included.
Two cases are easy to miss. Files pulled in through //go:embed are compiled into the binary, so templates and static assets need their own globs. Generated code should be an output of a generator target that build depends on. Otherwise a stale .pb.go file can be treated as source. Add environment inputs for GOOS, GOARCH, and CGO_ENABLED, because the same source produces a different binary for each combination. Declare the binary path, such as {workspaceRoot}/dist/{projectName}, in outputs so Nx can restore the binary on a cache hit.
Getting the inputs wrong fails in one of two ways:
| Inputs | Symptom | Cost |
|---|---|---|
| Too narrow | Cache hits after a real change | A stale binary or a false test pass reaches CI |
| Too broad (for example, the whole repo) | Almost every change misses | Little caching benefit remains |
Tests that hit a database or the network depend on state that Nx cannot hash. Move them into a separate integration target with caching disabled ("cache": false). Inside that target, run go test -count=1 so Go's own test-result cache doesn't replay an old pass either.
The three caches work at different levels. The Nx cache skips whole tasks and can be shared across machines. Go's build cache (GOCACHE) reuses compiled packages when a task does run. The module cache avoids downloading dependencies again. Persist all three in CI, because each one speeds up a part of the build the others don't cover.
{
"name": "api",
"namedInputs": {
"go-sources": [
"{projectRoot}/**/*.go",
"!{projectRoot}/**/*_test.go",
"{projectRoot}/go.mod",
"{projectRoot}/go.sum",
"{projectRoot}/templates/**/*",
"{projectRoot}/static/**/*"
],
"go-env": [{ "env": "GOOS" }, { "env": "GOARCH" }, { "env": "CGO_ENABLED" }]
},
"targets": {
"generate": {
"command": "go generate ./...",
"options": { "cwd": "{projectRoot}" },
"inputs": ["{projectRoot}/proto/**/*.proto"],
"outputs": ["{projectRoot}/gen"]
},
"build": {
"dependsOn": ["generate"],
"command": "go build -o ../../dist/api ./cmd/api",
"options": { "cwd": "{projectRoot}" },
"inputs": ["go-sources", "go-env"],
"outputs": ["{workspaceRoot}/dist/{projectName}"]
},
"test": {
"dependsOn": ["generate"],
"command": "go test ./...",
"options": { "cwd": "{projectRoot}" },
"inputs": ["go-sources", "{projectRoot}/**/*_test.go", "go-env"]
},
"integration": {
"command": "go test -count=1 -tags=integration ./...",
"options": { "cwd": "{projectRoot}" },
"cache": false
}
}
}
A project.json for a Go service at apps/api: build hashes non-test Go files, go.mod, go.sum, embedded assets and GOOS/GOARCH/CGO_ENABLED, test adds _test.go files, and integration tests skip both the Nx cache and Go's test cache.
How does Nx know which Go projects depend on each other?
Nx builds its project graph from two sources: dependencies it infers by analyzing project files, and dependencies you declare yourself. Nx's built-in analysis understands JavaScript and TypeScript imports, but it does not parse Go source. Unless you install something that teaches it Go, a Go service has no edges at all.
Inferred edges from a plugin
An nx-go plugin from the community can add a project graph extension that reads each go.mod and the import statements in .go files. It maps module paths such as example.com/repo/libs/auth back to the Nx project that owns that directory. When services/billing imports that package, the plugin adds an edge, and editing libs/auth marks billing as affected.
Declared edges with implicitDependencies
Without a plugin, list dependencies in each project's project.json. For example, add "implicitDependencies": ["contracts"] to both the Go billing-api project and the TypeScript billing-client project. Here contracts holds the OpenAPI spec or .proto files. A schema change then marks both the server and the client as affected, even though neither one imports the schema as code.
The risk is a silent failure. If an edge is missing, nx affected does not report an error. It skips the Go service that changed through a shared package, CI passes, and the broken binary ships.
Before you rely on affected results, open nx graph and confirm that every shared Go package has edges to its consumers. Then run nx show project billing-api to check its resolved dependencies and target inputs.
cat > services/billing-api/project.json <<'EOF'
{
"name": "billing-api",
"root": "services/billing-api",
"implicitDependencies": ["contracts", "auth"]
}
EOF
cat > libs/billing-client/project.json <<'EOF'
{
"name": "billing-client",
"root": "libs/billing-client",
"implicitDependencies": ["contracts"]
}
EOF
nx graph --focus=contracts
nx show project billing-api --json | jq '.implicitDependencies'
nx graph --file=graph.json
jq '.graph.dependencies["billing-api"]' graph.json
nx show projects --affected --base=origin/main --head=HEAD
Declares implicitDependencies so a change to the shared contracts project affects both the Go billing-api and the TypeScript billing-client, then checks with nx graph and nx show project that those edges exist before relying on affected results.
What does an nx-go plugin add, and what are the alternatives?
A community Go plugin, usually called nx-go, packages the wiring from earlier sections. In concept it adds three things: generators that scaffold a Go module and register it as a project, preconfigured targets for build, test, lint and tidy, and project graph inference that reads Go imports so that dependency edges appear without manual implicitDependencies.
Releases differ in what they include, so check your installed version before you rely on it. Run nx list with the plugin's package name to see its generators and executors. Add --help to a generator call to see its options. Then run nx show project on a generated project to see which targets were inferred and what cache inputs they use.
The plugin is maintained separately from Nx core, and its release cycle may lag behind Nx's. Pin its version and upgrade it in the same change as Nx. Keep plain run-commands targets for your critical paths so a broken plugin release does not block CI.
| Approach | Setup effort | Correctness of affected | Upgrade risk |
|---|---|---|---|
| Hand-written run-commands | Moderate. You write targets and inputs yourself. | Only as good as your declared dependencies. Missed edges cause silent skips. | Low. Depends only on Nx core. |
| Community plugin | Low | Good if import inference works for your module layout | Medium. Compatibility with each Nx release varies. |
| Separate Go repo with native tooling and Makefiles | Low for Go | No cross-language affected. Go's own test cache helps within the repo. | Low |
| Different polyglot build system | High. Requires hermetic build definitions. | Strong when the definitions are complete | Migration cost, plus a toolchain the team must learn |
How do you run nx affected for Go and TypeScript in one CI pipeline?
A single job with both toolchains is simpler than splitting by language: nx affected computes one project graph, so a TypeScript client that depends on a Go service's generated schema is scheduled correctly. Separate jobs would each need their own copy of that graph.
Job outline
- Check out with history. Affected calculation diffs two commits, so a shallow clone of depth 1 will fail or mark everything affected. Fetch enough history to reach the base commit.
- Install Node and Go. Pin both versions in files the repo controls, such as the
godirective in eachgo.modand your Node version file, so local and CI toolchains match. - Pick the base ref.
- For pull requests, use
git merge-base origin/main HEAD. This compares against where the branch forked, not against whatevermainhas moved to since. - For pushes to
main, use the SHA of the last successfulmainbuild, stored by your CI system. If you useHEAD~1instead, a failed commit's changes drop out of the next run.
- For pull requests, use
- Restore caches, then run
npm ci(or your package manager's equivalent) andgo mod downloadfor each module. - Run one command:
nx affected -t build test lint --base=$BASE --head=HEAD.
Caching Go separately
Persist three directories as separate cache entries:
go env GOCACHE, the compiled package and test cache.go env GOMODCACHE, the downloaded modules.- The Nx cache directory.
Key the Go entries on a hash of every go.sum in the repo. That way a dependency change invalidates only the module cache, and the Nx cache is unaffected. Keep the Nx cache separate because its validity follows task inputs, not dependency lockfiles.
If your team has decided not to use go.work in CI, export GOWORK=off at the job level. Without it, a stray workspace file could change which module versions are resolved.
How can an Nx Go monorepo save engineering time?
The time savings come from work that no longer happens, not from making individual Go builds faster. go build is already quick and already caches compiled packages. The savings appear in these places:
- CI work scales with the change, not the repo. With correct dependency edges, a pull request that touches one service builds and tests that service and its dependents. Engineers wait less for CI, and shared runners stay free for other pull requests.
- Remote cache hits skip repeated work. When a task's inputs match a hash that another machine or an earlier CI run already produced, Nx restores the result instead of running it again. A rebased branch or a re-run after a flaky unrelated job can then finish without rebuilding untouched Go services.
- One pipeline to maintain. A single
nx affected -t build test lintstep replaces a Go pipeline and a TypeScript pipeline that each need their own change-detection logic. Platform engineers update one set of CI configuration instead of two. - Contract breaks surface in the original pull request. When a schema change marks both the Go server and the TypeScript client as affected, a breaking change fails in the same pull request that caused it. Without this, it often shows up later in a separate repository, after someone has already merged and moved on, and the debugging takes longer.
- One command surface. New team members learn
nx run,nx run-many, andnx affectedonce and can build or test any project, in either language, the same way.
These savings depend on the dependency edges and cache inputs being correct. A wrong edge can cost more time than it saves, because a missed consumer passes CI untested and fails later. The next section works through an illustrative estimate of the CI savings, with assumed inputs, and lists cases where the savings are too small to justify the setup.
When should you avoid an Nx Go monorepo, and what does it cost?
The setup trades daily friction for CI and coordination savings. Before adopting it, check whether those savings apply to your workspace.
| Cost | Saving |
|---|---|
| Go engineers learn Nx conventions and keep Node installed | One command surface for both languages |
| Extra project configuration, and another way for builds to fail | Affected detection keeps CI work proportional to the change |
| Community plugins can lag behind Nx releases | A contract change runs Go and TypeScript consumers in the same pipeline |
| The Nx cache partly overlaps Go's build cache | Remote cache hits are shared across machines |
The cache overlap matters most for small services. go build and go test already skip unchanged packages locally, so Nx adds little there. Its real gain is skipping whole projects in CI.
Illustrative estimate (assumed numbers, not a benchmark). Assume these inputs:
- 12 Go services
- 6 CI minutes per service
- 70% of PRs touch one service
- 30% of PRs touch shared code that affects every service
The formula is:
Expected minutes per PR = (p × m) + ((1 − p) × N × m)
With the assumed inputs:
- Expected minutes per PR = (0.7 × 6) + (0.3 × 12 × 6) = 25.8 minutes
- Running everything on every PR = 72 minutes
- Saving per PR = 72 − 25.8 = 46.2 minutes
If your services take 1 minute each, the saving shrinks to under 8 minutes. That may not justify the setup.
Signals to avoid it
- No real TypeScript coupling. The Go services share no contracts, generated clients, or schemas with the TypeScript projects. A separate repository with plain Go tooling is simpler.
- Very small services. Builds finish in seconds, so affected detection saves little.
- No one will maintain dependency edges. If the dependency graph goes stale,
nx affectedmisses consumers. CI then passes changes it never tested, which is worse than running everything.
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.