What is Nx CODEOWNERS generation and why does hand-written CODEOWNERS drift?
Nx CODEOWNERS generation treats the CODEOWNERS file as a build artifact. You don't edit it by hand. Each project declares its owners in its own metadata, next to its project.json or package.json, and a generator walks the Nx project graph and writes the rules. The file in .github/ becomes output, the same way a compiled bundle is output. Nobody edits it directly.
The reason is drift. A hand-maintained CODEOWNERS file stores ownership as a list of paths, while the monorepo is organized around projects. The two fall out of sync in predictable ways:
- Projects move. Someone renames
libs/billingtolibs/payments/billing. The old rule now matches nothing, and nothing in the move prompts anyone to update it. - New projects arrive without an owner. A team runs a generator, gets a new library, and merges it. No rule was ever written for that path.
In both cases GitHub doesn't warn you. A rule that matches no files is not an error. Files that lose their specific rule fall through to whatever broader pattern also matches, often a catch-all like * owned by a platform team, or no owner at all. Reviews still get requested, just from the wrong people. That can go unnoticed for months.
This approach helps platform and backend teams running Nx monorepos where several teams share one repository and branch protection requires code owner approval. The generator is a small script. The real value is that ownership lives on the project, moves with it, and gets checked in CI, so a missing or stale owner fails a build.
How do GitHub CODEOWNERS rules work?
GitHub looks for the file in three places: .github/CODEOWNERS, CODEOWNERS at the repository root, and docs/CODEOWNERS. It uses only the first one it finds, so a generator should write to a single location and CI should fail if a stray copy exists elsewhere. Otherwise reviewers may read one file while GitHub enforces another.
Each line is a path pattern followed by one or more owners. When several patterns match a changed file, the last matching line wins. Owners do not accumulate across lines. A broad catch-all near the bottom silently replaces every specific rule above it.
The pattern syntax looks like .gitignore, but it is not identical:
| Feature | .gitignore |
CODEOWNERS |
|---|---|---|
* and ** globs |
Supported | Supported |
! negation |
Supported | Not supported |
[a-z] character ranges |
Supported | Not supported |
| Precedence | Last match, with negation | Last match only |
Owners can be @username, @org/team-name, or an email address. Each one needs write access to the repository. If a listed team lacks write access, GitHub does not request its review, so the rule protects nothing.
The file only requests reviews. GitHub blocks a merge on owner approval only when branch protection or a ruleset requires Code Owner review on the target branch.
GitHub also caps the file's size and ignores it entirely past that limit. Emit one rule per project root instead of one rule per file.
CODEOWNERS matches paths only. It does not know that libs/auth is imported by twelve apps. Any dependency-aware ownership has to be resolved before the file is written.
# .github/CODEOWNERS (generated: edit project owners, not this file)
# Rules are evaluated top to bottom and the LAST matching line wins.
# Owners do not merge across lines, so put the broadest rule first.
# 1. Catch-all fallback. Must come first, or it overrides everything below.
* @acme/platform-team
# 2. One rule per project root. This keeps the file small and stable.
# The leading '/' anchors to the repo root. The trailing '/' covers
# every file under that directory.
/apps/storefront/ @acme/storefront-team
/apps/admin-portal/ @acme/admin-team
/libs/auth/ @acme/identity-team
/libs/ui-kit/ @acme/design-systems @jdoe
# 3. Narrower overrides go AFTER their parent so they win.
# Every listed owner is requested. Re-list identity-team here
# if it should still review this path.
/libs/auth/src/crypto/ @acme/security-team @acme/identity-team
# 4. Shared workspace config. Changes here affect every project.
/nx.json @acme/platform-team
/package.json @acme/platform-team
# Not valid in CODEOWNERS (gitignore-only syntax). Never emit these:
# !/libs/auth/README.md <- '!' negation is not supported
# /apps/[a-m]*/ <- '[ ]' ranges are not supported
# Wrong order (do not do this). A later catch-all replaces every rule above it:
# /libs/auth/ @acme/identity-team
# * @acme/platform-team <- now owns libs/auth too
# Reminder: these teams need write access, and a branch protection rule
# or ruleset must require Code Owner review before any of this blocks a merge.
A generated CODEOWNERS file with the catch-all first, one rule per project root, and narrower overrides placed after their parents, because the last matching line wins.
How does generating CODEOWNERS from the Nx project graph work?
That resolution happens at generation time, not at review time. The pipeline has four stages. Nx already knows each project's name, root directory and tags. You add a mapping config that ties those attributes to GitHub teams. A generator combines the two and writes CODEOWNERS. A CI check then regenerates the file and fails if the committed copy differs. The project graph becomes the source of truth, and CODEOWNERS becomes a build artifact you never edit by hand.
Route 1: the Nx owners plugin
Nx provides an owners plugin. You configure it in nx.json, and it runs as a sync generator. Because it runs as a sync generator, Nx can regenerate CODEOWNERS whenever the project graph changes, such as when a project is added, moved or retagged. You don't need a separate step that someone has to remember. The package name, licensing terms and configuration shape have changed over time, so check the current Nx documentation before you adopt it.
Route 2: a framework-agnostic script
If you can't use the plugin or prefer not to, write a script against the Nx CLI:
- Call
nx show projects --jsonto list every project name. - For each name, call
nx show project <name> --jsonto get itsrootandtags. - Look up an owner in your mapping and emit one rule anchored at that root, such as
/libs/auth/. - Sort the output deterministically. If the order is stable, the CI diff shows only real ownership changes and never noise from reordering.
#!/usr/bin/env node
// Generate .github/CODEOWNERS from the Nx project graph.
// Usage: node tools/generate-codeowners.js [--check]
const { execFileSync } = require('node:child_process');
const fs = require('node:fs');
// Mapping config: the first matching tag wins. Team handles are placeholders.
const TAG_OWNERS = [
['scope:auth', '@acme-org/identity-team'],
['scope:payments', '@acme-org/payments-team'],
['type:ui', '@acme-org/design-systems'],
];
const FALLBACK_OWNER = '@acme-org/platform-team';
const OUT = '.github/CODEOWNERS';
const nx = (...args) =>
JSON.parse(execFileSync('npx', ['nx', ...args], { encoding: 'utf8' }));
const rules = nx('show', 'projects', '--json')
.map((name) => {
const { root, tags = [] } = nx('show', 'project', name, '--json');
const match = TAG_OWNERS.find(([tag]) => tags.includes(tag));
return { root, owner: match ? match[1] : FALLBACK_OWNER };
})
.filter((r) => r.root && r.root !== '.') // the workspace root is owned by a separate catch-all rule
// Plain code-unit sort keeps output stable across machines and puts parents before
// nested children, so the more specific rule comes later and wins (last match wins).
.sort((a, b) => (a.root < b.root ? -1 : a.root > b.root ? 1 : 0));
const content = [
'# GENERATED FILE - do not edit. Run: node tools/generate-codeowners.js',
`* ${FALLBACK_OWNER}`,
...rules.map((r) => `/${r.root}/ ${r.owner}`),
].join('\n') + '\n';
if (process.argv.includes('--check')) {
const current = fs.existsSync(OUT) ? fs.readFileSync(OUT, 'utf8') : '';
if (current !== content) {
console.error(`${OUT} is out of date. Regenerate it and commit the result.`);
process.exit(1);
}
} else {
fs.writeFileSync(OUT, content);
}
A framework-agnostic Node script that reads project names, roots and tags from nx show projects --json and nx show project <name> --json, maps tags to placeholder GitHub teams, writes a deterministically sorted CODEOWNERS file, and fails in --check mode when the committed copy has drifted.
How do you map project roots, tags and shared files to GitHub teams?
Start with the resolution order the generator applies to each project. An explicit owner in your mapping file wins, then a tag match such as scope:payments → @acme/payments, then a name pattern like payments-*. Always resolve to team handles, never individuals. Team membership changes in GitHub settings without a regenerate, and nobody's PTO blocks a merge.
| Source of ownership | Example input | Emitted owner | Typical use |
|---|---|---|---|
| Project root | /libs/auth/ |
@acme/identity |
Default for every project |
| Tag | scope:payments |
@acme/payments |
Groups of projects owned by one team |
| Name pattern | infra-* |
@acme/platform |
Naming conventions without tags |
| File override | /apps/api/migrations/ |
@acme/dba |
Sensitive paths inside a project |
File-level overrides add a second team to specific paths inside a project, such as migrations, OpenAPI or protobuf contracts, and per-project CI config. The project team still owns the rest of its source. The override only adds a security or platform reviewer where a mistake is costly.
Map root and shared files on purpose. These include nx.json, the root package.json and lockfile, tsconfig.base.json, .github/workflows/, and tooling directories. A lockfile bump can change every project's behaviour, so it should not reach a catch-all owner by accident.
Keep each path's owner list short, ideally one team. Owners should cover their own source, not their dependents. Adding the owners of every dependent project to a shared library means one utility change can request reviews from a dozen teams. Reviewers learn to ignore those requests. If you need to manage blast radius, run affected tests in CI rather than adding more reviewers.
Leave module-boundary tags for architecture enforcement. CODEOWNERS only routes reviews.
# .github/CODEOWNERS (generated; edit the mapping file, not this output)
# GitHub uses the LAST matching pattern, so order runs broad to specific.
# Catch-all: explicit fallback, not an accident
* @acme/platform
# Project roots (explicit mapping, then tag, then name pattern)
/libs/auth/ @acme/identity
/libs/payments/core/ @acme/payments # tag scope:payments
/apps/payments-api/ @acme/payments # tag scope:payments
/libs/infra-logging/ @acme/platform # pattern infra-*
/apps/api/ @acme/backend
# File-level overrides inside projects.
# The last match replaces earlier owners, so repeat the project team.
/apps/api/migrations/ @acme/backend @acme/dba
/apps/api/openapi.yaml @acme/backend @acme/api-governance
/libs/payments/core/proto/ @acme/payments @acme/api-governance
/apps/payments-api/project.json @acme/payments @acme/platform
# Root and shared files, mapped on purpose
/nx.json @acme/platform
/package.json @acme/platform
/package-lock.json @acme/platform @acme/security
/tsconfig.base.json @acme/platform
/.github/workflows/ @acme/platform @acme/security
/tools/ @acme/platform
# Protect the routing rules themselves
/.github/CODEOWNERS @acme/platform
A generated CODEOWNERS file ordered from catch-all to project roots to in-project overrides and shared root files. Every entry resolves to a team handle. Because GitHub applies the last matching pattern, each override repeats the project team alongside the added reviewer.
Why does rule ordering matter under last-match-wins?
GitHub evaluates CODEOWNERS from top to bottom, and the last pattern that matches a path determines its owners. Earlier matches are discarded entirely, not merged. So the generator has to choose an emit order on purpose. Iterating the project graph in whatever order it returns, or sorting by project name, will eventually produce a wrong file.
The wrong order
Suppose the generator emits rules in the order it reads projects from the graph:
/libs/billing/core/owned by@org/billing-core/libs/billing/owned by@org/billing*owned by@org/platform
The * rule comes last and matches every path, so the platform team owns the entire repository. If you move * to the top, rule 2 still matches libs/billing/core/src/invoice.ts after rule 1 does, so @org/billing reviews the core library and @org/billing-core never gets a request. The file parses, every team appears in it, and nothing looks broken.
The corrected order
*owned by@org/platform/libs/billing/owned by@org/billing/libs/billing/core/owned by@org/billing-core- File-level overrides, such as
/libs/billing/core/project.json
Sort project roots by path depth, with lexical order as a tiebreaker, so a parent root always comes before any root nested inside it. Emit explicit file overrides after all directory rules.
This bug is hard to spot because a misordered or overly broad rule does not cause a syntax error. Reviews still get requested, but they go to the wrong people, and nobody notices until the owning team misses a change.
interface ProjectOwner { root: string; owners: string[] }
interface FileOverride { path: string; owners: string[] }
const trim = (p: string) => p.replace(/^\/+|\/+$/g, '');
const depth = (p: string) => trim(p).split('/').length;
const byPath = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
export function renderCodeowners(
defaultOwners: string[],
projects: ProjectOwner[],
files: FileOverride[],
): string {
// 1. Catch-all goes first so every later, more specific rule can override it.
const lines = [`* ${defaultOwners.join(' ')}`];
// 2. Project roots: shallower paths first, so libs/billing precedes
// libs/billing/core and the nested rule wins under last-match-wins.
// Lexical tiebreak keeps output stable regardless of graph order.
const sorted = [...projects].sort(
(a, b) => depth(a.root) - depth(b.root) || byPath(trim(a.root), trim(b.root)),
);
for (const p of sorted) lines.push(`/${trim(p.root)}/ ${p.owners.join(' ')}`);
// 3. File-level overrides last: they must beat any directory rule above.
for (const f of [...files].sort((a, b) => byPath(a.path, b.path))) {
lines.push(`/${trim(f.path)} ${f.owners.join(' ')}`);
}
return lines.join('\n') + '\n';
}
// Input order mimics the graph returning the nested project first.
console.log(renderCodeowners(
['@org/platform'],
[{ root: 'libs/billing/core', owners: ['@org/billing-core'] },
{ root: 'libs/billing', owners: ['@org/billing'] }],
[{ path: 'libs/billing/core/project.json', owners: ['@org/platform'] }],
));
// * @org/platform
// /libs/billing/ @org/billing
// /libs/billing/core/ @org/billing-core
// /libs/billing/core/project.json @org/platform
A CODEOWNERS renderer that emits the catch-all first, then project roots sorted by depth with a lexical tiebreak, then file overrides, so libs/billing/core is owned by @org/billing-core even when the project graph lists it first.
How do you enforce and validate generated CODEOWNERS in CI?
Generation only helps if drift breaks the build. If you implement it as an Nx sync generator, developers run nx sync locally to rewrite CODEOWNERS, and CI runs nx sync:check, which fails when the committed file differs from what the generator would produce. Without a sync generator, CI can run your generation target and then git diff --exit-code on the CODEOWNERS file. Either way, a stale file becomes a red build.
Add a second check that fails when any project in the graph has no declared owner. The catch-all rule at the top of the file hides these gaps: the PR still gets a reviewer, so nobody notices that a new project has no real owner. Failing at generation time makes the author of the new project choose a team.
A passing check means the file matches the graph. It does not mean GitHub can use the file. Validate the output in three ways:
- GitHub's error reporting. When you view CODEOWNERS in the web UI, GitHub flags unknown users or teams and lines it cannot parse. GitHub ignores those lines, which can silently remove a review requirement.
- Periodic team audits. Teams get renamed or deleted, and a team without write access to the repository cannot be a code owner. Run a scheduled job that checks every referenced team.
- A test PR. Open a PR that touches one file per ownership tier, such as a project root, a tag-based rule and a shared config file. Confirm that each tier requests the expected reviewers.
Concurrent PRs that each add a project will conflict in CODEOWNERS. Don't resolve these conflicts by hand. Regenerate the file on rebase, or have CI regenerate it, because the graph already contains the correct merged result.
When should you avoid generated CODEOWNERS, and what are the alternatives?
Generation pays off when ownership changes faster than people remember to edit the file. In a repo with one or two teams, a handful of directory rules rarely drifts, so a generator adds moving parts for little gain. The same applies if branch protection does not require Code Owner review. Without that setting, CODEOWNERS only suggests reviewers, and a misrouted request costs a click.
Required reviews create the opposite problem on cross-cutting PRs. A dependency bump, a codemod or an Nx migration can touch every project, so it needs approval from every owning team, and the slowest team sets the merge time. One mitigation is to route these changes through a platform-owned path. For example, keep lockfiles, root config and migration files under platform ownership, and land repo-wide mechanical edits in small batches that platform engineers can approve. Pair this with a documented bypass for automated PRs, and audit its use.
| Option | Portability | Lock-in | Maintenance as graph output changes |
|---|---|---|---|
| Hand-written file | Any repo, any tool | None | Manual edits for every new or moved project |
| Nx owners plugin | Nx workspaces only | Plugin config format, and license terms you should check | Tracks Nx changes, but you depend on the plugin's release cadence |
| Custom graph script | Any repo where you can export the graph | Your own code | You fix it when the graph JSON shape changes |
The trade-off is engineering time. Generation removes the manual edit for each new project and reduces misrouted reviews. In exchange, someone has to own the generator, and every PR pays for an extra CI step. If your project list changes rarely, the hand-written file usually wins.
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.