How does GitHub CODEOWNERS actually decide who reviews a pull request?
GitHub reads a single CODEOWNERS file from one of three locations: .github/, the repository root, or docs/. It checks them in that order and uses the first one it finds, so a stray copy in docs/ is silently ignored if .github/CODEOWNERS exists. The file on the pull request's base branch is the one that applies, not the one on the branch being merged.
Each line pairs a path pattern with one or more owners. For any changed file, the last matching pattern wins. Earlier matches are discarded, not merged. This is the most common source of surprise. Consider a file that first assigns /libs/payments/ to @org/payments, then later adds *.ts @org/platform as a catch-all. Every TypeScript file under libs/payments/ now belongs only to @org/platform, because the broad glob appears later. Specific rules must come after general ones.
Owners must be users or teams with write access to the repository, and teams must be visible. An owner that doesn't meet this requirement doesn't cause the file to be rejected. GitHub skips invalid lines or entries and keeps processing the rest. It flags errors when you view the file, but nothing fails, so a typo in a team slug can quietly leave a directory unowned.
Ownership is advisory by default. GitHub automatically requests code owners as reviewers when a pull request is ready for review, but it does not block the merge. Approval becomes mandatory only when a branch protection rule or ruleset requires review from code owners.
# .github/CODEOWNERS (read from the PR's base branch)
# Problem ordering: the broad glob comes last, so it wins.
# Default owner for anything not matched below
* @example-org/platform
# Specific rule: payments library
/libs/payments/ @example-org/payments
# Catch-all added later for TypeScript files.
# Because it is the LAST matching pattern, every .ts file
# under /libs/payments/ is now owned only by @example-org/platform.
# Earlier matches are discarded, not merged.
*.ts @example-org/platform
# ------------------------------------------------------------
# Corrected ordering: general rules first, specific rules last.
# ------------------------------------------------------------
# * @example-org/platform
# *.ts @example-org/platform
# /libs/payments/ @example-org/payments
#
# Now /libs/payments/src/charge.ts matches /libs/payments/ last,
# so @example-org/payments owns it.
# Note: if a team slug is misspelled or lacks write access,
# GitHub skips that owner and keeps processing the file; it
# flags the error when the file is viewed but does not fail.
A CODEOWNERS file where a later *.ts glob overrides the earlier /libs/payments/ rule because the last matching pattern wins, with a corrected ordering shown in comments.
Why does a hand-maintained CODEOWNERS file drift in an Nx monorepo?
A CODEOWNERS file is a list of path patterns, while an Nx workspace is organized around projects. Nothing ties the two together, so they drift apart in three predictable ways.
Project roots move. Someone runs nx g @nx/workspace:move or relocates a library by hand from libs/payments to libs/billing/payments. Nx updates the project configuration and import paths, but CODEOWNERS still points at the old directory. The pattern now matches nothing, and GitHub does not warn about patterns that match no files.
Generators create projects without owner lines. A new library gets a project.json, a tsconfig, and a test setup. No generator adds a CODEOWNERS entry, so the project falls through to whatever broader rule happens to match. Often that is nothing.
Broad globs take ownership without anyone noticing. GitHub uses the last matching pattern in the file. A rule like /libs/** that is appended late, or a catch-all * placed after the specific entries, overrides every team-specific line above it. Reviews get routed to the wrong team. With required reviews enabled, they either block on people who lack context or get approved by people who should not be approving.
The fix is to stop editing the file by hand. Treat CODEOWNERS as a build artifact: generate it from the project graph, sort it deterministically, and fail CI when the committed file differs from the generated one. This pays off for platform teams running multi-team Nx repositories with required code-owner reviews. A small single-team repo with a handful of static lines does not need it.
Should project ownership live in metadata or in project tags?
Before writing a generator, decide where ownership is recorded. Nx gives you two plausible homes: a custom key under metadata in each project.json, or a tag such as team:payments that a central file maps to a GitHub team.
Tags look attractive because they already exist and are queryable. But in most Nx repos, tags drive module boundary rules: depConstraints in the lint config decide which tagged projects may import which. If a tag carries ownership, two concerns share one string. Encoding the GitHub handle directly, as in owner:@acme/payments-api, is worse. A team rename or reorg then forces edits to lint rules that have nothing to do with dependency direction, and a mistake there can silently loosen boundaries.
| Concern | metadata.owners |
Ownership tags |
|---|---|---|
| Coupled to lint boundary rules | No | Yes, same namespace |
| Team rename touches | One mapping file | Tags, plus any rule that references them |
| Supports multiple owners per project | Natural (array) | Possible, but tag lists get noisy |
Queryable with nx show projects filters |
Not directly | Yes |
| Validated by existing tooling | No, your generator must check it | Partially, via lint |
The recommended default is a stable, org-neutral team key in metadata.owners, such as payments, never a GitHub handle. A single mapping file at the workspace root translates each key to one or more GitHub teams. A reorg then changes one line in the mapping file, and project files only change when ownership actually moves. Keep tags for architecture. If you want team-level boundary rules later, add a separate scope: tag.
# 1) Each project records a stable, org-neutral team key under metadata.
# Tags stay reserved for architecture (module boundary rules).
cat > libs/payments/api/project.json <<'EOF'
{
"name": "payments-api",
"$schema": "../../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "libs/payments/api/src",
"projectType": "library",
"tags": ["type:data-access"],
"metadata": {
"owners": ["payments"]
}
}
EOF
# 2) One mapping file at the workspace root translates team keys to
# GitHub teams. A reorg or team rename edits only this file.
cat > team-owners.json <<'EOF'
{
"payments": ["@acme/payments-api"],
"platform": ["@acme/platform", "@acme/sre"]
}
EOF
A project.json that stores an org-neutral team key in metadata.owners, alongside a single root mapping file that resolves each key to one or more GitHub teams.
How does nx codeowners generation work from the project graph?
The generator should ask Nx which projects exist rather than globbing for project.json. Projects inferred by plugins from package.json or other config files never have a project.json, and a filesystem glob silently skips them. The graph is the same source of truth that nx affected uses, so ownership and CI scope stay in agreement.
There are three ways to read it:
nx show projects --jsonlists project names, andnx show project <name> --jsonreturns each project's resolved configuration, includingrootandmetadata. This is easy to use from a shell script, but it spawns one process per project, which gets slow in large workspaces.nx graph --file=graph.jsonwrites the whole graph in one call. Each node is keyed by project name and carries its root and configuration. It is a good fit for a generator that is not written in Node.createProjectGraphAsyncfrom@nx/devkit, called in a Node script, returns the graph as typed objects and reuses Nx's cache. Prefer this option if your tooling is already in TypeScript.
Whichever source you use, the generator joins each project's owner key to the team map. It emits one /<root>/ @org/team line per project, sorted by root so the output is deterministic. It writes these lines between marker comments and copies everything outside the markers unchanged.
project config (metadata.owner) ─┐
├─► Nx project graph ─► generator
team map (owner → @org/team) ────┘ │
▼
manual section (preserved) + generated section (between markers)
│
▼
committed CODEOWNERS ◄── CI: regenerate, fail on diff
Watch for a project whose root is .. It would emit / and claim the entire repository, so either skip it or route it to the manual section.
// scripts/codeowners.ts: regenerate the Nx-owned block of .github/CODEOWNERS.
// Run with --check in CI to fail when the committed file is stale.
import { createProjectGraphAsync } from '@nx/devkit';
import { readFileSync, writeFileSync } from 'node:fs';
const FILE = '.github/CODEOWNERS';
const BEGIN = '# BEGIN nx-generated (do not edit)';
const END = '# END nx-generated';
// Team map kept in the repo, e.g. { "payments": "@acme/payments-team" }
const teams: Record<string, string> = JSON.parse(readFileSync('tools/teams.json', 'utf8'));
async function main() {
// The graph includes inferred projects that have no project.json.
const graph = await createProjectGraphAsync();
const lines: string[] = [];
for (const [name, node] of Object.entries(graph.nodes)) {
const owner = (node.data.metadata as Record<string, unknown> | undefined)?.owner;
const team = typeof owner === 'string' ? teams[owner] : undefined;
if (!team) throw new Error(`Project ${name} has no owner mapped in tools/teams.json`);
if (node.data.root === '.') continue; // a root project would claim the whole repo
lines.push(`/${node.data.root}/ ${team}`);
}
lines.sort(); // deterministic output, so diffs show only real ownership changes
// Assumes both markers already exist; everything outside them is preserved verbatim.
const current = readFileSync(FILE, 'utf8');
const start = current.indexOf(BEGIN);
const end = current.indexOf(END);
if (start === -1 || end === -1) throw new Error(`Markers missing in ${FILE}`);
const next = current.slice(0, start) + [BEGIN, ...lines].join('\n') + '\n' + current.slice(end);
if (process.argv.includes('--check')) {
if (next !== current) { console.error(`${FILE} is out of date; run the generator`); process.exit(1); }
} else {
writeFileSync(FILE, next);
}
}
main().catch((err) => { console.error(err); process.exit(1); });
A Node script that reads project roots and metadata.owner from createProjectGraphAsync, maps owners to teams, rewrites only the marked block of CODEOWNERS, and supports a --check mode for CI.
How do you implement a deterministic CODEOWNERS generator and CI drift check?
The generator itself is small. Read the project list and roots from nx graph --file=graph.json (or nx show projects --json plus per-project details), then write the file in a fixed order:
- A catch-all default line (
* @org/platform) at the top. GitHub applies the last matching pattern, so anything below overrides it, and no file is ever left unowned. - One line per project root, sorted by path. In a lexical sort,
libs/paymentscomes beforelibs/payments/adapters, so the nested project appears later and wins for its subtree. Sort with a fixed, locale-independent comparison and normalize trailing slashes. If ordering depends on graph traversal order, runs that change nothing can still produce noisy diffs. - The preserved hand-written block, copied verbatim from between the markers. This covers
nx.json, the rootpackage.json, the lockfile,.github/workflows/, andCODEOWNERSitself. Placing it last lets these explicit rules override any project glob that happens to match them.
The CI job regenerates the file, then runs git diff --exit-code CODEOWNERS. A non-empty diff fails the build with a message that tells the author to run the script. The job also fails separately if any project resolves to no owner. Do not let such a project silently fall through to the catch-all.
Unit-test the ordering logic with fixtures that include nested roots, sibling roots that share a prefix (libs/api vs libs/api-client), and a root of .. To catch missing owners earlier, have your custom Nx project generator require an owner tag, so every new project has an owner from the moment it is created.
The check has a real cost. Computing the graph requires an installed workspace, and inferring plugins may run tool configs. In CI, this makes the job slower and more fragile than a plain file lint. Trigger it only when project config files or CODEOWNERS change, and reuse the dependency cache.
#!/usr/bin/env bash
# CI drift check for the generated CODEOWNERS file.
set -euo pipefail
CODEOWNERS_FILE="CODEOWNERS"
# Compute the project graph once. This needs an installed workspace
# (node_modules), and inferring plugins may evaluate tool configs.
# Disabling the daemon avoids state left over from earlier runs.
NX_DAEMON=false npx nx graph --file=graph.json
# Fail if any project has no owner tag. Do not let it fall through
# to the catch-all default line.
unowned=$(jq -r '
.graph.nodes | to_entries[]
| select((.value.data.tags // []) | any(startswith("owner:")) | not)
| .key' graph.json)
if [ -n "$unowned" ]; then
echo "Projects without an owner:* tag:" >&2
echo "$unowned" >&2
exit 1
fi
# Regenerate from the same graph.json. The generator writes the catch-all,
# then project roots sorted by path, then the preserved hand-written block.
# LC_ALL=C keeps any shell-side sorting locale-independent.
LC_ALL=C node tools/codeowners/generate.mjs graph.json > "$CODEOWNERS_FILE"
# Any difference means someone changed projects without regenerating.
if ! git diff --exit-code -- "$CODEOWNERS_FILE"; then
echo "CODEOWNERS is out of date." >&2
echo "Run: node tools/codeowners/generate.mjs graph.json > CODEOWNERS" >&2
exit 1
fi
A CI script that builds the Nx graph once, fails if any project lacks an owner tag, regenerates CODEOWNERS, and fails on a non-empty git diff.
How do you validate owners and handle cross-cutting changes?
Validate every team before merging
A generated file can still reference a team that no longer exists. When a team is deleted or renamed, or lacks write access to the repository, GitHub skips it as an owner. If no other valid owner matches that path, the path loses its required review, and nothing fails visibly. Add a CI step that reads the unique team handles from the generated file. For each one, call the REST endpoint that checks a team's permission on a repository (GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}). Fail the step if the team is missing or has less than write permission. GitHub also reports syntax and unknown-owner problems in the CODEOWNERS file view and through the codeowners/errors REST endpoint, so the job can query that endpoint as well. Use a token that can read organization teams, because the default workflow token often can't.
Keep shared libraries from fanning out
A change to a widely imported library should not request review from every consumer. Assign that library to one coarse owner. Usually this is a platform team, which should also own shared tooling such as lint configs, generators, and CI files.
To show reviewers the blast radius, post nx affected output as a PR comment. Keep that comment informational and separate from branch protection. CODEOWNERS decides reviewers by file path, not by dependency impact. Generating the file from the project graph makes the path mapping more accurate, but it does not change what GitHub enforces.
When should you avoid generated CODEOWNERS, and what are the alternatives?
Generation is the wrong default in three situations:
- Small or overloaded teams. If a team has two reviewers and one is on leave, required code owner review turns every pull request touching their projects into a queue. A more accurate file only blocks more precisely.
- Frequent cross-cutting refactors. Repos that often rename shared libraries or change workspace-wide config tend to accumulate broad fallback owners or admin bypasses. Both weaken the review guarantee the file was meant to provide.
- Frequent renames. A drift check fails every pull request that adds or renames a project until someone regenerates the file. That cost falls on whoever touched the graph, not on the owning team.
| Approach | Accuracy | Friction | Visibility of ownership changes |
|---|---|---|---|
| Hand-maintained file | Drifts over time | Low per PR | Reviewed when edited |
| Generated, CI drift failure | High | Fails PRs that change projects | Diff appears in the PR |
| Generated, auto-commit | High | Low | Changes land without review |
| Suggestion-only, no required review | Same as the source | None | Not enforced |
Illustrative estimate. Assume 40 projects, four missed ownership updates a month, and 30 minutes of misrouted review per miss. That costs about 2 hours a month. Assume the generator takes 8 hours to build and 1 hour a month to maintain. The net saving is then 1 hour a month, so it breaks even after roughly 8 months. If drift failures cost more than an hour a month, it never does.
Rollout path:
- Run the generator in report-only mode.
- Diff its output against the current file.
- Fix projects with no owner tag.
- Enable required code owner review one protected branch at a time.
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.