Why does a hand-maintained CODEOWNERS file rot in an Nx monorepo?

A CODEOWNERS file maps path patterns to the GitHub users or teams responsible for them. When a pull request touches a matching path, GitHub automatically requests a review from those owners. If branch protection requires code owner review, the PR cannot merge until one of them approves. In a multi-team repository, this is how you guarantee that the payments team sees changes to payments code, even when another team opens the PR.

The file is easy to start and hard to keep accurate. It is a flat list of glob patterns, and nothing ties those patterns to the code they describe. In an Nx monorepo, projects change shape all the time:

  • A generator scaffolds a new library under libs/ and nobody adds a line for it.
  • A project is moved or renamed, and its old path stays in CODEOWNERS while the new path matches nothing.
  • A broad catch-all rule placed later in the file silently overrides a specific one, because GitHub uses the last matching pattern.

None of these mistakes cause errors. Reviews just stop being requested from the right people, and nobody notices until something ships without review.

Nx already knows where every project lives. Each project declares its root, and the project graph resolves all of them. Ownership is a property of the project, so it should be declared next to that project's configuration, and CODEOWNERS should be generated from the graph instead of edited by hand.

This approach is most useful for platform and backend teams running Nx repositories shared by several teams, where projects move faster than any one person can track.

Should you declare ownership with tags or a dedicated project field?

Both approaches work. The real choice is whether ownership should share a namespace with your dependency rules.

Option A: an owner: tag

Add a tag such as "tags": ["scope:billing", "type:data-access", "owner:team-payments"] to the project's project.json. Nx already exposes tags in the project graph, and most teams already understand the key:value convention from enforce-module-boundaries. The generator needs nothing new.

The cost is coupling. Tags are what your lint constraints match on. Someone may later write a rule keyed on owner:*, or treat ownership and scope: as interchangeable. Once that happens, a reorganization that moves a project between teams can start failing boundary checks or loosening them, and the reviewer sees both changes in one diff.

Option B: a dedicated field

Add a separate property, for example "owners": ["@acme/payments"], next to tags in project.json. Your lint rules never read it, so changing the owner cannot alter dependency rules. You can also store GitHub team handles directly instead of mapping tag values to handles. Before relying on this, confirm that your Nx version keeps the custom property in the graph node data. If it doesn't, have the generator read project.json directly.

Concern owner: tag Dedicated field
Visible in project graph Yes Verify for your version
Affects boundary lint Can, if rules match it No
Maps to GitHub handles Needs a lookup table Direct
Familiarity High Needs documenting

Pick one approach and document it in the repository's contributing guide. A generator that has to accept both formats will eventually disagree with itself.

# Option A: libs/billing/data-access/project.json
# Ownership rides on the tags namespace that enforce-module-boundaries reads.
{
  "name": "billing-data-access",
  "sourceRoot": "libs/billing/data-access/src",
  "projectType": "library",
  "tags": ["scope:billing", "type:data-access", "owner:team-payments"]
}

# Generator still needs a lookup: owner:team-payments -> @acme/payments

# Option B: libs/billing/data-access/project.json
# Ownership lives in its own field. Lint rules never read it, and it
# stores the GitHub team handle directly.
{
  "name": "billing-data-access",
  "sourceRoot": "libs/billing/data-access/src",
  "projectType": "library",
  "tags": ["scope:billing", "type:data-access"],
  "owners": ["@acme/payments"]
}

# Check that your Nx version keeps "owners" in the graph node data.
# If it doesn't, have the generator read project.json directly.

The same library's project.json written both ways: ownership as an owner: tag next to the boundary tags, or as a separate owners field that holds GitHub team handles and stays out of lint rules.

How does generating CODEOWNERS from the Nx project graph work?

The generator is a short pipeline that runs in four steps.

1. Read the graph. Running nx graph --file=graph.json writes the project graph to disk without opening the browser UI. Inside a Node script, you can use the project graph functions exported by @nx/devkit instead. Both the JSON shape and the API names have changed across Nx releases, so check them against the version pinned in your workspace before you depend on a particular field path.

2. Extract name, root and owner. Each project node gives you its name, its root directory, and its metadata. The owner comes from a tag or a custom field, depending on the convention you chose earlier. If a project has no owner, the generator should fail loudly. Skipping it silently means the default team inherits that project without anyone noticing.

3. Map to CODEOWNERS syntax. A root such as libs/payments becomes the pattern /libs/payments/. The leading slash anchors the pattern to the repository root, and the trailing slash matches everything beneath that directory. A short owner value such as payments becomes @acme/payments-team through a lookup table. That keeps GitHub handles in one place, so a team rename means editing one entry instead of every project.

4. Merge and write. Read the hand-written header from the existing .github/CODEOWNERS, keep it verbatim, and append the generated block underneath it.

The ordering of lines matters because GitHub applies the last matching pattern, not the most specific one. A catch-all * @acme/platform must therefore go at the top, where any project rule further down overrides it. Nested roots follow the same logic. If libs/payments/api is its own project, its line must come after /libs/payments/, or the parent rule will win. Sorting entries by path depth, then alphabetically, gives you that order and keeps diffs stable between runs.

+-------------------------------+   +-------------------------------+
| nx graph --file=graph.json    |   | @nx/devkit project graph API  |
+---------------+---------------+   +---------------+---------------+
                |                                   |
                +-----------------+-----------------+
                                  v
              +---------------------------------------+
              | 1. Read graph (check your Nx version) |
              +-------------------+-------------------+
                                  v
              +---------------------------------------+
              | 2. Extract name, root, owner          |
              |    no owner? --> fail the run         |
              +-------------------+-------------------+
                                  v
+-----------------+   +---------------------------------------+
| owner lookup    |-->| 3. libs/payments -> /libs/payments/   |
| payments ->     |   |    payments -> @acme/payments-team    |
| @acme/payments- |   +-------------------+-------------------+
| team            |                       v
+-----------------+   +---------------------------------------+
+-----------------+   | 4. Sort: catch-all first, parents     |
| static header   |-->|    before nested roots; merge header  |
| (kept verbatim) |   +-------------------+-------------------+
+-----------------+                       v
              +---------------------------------------+
              | .github/CODEOWNERS (last match wins)  |
              |   * @acme/platform                    |
              |   /libs/payments/      @acme/pay-team |
              |   /libs/payments/api/  @acme/api-team |
              +---------------------------------------+

The generator reads the Nx project graph, maps each project root and owner to a CODEOWNERS line, and writes the file below a preserved header. The catch-all goes first and nested roots follow their parents because GitHub applies the last matching pattern.

Implementing the generator script

The script has four jobs: load the graph, validate ownership, order the rules, and write the file. Load the graph with createProjectGraphAsync from @nx/devkit so it reflects the same project inference your builds use. Do not glob for project.json files, which misses inferred projects. For each node, read data.root and the owner you declared in the previous step. Collect every project without an owner and fail with one error that lists all of them. Reporting one at a time forces engineers through repeated CI runs.

Turn each root into an anchored directory pattern such as /libs/payments/api/. Sort by segment count, then by path string. Only the depth order matters to GitHub. The alphabetical tiebreak keeps output byte-identical across machines. Normalize separators to forward slashes, end with one trailing newline, and leave out timestamps. That way the CI diff check only fires on real changes.

Keep a hand-written header above a generated marker. It covers root config files, .github/workflows/, tooling directories, and the generator script itself. The script copies the header unchanged and regenerates only the content below the marker.

Add a fixture test with nested projects at libs/payments and libs/payments/api. Assert that the child line comes later and that a missing owner throws.

GitHub constraints the script cannot check for you:

  • The file must live in the repository root, .github/, or docs/.
  • Owners need write access to the repository, and teams must be visible.
  • There is no negation syntax.
  • Invalid lines are skipped silently.

After merging, open the file on GitHub, which shows errors for lines it could not parse.

// tools/codeowners.js: run with `node tools/codeowners.js`, then let CI fail on `git diff --exit-code`
const { createProjectGraphAsync } = require('@nx/devkit');
const fs = require('node:fs');
const FILE = '.github/CODEOWNERS';
const MARKER = '# --- generated by tools/codeowners.js: edit only above this line ---';
const cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0); // locale-independent, so output is byte-identical everywhere

function buildRules(nodes) {
  const missing = [], rules = [];
  for (const { name, data } of nodes) {
    const root = data.root.replace(/\\/g, '/').replace(/^\/+|\/+$/g, '');
    if (root === '' || root === '.') continue; // the root project is covered by the hand-written header
    const owners = (data.tags ?? []).filter((t) => t.startsWith('owner:')).map((t) => t.slice(6));
    if (owners.length === 0) { missing.push(name); continue; }
    rules.push({ root, line: `/${root}/ ${owners.sort(cmp).join(' ')}` });
  }
  // Report every unowned project at once instead of failing on the first one
  if (missing.length) throw new Error(`Projects without an owner tag:\n  ${missing.sort(cmp).join('\n  ')}`);
  const depth = (r) => r.root.split('/').length;
  // Shallow first so nested projects override their parents (GitHub uses the last matching line)
  return rules.sort((a, b) => depth(a) - depth(b) || cmp(a.root, b.root)).map((r) => r.line);
}

async function main() {
  const graph = await createProjectGraphAsync(); // same inference as your builds, so no globbing for project.json
  const current = fs.readFileSync(FILE, 'utf8');
  const at = current.indexOf(MARKER);
  if (at === -1) throw new Error(`${FILE} is missing the generated marker line`);
  const lines = buildRules(Object.values(graph.nodes));
  fs.writeFileSync(FILE, current.slice(0, at) + MARKER + '\n' + lines.join('\n') + '\n');
}
module.exports = { buildRules };
if (require.main === module) main().catch((e) => { console.error(e.message); process.exit(1); });

// tools/codeowners.test.js: run with `node --test tools/`
// const test = require('node:test'); const assert = require('node:assert'); const { buildRules } = require('./codeowners');
// const node = (name, root, tags) => ({ name, data: { root, tags } });
// test('child after parent', () => assert.deepStrictEqual(buildRules([node('pay-api', 'libs/payments/api', ['owner:@acme/pay-api']), node('pay', 'libs/payments', ['owner:@acme/pay'])]), ['/libs/payments/ @acme/pay', '/libs/payments/api/ @acme/pay-api']));
// test('missing owner throws', () => assert.throws(() => buildRules([node('orphan', 'libs/orphan', [])]), /orphan/));

A Node generator that reads owner: tags from the Nx project graph, reports all unowned projects in a single error, sorts anchored rules by depth and then by path, and rewrites only the part of .github/CODEOWNERS below the marker; a nested-layout fixture test is shown in the trailing comments.

How do you keep CODEOWNERS in sync and enforced in CI?

Add a CI job that runs the generator and then runs git diff --exit-code against the CODEOWNERS path. If someone adds a project, renames a root, or changes an owner field without regenerating, the job fails and the diff in the log shows the exact lines that need to change. This turns drift into a merge blocker instead of something found months later. git diff ignores untracked files, so commit the file before you enable the check. The generator should also exit non-zero when any project has no owner. A silent gap means GitHub requests no reviewer for that path, and the gap is easy to miss.

Then enable Require review from Code Owners in branch protection or in a ruleset on the default branch. Without that setting, CODEOWNERS only requests reviewers and does not block merges. With it enabled, a PR that touches three projects owned by three teams needs an approval from each matched owner set. Plan for this before the first wide refactor lands.

The check has a runtime cost. Computing the project graph runs every inference plugin, which can take a noticeable share of a short CI job in a large workspace. Run it only when project configuration, nx.json, or the generator itself changes, or reuse a graph your pipeline already computes.

Inference also causes churn. A plugin config change that moves project roots can rewrite dozens of CODEOWNERS lines in one PR. Review those diffs as ownership changes, not as formatting noise.

Finally, give the generator script, nx.json, and CODEOWNERS itself to the platform team. Anyone who can edit the generator can reassign every path in the repository.

# .github/workflows/codeowners.yml
name: codeowners

on:
  pull_request:
    # Only pay for project graph computation when ownership inputs change.
    # Add the config files your inference plugins read (e.g. vite.config.ts).
    paths:
      - 'nx.json'
      - '**/project.json'
      - '**/package.json'
      - 'tools/scripts/generate-codeowners.mjs'
      - '.github/CODEOWNERS'

jobs:
  codeowners-drift:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: npm
      - run: npm ci

      # The generator reads the project graph, rewrites .github/CODEOWNERS,
      # and exits non-zero if any project has no owner.
      - name: Regenerate CODEOWNERS
        run: node tools/scripts/generate-codeowners.mjs

      # Fail if the committed file differs from the generated one; the diff
      # in the log shows the exact lines to fix. CODEOWNERS must already be
      # committed, because git diff ignores untracked files.
      - name: Fail on drift
        run: git diff --exit-code -- .github/CODEOWNERS

A GitHub Actions workflow that runs only when ownership inputs change. It regenerates CODEOWNERS from the Nx project graph and fails the PR if the committed file has drifted or a project has no owner.

When should you avoid relying on graph-generated CODEOWNERS?

The generated file inherits every limit of CODEOWNERS itself, and a few of its own.

Ownership follows paths, not dependency edges. GitHub matches changed files against patterns. It never reads the project graph. A change to libs/shared/auth requests review only from that library's owners, even if the change breaks a dozen consuming applications. Generating the file from the graph does not change this. Cover the consumer side with affected test runs. If consumer teams need a say, add a separate check that comments on the PR and mentions them.

Cross-cutting changes stall. A framework migration, a lint rule rollout, or a root dependency bump touches many projects at once. With required code owner reviews, that one PR waits on approval from every team. Plan for this before it happens. You can split the change into PRs scoped to each owner. Or you can document a bypass, such as an admin merge or a platform-owned path, with a record of who used it and why.

Ordering bugs are silent. When several patterns match a file, GitHub applies the last matching one. If the generator sorts entries wrongly, a broad pattern can override a specific one. Nothing fails, and reviews simply go to the wrong team.

Handles rot quietly. A team that is renamed or deleted in GitHub stays valid in project.json. Your sync check compares files and passes. Validate handles against the organisation separately.

Small repos don't need this. With a handful of projects and two teams, a hand-written file is shorter than the script that generates it.

What are the alternatives, and how do they affect cost and engineering time?

Four approaches cover most teams. They differ mainly in who pays the upkeep and when.

Approach Blocks merges? Upfront cost Ongoing cost Main failure mode
Hand-maintained CODEOWNERS Yes, via branch protection None Every project add, move or team change Silent drift and stale routing
Generated from project graph Yes Writing and testing the script Script upkeep when the project config schema changes Bugs in the generator spread to every rule
Affected-owners PR comment No, informational only A CI job plus a comment step Low. It reuses the same ownership metadata Comments get ignored as noise
First-party Nx ownership feature Depends on configuration Adoption and config migration Tied to the Nx upgrade cadence Licensing or capability gaps for your setup

The affected-owners comment complements the generator. CODEOWNERS only maps paths to reviewers. A comment that lists the owners of downstream dependents tells a team that a change to a shared library touches their service, and it does this without making them required reviewers on every PR.

For the first-party option, check what your installed Nx version actually supports. Confirm whether it emits a GitHub-compatible file and how ownership is declared. Also check whether it requires a paid or registered licence. Don't assume any of these from older documentation.

To judge whether the generator pays off, compare two costs:

  • Script cost: the time to build it plus the time to maintain it each year.
  • Avoided cost: how many PRs per period get routed to the wrong reviewer or to nobody, multiplied by the delay and the follow-up each one causes. Add the time saved when new projects get correct owners automatically.

If the avoided cost per period exceeds the script cost spread over the same period, the generator is worth building.

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