What is Nx CODEOWNERS generation, and why does a hand-edited file drift?

Nx CODEOWNERS generation treats ownership as project metadata rather than a list of path patterns. Each Nx project carries a tag such as owner:payments or owner:platform-infra. A small script reads the project graph and writes the CODEOWNERS file from it. The file becomes a build artifact. Nobody edits it by hand, and it is regenerated whenever projects change.

A hand-maintained file rots because it encodes paths, and paths in a monorepo are not stable. Teams move a library from libs/billing to libs/payments/billing, split one project into three, or rename a folder during a cleanup. GitHub does not raise an error when a CODEOWNERS pattern matches nothing. The rule stays in the file, and the new location falls through to a broad catch-all entry or has no owner at all. Nobody notices until a pull request merges without the right reviewer, or a team gets paged for code it no longer owns.

Ownership often already lives in Nx. Teams that use scope: and type: tags for module boundary rules have described who owns what in project configuration. Keeping a second copy in CODEOWNERS means two sources of truth, and the copy nobody checks is the one that falls behind.

Platform teams running multi-team monorepos with consistent tagging gain the most from this approach. The time saved comes from two places:

  • Nobody spends review cycles fixing path patterns after a refactor.
  • Fewer pull requests are routed to the wrong team or merged with no owner review at all.

How should you design an owner tag convention for Nx projects?

Use a dedicated tag prefix, owner:<github-team-slug>, and keep it separate from the scope: and type: tags you may already use with module boundary rules. Scope tags describe the architecture: which projects may depend on which. Owner tags describe people: who must approve a change. These two change on different schedules. A team reorganisation should not force you to edit lint constraints, and splitting a domain into two libraries should not quietly reassign reviewers.

Aspect scope: tags owner: tags
Answers What may this project depend on? Who approves changes here?
Read by Module boundary lint rule CODEOWNERS generator
Changes when Architecture changes Teams reorganise
Typical count per project One One or more

Do not put @org/payments directly in the tag. Keep a small mapping file at the workspace root that maps each tag value to a GitHub team handle, so payments maps to @org/payments. This gives you one place to update when a team is renamed. It also gives the generator a closed list to validate against, so a typo like owner:paymnets fails the build. Without that list, the typo would produce a CODEOWNERS entry that GitHub silently ignores.

Make two decisions before the first tag lands:

  • Multiple owners: allow repeated owner: tags. Emit every mapped handle on the same CODEOWNERS line, sorted, so the output is stable. GitHub treats them as alternatives: approval from any one listed owner is enough.
  • Unowned projects: never let a missing tag mean "nobody." Require an explicit owner:unowned that maps to a fallback team, and fail generation for projects that have no owner tag at all.
// owners.json at the workspace root is the closed list of valid owner tag values:
// { "payments": "@org/payments", "checkout": "@org/checkout", "unowned": "@org/platform" }
import { readFileSync } from 'node:fs';

const ownerMap: Record<string, string> = JSON.parse(
  readFileSync('owners.json', 'utf8'),
);

// Resolve one project's tags to a sorted, de-duplicated list of GitHub team handles.
export function resolveOwners(project: string, tags: string[] = []): string[] {
  // Only owner: tags matter here. scope: and type: tags belong to module boundary rules.
  const values = tags
    .filter((t) => t.startsWith('owner:'))
    .map((t) => t.slice('owner:'.length));

  // A missing owner tag is an error, not "nobody owns this".
  if (values.length === 0) {
    throw new Error(`${project}: no owner: tag (use owner:unowned explicitly)`);
  }

  const handles = values.map((v) => {
    const handle = ownerMap[v];
    // A typo like owner:paymnets fails here instead of producing an entry GitHub ignores.
    if (!handle) throw new Error(`${project}: unknown owner "${v}" (not in owners.json)`);
    return handle;
  });

  // Sorting keeps generated CODEOWNERS lines stable across runs.
  return [...new Set(handles)].sort();
}

// Example:
// resolveOwners('payments-feature-refunds',
//   ['scope:payments', 'type:feature', 'owner:payments', 'owner:checkout'])
// -> ['@org/checkout', '@org/payments']

A resolver that maps a project's owner: tags to GitHub team handles through a root owners.json file, rejects unknown or missing owners, and returns a sorted list for a stable CODEOWNERS line.

How does generating CODEOWNERS from the project graph work?

The generator is a small Node script that runs in four steps, each feeding the next. The pipeline also defines where a failure should surface.

project graph ──► tags ──► tag→team map ──► overrides ──► CODEOWNERS ──► CI diff check
 (devkit API)    owner:*    owners.json      overrides.json   sorted file    fail if stale

Read the graph, not the filesystem

Load the project graph through the devkit API, using createProjectGraphAsync from @nx/devkit, instead of globbing for project.json files. Nx can infer projects from package.json files and plugins, so a glob misses projects that have no project.json. It can also pick up stale config in directories Nx ignores. The graph gives you each project's root and tags exactly as Nx resolves them, which are the same values nx affected and module-boundary lint rules use.

Exposed APIs and output shapes have changed across Nx releases. Before you commit to an approach, check what your installed version offers. If the devkit function isn't available or behaves differently, nx graph --file=<path>.json or nx show projects --json combined with nx show project <name> --json can supply the same data.

Map, merge, emit

For each project, find its owner:* tag and resolve it through the tag-to-team mapping to one or more GitHub teams. Then apply overrides for paths that aren't projects, such as workspace config, CI files and tools/. Overrides are applied last so they win.

Emit one line per root, sorted by path. Stable ordering keeps diffs reviewable and makes the CI staleness check a plain byte comparison.

┌──────────────────────────┐
│ Nx project graph         │  createProjectGraphAsync (@nx/devkit)
│ inferred + explicit      │  fallback: nx graph --file=graph.json
└────────────┬─────────────┘
             │ root + tags per project
             ▼
┌──────────────────────────┐
│ Extract owner:* tags     │  no owner:* tag → error
└────────────┬─────────────┘
             │ project root → owner:<x>
             ▼
┌──────────────────────────┐     ┌──────────────────┐
│ Resolve tag → team(s)    │◄────┤ owners.json      │
└────────────┬─────────────┘     └──────────────────┘
             │ project root → @org/team ...
             ▼
┌──────────────────────────┐     ┌──────────────────┐
│ Apply overrides (last)   │◄────┤ overrides.json   │
└────────────┬─────────────┘     │ config, CI, tools│
             │                   └──────────────────┘
             ▼
┌──────────────────────────┐
│ Emit CODEOWNERS          │  one line per root, sorted by path
└────────────┬─────────────┘
             ▼
┌──────────────────────────┐
│ CI: regenerate and       │  bytes differ → fail (stale file)
│ compare to committed     │
└──────────────────────────┘

The generator reads project roots and tags from the Nx project graph, resolves owner: tags to teams through owners.json, applies path overrides last, writes a sorted CODEOWNERS file, and CI fails when the committed file differs from a fresh run.*

Implementing the generator: deterministic output, ordering and overrides

Start the file with a header comment such as # GENERATED by tools/scripts/codeowners.mjs — do not edit; run the generator instead, so a reviewer who opens it knows where to make changes. Next comes the catch-all * @acme/platform. GitHub applies the last matching pattern, so the catch-all must come first. That way anything a later rule doesn't claim still has an owner.

The script loads the graph with createProjectGraphAsync from @nx/devkit, reads each project's root and its owner: tags, and maps each tag to a team handle. Sort rules by path depth, then by path using plain code-point comparison rather than localeCompare. Depth ordering puts libs/billing/ before libs/billing/invoices/, so the nested project's rule wins. Code-point ordering gives the same output on every machine, whatever the locale. A project with no owner tag should fail the run instead of being skipped silently.

Append the overrides file last, in the order it is written. It covers paths no project owns: nx.json, package.json, the lockfile, .github/workflows/, tools/ (including generators), and tsconfig.base.json.

Sample output for a nested root:

  • * @acme/platform
  • /apps/api/ @acme/core-api
  • /libs/billing/ @acme/payments
  • /libs/billing/invoices/ @acme/invoicing
  • /nx.json @acme/platform
  • /.github/workflows/ @acme/platform
  • /tools/ @acme/platform

Write each root with a leading slash so the rule matches only at the repository root. Without it, libs/billing/ would also match any nested directory with that path.

// tools/scripts/codeowners.mjs: run with `node tools/scripts/codeowners.mjs`
import { createProjectGraphAsync } from '@nx/devkit';
import { readFileSync, writeFileSync } from 'node:fs';

const graph = await createProjectGraphAsync();
const rules = [];
for (const [name, node] of Object.entries(graph.nodes)) {
  const root = node.data.root.replace(/\/+$/, '');
  if (root === '.') continue; // a workspace-root project is covered by the catch-all
  // Map each tag such as owner:payments to the team handle @acme/payments
  const owners = (node.data.tags ?? [])
    .filter((t) => t.startsWith('owner:'))
    .map((t) => `@acme/${t.slice('owner:'.length)}`)
    .sort();
  if (owners.length === 0) throw new Error(`Project "${name}" has no owner: tag`);
  rules.push({ path: `/${root}/`, owners }); // leading slash anchors the rule to the repo root
}

// Parents come before nested roots, because GitHub applies the last matching rule.
// Ties are broken by code-point order, so the output does not depend on the locale.
const depth = (p) => p.split('/').length;
rules.sort((a, b) => depth(a.path) - depth(b.path) || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));

// The hand-maintained overrides are appended last, in the order they are written in the file.
const overrides = readFileSync('tools/codeowners.overrides', 'utf8')
  .split('\n').map((l) => l.trim()).filter((l) => l && !l.startsWith('#'));

const lines = [
  '# GENERATED by tools/scripts/codeowners.mjs. Do not edit; run the generator instead.',
  '* @acme/platform', // the catch-all comes first so every later rule overrides it
  ...rules.map((r) => `${r.path} ${r.owners.join(' ')}`),
  ...overrides,
];
writeFileSync('.github/CODEOWNERS', lines.join('\n') + '\n');

// Sample output for a nested root:
// * @acme/platform
// /apps/api/ @acme/core-api
// /libs/billing/ @acme/payments
// /libs/billing/invoices/ @acme/invoicing
// /nx.json @acme/platform
// /package.json @acme/platform

A generator that reads root and owner: tags from the Nx project graph, sorts rules by depth and then by code point so nested roots follow their parents, and appends hand-maintained overrides after a catch-all owner.

How do you enforce CODEOWNERS in CI and on GitHub?

Build the drift check first

Enforcement starts in CI, not on GitHub. Add a job that runs the generator and then git diff --exit-code on the CODEOWNERS path. A non-zero exit means someone hand-edited the file or changed project tags without regenerating, and the job fails. Have the generator fail on its own in two more cases: a project with no owner tag, and an owner tag with no mapped team. Without those checks, a new library ships with no owner and the gap goes unnoticed until someone needs a review.

To keep CI failures rare, regenerate locally. A pre-commit hook works, as does a sync-style step that developers run alongside other workspace codegen. CI stays the backstop, because hooks can be skipped.

Make GitHub honor the file

GitHub reads CODEOWNERS from .github/, the repository root or docs/, and uses the first one it finds. Keep exactly one copy so you never edit a file GitHub ignores.

The file only routes review requests until you require code owner approval. Turn that on through branch protection or a ruleset on your default branch.

Each referenced team needs write access to the repository. GitHub silently skips entries for teams without it, so a path can look owned and still merge without that team's approval. After changes, open the file in the GitHub UI. GitHub flags invalid or unknown owners there, which catches typos and access gaps that your generator cannot see.

# .github/workflows/codeowners-drift.yml
# Fails the PR if CODEOWNERS is out of sync with Nx project tags.
name: codeowners-drift

on:
  pull_request:
    branches: [main]

jobs:
  check:
    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 exits non-zero by itself when a project has no
      # owner tag or a tag maps to no team, so those cases fail here.
      - name: Regenerate CODEOWNERS
        run: node tools/scripts/generate-codeowners.mjs

      # Any diff means a hand edit or tags changed without regenerating.
      - name: Fail on drift
        run: |
          if ! git diff --exit-code -- .github/CODEOWNERS; then
            echo "CODEOWNERS is stale. Run the generator locally and commit the result."
            exit 1
          fi

A GitHub Actions job that regenerates CODEOWNERS from Nx project tags and uses git diff --exit-code to fail the pull request on drift, while the generator itself fails on missing or unmapped owner tags.

When should you avoid generated CODEOWNERS, and what does it cost?

Generated ownership solves routing, not impact. GitHub CODEOWNERS matches changed file paths, so a change to a shared library requests review from that library's owners but not from the teams whose apps depend on it. Keep nx affected and its tests as the impact check. CODEOWNERS only decides who approves.

Risk Why it happens Mitigation
Review fan-out Lockfile, nx.json or bulk refactors touch many owned paths Platform-owned root files; documented admin bypass
Generator breaks CI It is a build step with inputs and dependencies Few dependencies, explicit logging, fail loudly
Silent mis-assignment Last matching pattern wins, so one broad rule can shadow a narrower one Snapshot test on the generated output
Wrong owners Tags are stale or missing Lint rule that requires an owner tag
Bottleneck or rubber stamp Team is inactive, or so broad that nobody feels responsible Periodic audit of owner teams

Skip generation when the workspace has few projects or a single team. A hand-edited file of ten lines does not drift enough to justify a script.

Illustrative estimate (assumed numbers, not a benchmark)

Net hours per month = (PRs × minutes saved on routing ÷ 60) − script upkeep − (fan-out PRs × extra wait hours)

Assumed inputs:

  • 300 PRs per month
  • 3 minutes saved per PR on finding reviewers
  • 4 hours of script upkeep per month
  • 10 fan-out PRs per month, each waiting 1 extra hour

Net: (300 × 3 ÷ 60) − 4 − (10 × 1) = 15 − 4 − 10 = 1 hour per month

The result is small enough that a stricter fan-out policy decides whether the script is worth keeping. Plug in your own numbers before committing to it.

What are the alternatives, and how do you roll this out?

If the arithmetic doesn't favour the script, a hand-maintained file may be enough. Before you build anything, check whether your Nx edition, plugins or hosting platform already offer a supported ownership feature.

Option Source of truth Drift risk Ongoing cost
Hand-maintained CODEOWNERS The file itself High: renames and new projects go unnoticed Reviewer attention on every structural change
Custom generator from tags owner:* tags in project config Low, if CI checks for drift You own the script and its edge cases
First-party ownership feature Defined by the vendor Depends on the feature Licence or upgrade coupling; check before building

Once the tags exist, you can reuse them. The @nx/enforce-module-boundaries rule accepts depConstraints keyed on tags, so an owner:payments source can be restricted to depending on its own projects plus shared libraries. A CI step can also map the affected project list to owner tags and post a PR comment naming the teams a change touches. Both are advisory. Keep CODEOWNERS as the only thing that blocks a merge, so you have one enforcement path to debug and no conflicting rules.

Roll out in stages:

  1. Run the generator in report-only mode. Write to a temporary path and don't fail CI.
  2. Diff the output against the committed file. Each difference is either a missing tag or a stale entry.
  3. Backfill tags one team at a time. The owning team confirms each mapping.
  4. Make the drift check blocking, then turn on "Require review from Code Owners" in branch protection.

Do step 4 last. If you enable required review before the tags are accurate, PRs get blocked waiting on reviewers who no longer own the code.

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.