What is nx-go, and why add Nx to a Go monorepo?

Nx is a build system and task runner that models a repository as a graph of projects and the dependencies between them. It caches task results and can work out which projects a change touches. Nx has no built-in understanding of Go. The community-maintained nx-go plugin provides it. The plugin reads your Go module paths and package imports and turns them into Nx project nodes and dependency edges. It also exposes Go build and test commands as Nx targets.

This article's position is that Nx earns its place in a Go monorepo mainly through two features: the project graph and nx affected. Caching helps, but the larger gain comes from not running work that a change cannot influence.

Affected detection works by comparing your branch against a base commit. Nx then walks the graph from the changed files outward. Suppose you edit a shared auth package. Nx selects that package and every service that imports it, directly or transitively. It skips the rest. A change to one service's handler selects only that service. In both cases, CI time scales with the size of the change instead of the size of the repository.

The following is an illustrative estimate, not a measured result. Assume 40 services, each taking 3 minutes to build and test. A full run costs 120 minutes of compute. If a typical change touches 4 services, the affected run costs 12 minutes.

That trade suits platform and backend teams with many services, shared packages, and slow full CI runs. It suits a repository with only a handful of services far less. In that case, go test ./... is already fast, and adding Node.js, a lockfile, and Nx configuration is unlikely to pay for itself.

Should you use one go.mod or a go.work multi-module layout?

The layout decision shapes everything Nx does afterwards, so settle it first.

With a single root go.mod, the whole repository is one Go module. An Nx project is a directory you register, usually a service under apps/ or a shared package under libs/. Because every project shares one module path, dependency edges come from import paths. If apps/billing imports example.com/repo/libs/money, that import is the edge. The cost is version coupling. Every service builds against the same version of every third-party dependency, so upgrading a shared library is one change that affects all services at once.

With several modules joined by go.work, each service or library has its own go.mod, and the module is the natural project boundary. Edges come from module requirements as well as imports, so they are coarser and harder to trace. A dependency that appears in go.mod but is not visible in source can still affect results. Isolation is the benefit: each module pins its own dependency versions. The costs are replace directives that drift, tools that behave differently depending on whether workspace mode is active, and CI that must decide whether to honour go.work.

Aspect Single go.mod go.work multi-module
Nx project Registered directory Module
Edge source Package imports Module requirements plus imports
Dependency versions Shared, coupled Per module, isolated
Operational overhead Low replace upkeep, workspace-mode tooling

Most teams should start with a single module. Moving from one layout to the other after you have configured Nx means restructuring how projects are registered and how edges are detected.

# Layout A: one module at the repo root.
# Every project shares the module path, so edges are package imports.
go mod init example.com/repo
go list -f '{{join .Imports "\n"}}' ./apps/billing | grep 'example.com/repo/'
# -> example.com/repo/libs/money   (this import is the dependency edge)

# Layout B: one module per project, joined by go.work.
(cd apps/billing && go mod init example.com/repo/apps/billing)
(cd libs/money && go mod init example.com/repo/libs/money)
go work init ./apps/billing ./libs/money

# Each module pins its own third-party versions; list them per module.
(cd apps/billing && go list -m all)

# The edge now also lives in go.mod as a requirement.
# A local replace keeps builds working when go.work is ignored,
# but it is one more path to keep in sync.
(cd apps/billing && go mod edit -replace example.com/repo/libs/money=../../libs/money)

# Workspace mode changes tool behaviour: check which go.work is in effect.
go env GOWORK

# CI must choose explicitly: build with go.work, or as standalone modules.
(cd apps/billing && go build ./...)            # uses go.work if found
(cd apps/billing && GOWORK=off go build ./...) # uses only go.mod + replace

Shows how dependency edges and version pinning differ between a single root go.mod and a go.work multi-module layout, including the replace directive and GOWORK setting that the multi-module layout adds.

How do you add the nx-go plugin and register Go projects?

Start from an existing Nx workspace or create one at the repository root, next to go.mod or go.work. Nx only needs a package.json and an nx.json. Your Go code stays where it is. Install the community nx-go plugin (published as @nx-go/nx-go) as a dev dependency, and pin an exact version rather than a caret range. The plugin decides how projects are detected and how the dependency graph is built, so an unplanned minor upgrade can silently change what affected reports.

Before you copy any configuration, check the generator names, executor names and plugin options against the documentation for the version you pinned. Recent releases have changed how targets are inferred and how multi-module workspaces are handled, and older examples can be misleading.

Register each deployable service (typically under cmd/ or services/) and each shared library under internal/ or pkg/ as its own Nx project. You can rely on the plugin's inference or add an explicit project.json with a root pointing at the package directory. Explicit files cost more to maintain, but they make project boundaries visible in review.

Define build, test and lint targets that wrap the ordinary toolchain: go build, go test and go vet (or your linter) scoped to that project's package path. Nx then caches and orchestrates the commands without replacing them. A developer who never installs Node can still run go build ./... and go test ./... from the root and get the same result.

# Run from the repository root, next to go.mod or go.work.
# Pin exact versions with no caret range. Replace X.Y.Z with the release whose docs you checked.
npm install --save-dev --save-exact nx@X.Y.Z @nx-go/nx-go@X.Y.Z

# Register a shared library explicitly so its boundary is visible in code review.
# nx:run-commands is Nx's built-in executor. Each target wraps the plain Go
# toolchain, scoped to this project's package path.
mkdir -p internal/payments
cat > internal/payments/project.json <<'EOF'
{
  "name": "payments",
  "root": "internal/payments",
  "projectType": "library",
  "targets": {
    "build": {
      "executor": "nx:run-commands",
      "options": { "command": "go build ./internal/payments/..." }
    },
    "test": {
      "executor": "nx:run-commands",
      "options": { "command": "go test ./internal/payments/..." }
    },
    "lint": {
      "executor": "nx:run-commands",
      "options": { "command": "go vet ./internal/payments/..." }
    }
  }
}
EOF

# Nx orchestrates and caches the targets.
npx nx run payments:test

# Developers without Node use the same toolchain directly and get the same result.
go build ./...
go test ./...

Installs Nx and nx-go at exact versions, then registers internal/payments as an Nx project whose build, test and lint targets call go build, go test and go vet, so plain Go commands from the root keep working without Nx.

How does nx-go build the project graph from Go imports?

For each project, nx-go reads the module path from go.mod, or the module paths listed in go.work. It then parses the import declarations in the project's .go files. When an import path falls under a directory that Nx knows as another project, Nx adds an edge from the importer to that project. Standard library and third-party imports are ignored, because they don't resolve to a project in the workspace. Changes to third-party dependencies show up through go.mod and go.sum instead.

Run nx graph to check the result. Focus on a shared package with nx graph --focus=<project> and confirm that every service importing it appears as a dependent. If a service is missing, the usual causes are a mismatched module path, a package outside any registered project root, or an import that exists only in a file the parser skipped.

Imports describe compile-time Go dependencies. They miss these:

Dependency Why imports miss it Fix
go:embed files Files are not Go source Add the embedded paths to the project's inputs
Files behind build tags The only importing file may be excluded for some tag sets Check the graph; add implicitDependencies if the edge is absent
cgo headers and C sources .h/.c files are not parsed for imports Add them to inputs
Generated code The real source is .proto or a schema Make generation a target, use dependsOn, and list the schema in inputs
Config read at runtime Loaded by path, not imported Add the config files to inputs
Network integration tests Services talk over HTTP or gRPC, not imports Add implicitDependencies on the called services
# 1. Inspect the inferred graph around a shared package.
nx graph --focus=shared-auth

# Export the graph as JSON and list every project that depends on shared-auth.
nx graph --file=graph.json
jq -r '.graph.dependencies | to_entries[]
  | select(any(.value[]; .target == "shared-auth")) | .key' graph.json

# 2. Add the edges and inputs that Go imports cannot express.
cat > services/orders/project.json <<'EOF'
{
  "name": "orders",
  "implicitDependencies": ["payments", "inventory"],
  "targets": {
    "generate": {
      "executor": "nx:run-commands",
      "inputs": ["{projectRoot}/proto/**/*.proto"],
      "outputs": ["{projectRoot}/gen"],
      "options": { "command": "buf generate", "cwd": "services/orders" }
    },
    "build": {
      "dependsOn": ["generate", "^build"],
      "inputs": [
        "default", "^default",
        "{projectRoot}/static/**/*",
        "{projectRoot}/cgo/**/*.{h,c}",
        "{projectRoot}/config/*.yaml"
      ]
    },
    "test": {
      "dependsOn": ["generate"],
      "inputs": ["default", "^default", "{projectRoot}/config/*.yaml"]
    }
  }
}
EOF
# implicitDependencies: payments and inventory are called over gRPC in integration tests.
# static/: go:embed files. cgo/: C headers and sources. config/: read at runtime.
# generate: .proto is the real source, so build and test wait for regeneration.

Checks shared-auth's dependents with nx graph and jq, then adds a project.json with implicitDependencies for network calls, a generate target with dependsOn, and inputs for embed, cgo and config files.

Which task inputs does Nx need so Go results are not stale?

A Nx cache hit replays a task's stored output without running it, so the hash must cover everything that can change the result. For Go, a production named input built only from {projectRoot}/**/*.go is not enough. Add these:

  • Module files: go.mod, go.sum and, in multi-module layouts, {workspaceRoot}/go.work.
  • Embedded assets: any files pulled in by //go:embed. They are compiled into the binary but are not .go files.
  • Test fixtures: testdata/**. Include it in the test target's inputs and exclude it from production inputs so fixture edits don't invalidate builds.
  • Generation sources: .proto files, OpenAPI specs or sqlc queries that produce committed Go code.

Also declare GOOS, GOARCH and CGO_ENABLED as env inputs. Without them, a Linux binary from the remote cache can be restored on a macOS runner, or a cgo build can be restored where a static binary was expected.

The two caches work at different levels. Nx decides whether go build or go test runs at all. If it runs, Go still reuses compiled packages and earlier passing test results inside that run. A "fresh" Nx run can therefore print cached ok lines from Go. To force real execution, combine --skip-nx-cache with go test -count=1.

For go.mod, go.sum and go.work you have two choices:

  • Treat them as global inputs. Every project retests when any of them changes. This is safe but slower.
  • Scope them to the owning module. This is faster, but a dependency bump that another module picks up through go.work can go untested.

Start with global inputs and narrow the scope only when CI time becomes a real problem.

{
  "namedInputs": {
    "goEnv": [
      { "env": "GOOS" },
      { "env": "GOARCH" },
      { "env": "CGO_ENABLED" }
    ],
    "goModules": [
      "{workspaceRoot}/go.work",
      "{workspaceRoot}/**/go.mod",
      "{workspaceRoot}/**/go.sum"
    ],
    "default": [
      "{projectRoot}/**/*.go",
      "{projectRoot}/**/testdata/**",
      "{projectRoot}/assets/**",
      "{projectRoot}/**/*.proto",
      "{projectRoot}/**/*.sql"
    ],
    "production": [
      "default",
      "!{projectRoot}/**/*_test.go",
      "!{projectRoot}/**/testdata/**"
    ]
  },
  "targetDefaults": {
    "build": {
      "cache": true,
      "inputs": ["production", "^production", "goModules", "goEnv"]
    },
    "test": {
      "cache": true,
      "inputs": ["default", "^production", "goModules", "goEnv"]
    }
  }
}

An nx.json sketch that hashes Go sources, embedded assets, generation sources, testdata, global go.mod/go.sum/go.work files and GOOS/GOARCH/CGO_ENABLED, excluding tests and fixtures from build inputs.

How do you run nx affected locally and in CI?

Suppose libs/auth changes and two services, api and worker, import it, while billing does not. Running nx affected -t test --base=origin/main --head=HEAD should test libs/auth, api, and worker, and skip billing. Run nx affected -t build with the same refs and confirm that billing is absent from the task list. Nx finds the merge base between the two refs, maps the changed files to projects, and then follows the project graph to their dependents. If billing shows up, an input is too broad. If worker is missing, the import edge was not detected.

CI setup

In CI, set both refs explicitly instead of relying on defaults. You can pass --base and --head as flags or set the NX_BASE and NX_HEAD environment variables.

  • Pull requests: use the target branch as the base and the PR commit as the head.
  • Main branch: use the last commit that passed CI as the base, not HEAD~1. A failed run then gets retested on the next push instead of being skipped.

Git history

Most CI systems clone shallowly by default. Without enough history, Nx cannot compute a merge base. Depending on the setup, it will either fail or diff against the wrong commit, which selects every project or none. Fetch full history, or at least deep enough to reach the base.

Merge queues and rebase workflows cause similar problems. A merge queue tests a temporary merge commit. A force-push after a rebase can make a stored base SHA unreachable. Check that the base resolves before trusting an empty result.

Full-run backstop

The affected graph is only as good as its inputs. Schedule a full go test ./... across every module, either nightly or on each merge to main, to catch anything the graph missed.

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

That backstop is also the first argument against Nx. If you still need a full run to trust the results, measure how much the affected filter saves before you take on its cost.

In a pure Go repository, Nx adds Node.js, a package manager, a lockfile and a node_modules tree that Go engineers did not ask for. nx-go is a community plugin, so its release schedule is separate from Nx core. Each Nx upgrade means checking plugin compatibility on CI images and on every developer machine. The worst failure is quiet. If the graph misses an edge, Nx skips a suite and exits zero, which looks exactly like a pass.

Approach What decides what runs Extra tooling Main risk
Plain go test ./... Go's build and test cache, keyed on actual inputs None Slower cold runs; no cross-language orchestration
Script using git diff plus go list Your mapping of changed files to packages and their reverse dependents Shell or a small Go program Edge cases you have to maintain yourself (embeds, build tags, go.mod)
Nx with nx-go Project graph inferred from imports, plus declared inputs Node.js, Nx, plugin Stale inputs or missing edges cause silent skips
Hermetic build systems Explicitly declared dependencies per target Their own rule sets and build files High adoption and migration cost

If Go's cache already makes repeat runs fast, plain tooling is often enough.

Verification checklist

  • Change a leaf package. Only its own project should be affected, plus any apps that import it.
  • Change a shared package. Every project that imports it, directly or transitively, should be affected.
  • Change go.mod (bump a dependency). Every project in that module should be affected.
  • For each case, compare the affected list with the projects that fail when you break the change on purpose.

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 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.