What does it mean to split an Nx monorepo, and why do teams do it?
Splitting an Nx monorepo means moving one or more Nx projects, usually a library, into its own repository while keeping its commit history. Afterward, the monorepo no longer imports that code through a TypeScript path alias. It installs a published package at a pinned version instead.
The git work is the smaller part of the job. A history-rewriting tool can isolate a directory's commits in an afternoon. The harder work is untangling the dependency graph and choosing a release model. Inside the workspace, every consumer always builds against the latest commit of the library. After the split, consumers choose when to upgrade, and the library team owns versioning, changelogs and breaking-change policy.
Teams usually split for one of these reasons:
- Ownership. A team wants full control of a codebase's conventions, tooling and review rules.
- Release cadence. The library ships on a schedule unrelated to the applications that use it.
- Access control. The code must be shared with contractors or the public without exposing the rest of the repository.
- CI scope. Changes to a widely used library cause affected-project runs to rebuild most of the workspace.
BEFORE AFTER
monorepo lib-repo ──publish──> registry
├─ libs/auth <──┐ (history intact) │
├─ apps/api ────┤ │ auth@1.x
└─ apps/admin ───┘ monorepo │
(path alias) ├─ apps/api <─────────┤
└─ apps/admin <─────────┘
This guide is for backend and platform engineers who own workspace structure and will maintain both sides of the boundary afterward.
BEFORE: apps import libs/auth through a TypeScript path alias
┌──────────────────────── monorepo ────────────────────────┐
│ ┌────────────┐ ┌────────────┐ │
│ │ apps/api │ │ apps/admin │ │
│ └─────┬──────┘ └─────┬──────┘ │
│ │ path alias │ path alias │
│ ▼ ▼ │
│ ┌───────────────────────────────┐ │
│ │ libs/auth (latest commit) │ │
│ └───────────────────────────────┘ │
└──────────────────────────────────────────────────────────┘
AFTER: libs/auth ships from its own repo as a versioned package
┌──── auth-repo ─────┐ publish ┌─── registry ───┐
│ libs/auth ├──────────►│ @org/auth │
│ (history intact) │ │ 1.3.2, 1.4.0 │
└────────────────────┘ └───────┬────────┘
│ install, pinned per app
┌───────────────────┬───────────┘
│ @org/auth@1.4.0 │ @org/auth@1.3.2
┌────────┼───────────────────┼────── monorepo ─────────────┐
│ ▼ ▼ │
│ ┌────────────┐ ┌────────────┐ │
│ │ apps/api │ │ apps/admin │ │
│ └────────────┘ └────────────┘ │
└──────────────────────────────────────────────────────────┘
Before the split, both apps build against the latest libs/auth through a path alias; afterward, libs/auth lives in its own repository with its history, publishes to a registry, and each app pins and upgrades its version independently.
When should you avoid splitting, and what are the alternatives?
Splitting has a real cost. Inside the monorepo, renaming a function in a shared library and fixing every caller happens in one commit and one review. After the split, the same refactor becomes a publish, a version bump, and a separate upgrade PR in each consumer, and those PRs merge at different times. nx affected and the computation cache stop seeing the extracted code, so CI can no longer tell you which consumers a change breaks. Consumers pin different versions. Diamond dependencies appear when two packages need incompatible releases of the same library. You also duplicate lint, test, and CI configuration, and you need a package registry plus named owners who cut releases.
| Option | What changes | Development cost | Ongoing engineering time |
|---|---|---|---|
| Stricter module boundaries + CODEOWNERS | Tag projects, enforce dependency rules in lint, require owner review | Low: config only | Low: rules run in existing CI |
| Publish from the monorepo | Source stays; selected libraries are versioned and pushed to a registry | Medium: release pipeline | Medium: versioning discipline |
| Split CI and ownership only | Separate pipelines, permissions, and on-call per project | Medium | Low to medium |
| Full split | Separate repository, history, toolchain, and releases | High | High: cross-repo coordination on every shared change |
Work through the options from cheapest to most expensive. Use a full split only when the code needs separate access control, a separate release cadence, or a separate owner that the cheaper options can't provide. If a library changes in lockstep with its consumers, don't split it. Tightly coupled code is usually the strongest case for staying put, because every cross-repo change then costs more engineering time than the separation saves.
How do you use the Nx project graph to choose what to extract?
Before deciding anything, look at the actual dependency edges instead of relying on what the team remembers. Running nx graph opens an interactive view, and nx graph --focus=<project> narrows it to one candidate and its direct neighbors. For something you can script against, nx graph --file=graph.json writes the project graph to disk. In that file, graph.dependencies maps each project to the projects it imports. Your candidate's own entry gives its dependencies. To find its dependents, collect every project whose dependency list names the candidate as a target.
Two patterns usually mean you should not extract the project as it stands:
- Many inbound dependents. If a dozen apps import the library, moving it out turns each of them into a consumer of an external artifact. That is the right outcome only if you intend to version and publish it as a package. Otherwise you are giving every dependent a cross-repo upgrade path in exchange for very little.
- Many outbound internal imports. If the candidate pulls in several internal libraries, it cannot build alone. You have two options: extract those libraries along with it, or replace them first with published packages or local copies.
A boundary is cleanly separable when:
- It has few internal dependencies, ideally none or only stable utilities.
- Its dependents are few, or you are willing to consume it through a versioned package.
- It has no circular edges with other projects.
- It owns its build, test and lint targets without relying on workspace-level configuration that other projects also use.
#!/usr/bin/env bash
# Inspect one extraction candidate using the exported Nx project graph.
# Usage: ./inspect-candidate.sh billing-api
set -euo pipefail
CANDIDATE="${1:?usage: $0 <project-name>}"
# Write the project graph to disk so it can be queried with jq.
npx nx graph --file=graph.json
# Outbound edges: internal projects the candidate imports.
# Skip external npm packages, which are not part of the split.
echo "== Internal dependencies of $CANDIDATE =="
jq -r --arg p "$CANDIDATE" '
.graph.dependencies[$p][]
| select(.target | startswith("npm:") | not)
| .target' graph.json | sort -u
# Inbound edges: every project whose dependency list targets the candidate.
echo "== Dependents of $CANDIDATE =="
jq -r --arg p "$CANDIDATE" '
.graph.dependencies
| to_entries[]
| select(any(.value[]; .target == $p))
| .key' graph.json | sort -u
# Direct cycles: a project that is both a dependency and a dependent.
# Any output here is a blocker for a clean split.
echo "== Direct circular edges =="
comm -12 \
<(jq -r --arg p "$CANDIDATE" '.graph.dependencies[$p][] | .target' graph.json | sort -u) \
<(jq -r --arg p "$CANDIDATE" '.graph.dependencies | to_entries[]
| select(any(.value[]; .target == $p)) | .key' graph.json | sort -u)
Exports the Nx project graph with nx graph --file=graph.json and uses jq to list a candidate's internal dependencies, its dependents, and any direct circular edges, which are the inputs for deciding whether the boundary is separable.
How do you prepare the monorepo before rewriting any history?
Every fix you make before running git filter-repo is a fix you make once. After the rewrite, the same problem appears in two repositories.
Close the public entry point
Search consumers for imports that reach past the library's entry point, such as @acme/billing/src/lib/internal/rates. Inside the monorepo these work because the TypeScript path alias resolves to source. A published package exposes only what its entry point and exports field allow, so every deep import breaks after the split. Re-export what consumers genuinely need from the library's index.ts, and make the rest private.
Switch to package-name imports
Where the library will become a versioned dependency, consumers should import it by the name it will be published under. Keep the tsconfig.base.json path mapping temporarily, but make sure its key matches the future package.json name. Then the cutover only changes how the name resolves, and no import statements need to be rewritten.
Enforce the cut line
Tag the project in project.json, for example "tags": ["scope:billing", "type:lib"]. In the enforce-module-boundaries rule's depConstraints, add an entry with sourceTag: "scope:billing" and onlyDependOnLibsWithTags: ["scope:billing", "scope:shared"]. Lint must pass with no suppressions. A passing lint run shows the library does not secretly depend on code that stays behind.
Inventory what lives outside the folder
List every root-level dependency of the project's targets:
compilerOptionsinherited fromtsconfig.base.json- Packages in the root
package.json - Shared ESLint, Prettier and Jest presets
targetDefaultsandnamedInputsinnx.json- CI workflow steps
- Any codegen or scripts that targets invoke
filter-repo keeps only the paths you choose, so anything missing from this list will be missing from the new repository.
// eslint.config.js at the workspace root (ESLint flat config)
// libs/billing/project.json declares: "tags": ["scope:billing", "type:lib"]
// libs/shared-utils/project.json declares: "tags": ["scope:shared", "type:lib"]
const nx = require('@nx/eslint-plugin');
module.exports = [
...nx.configs['flat/base'],
...nx.configs['flat/typescript'],
{
files: ['**/*.ts', '**/*.tsx', '**/*.js', '**/*.jsx'],
rules: {
'@nx/enforce-module-boundaries': [
'error',
{
// Keep this empty: an allow entry is an untracked hole in the cut line
allow: [],
depConstraints: [
{
// billing may use itself and shared code, never code that stays behind
sourceTag: 'scope:billing',
onlyDependOnLibsWithTags: ['scope:billing', 'scope:shared'],
},
{
// shared must not reach back into billing, or the split creates a cycle
sourceTag: 'scope:shared',
onlyDependOnLibsWithTags: ['scope:shared'],
},
{
// libraries never import applications
sourceTag: 'type:lib',
onlyDependOnLibsWithTags: ['type:lib'],
},
],
},
],
},
},
];
An ESLint flat config that uses enforce-module-boundaries and project tags to restrict the billing library to its own scope and shared code, so a clean lint run confirms where the repository can be cut.
How do you extract a library with git filter-repo and preserve git history?
from every commit in the new repository's history.
Run the rewrite on a throwaway clone
git filter-repo is not bundled with Git; install it separately. The Git documentation recommends it over git filter-branch, which is slow and easy to misuse. Clone the monorepo fresh into a scratch directory and work only there. By default, filter-repo refuses to run on a clone that isn't fresh. That check protects your working copy, so don't override it with --force on a repository you care about.
Pass one --path for the project directory and one for each shared file you listed. Then use --path-rename to move the project to the root. --subdirectory-filter does the same thing for a single directory, but it discards everything outside that directory, so it doesn't work if you also need shared files. If the project ever lived somewhere else, such as an older packages/ directory before a move to libs/, add a --path and a matching rename for every historical location. Otherwise, history before the move disappears.
Inspect what survived
Run git log --follow on a few key files and confirm that the log reaches back past known moves. Compare commit counts with git rev-list --count HEAD, run in the monorepo with your paths as a pathspec and in the new repository without one.
Also check for history that was kept by accident. Shared config files carry every past version with them. Review git log -p for each one and look for credentials or settings that belong to other teams.
Every commit hash changes in the rewrite. filter-repo writes an old-to-new mapping to .git/filter-repo/commit-map; keep a copy of that file. The monorepo remains the record for the original hashes.
# Work only in a fresh scratch clone; filter-repo refuses non-fresh clones by default.
git clone git@git.example.com:acme/monorepo.git /tmp/billing-extract
cd /tmp/billing-extract
# Keep the project under its current and historical locations, plus shared files.
# Then move each historical location to the new repo root.
git filter-repo \
--path libs/billing/ \
--path packages/billing/ \
--path tsconfig.base.json \
--path-rename libs/billing/: \
--path-rename packages/billing/:
# History should reach back past the packages/ -> libs/ move.
git log --follow --oneline -- src/index.ts | tail -n 5
# Compare commit counts: the monorepo uses the kept paths as a pathspec.
git -C ~/src/monorepo rev-list --count HEAD -- \
libs/billing packages/billing tsconfig.base.json
git rev-list --count HEAD
# Look for content kept by accident in shared files' full history.
git log -p -- tsconfig.base.json | grep -inE 'token|secret|password|apikey'
# Save the old-to-new hash mapping before this scratch clone is deleted.
cp .git/filter-repo/commit-map ~/billing-commit-map.txt
Extracting a library and a shared config file from a fresh clone with git filter-repo, moving both historical locations to the repo root, then checking --follow history, commit counts and shared-file diffs, and saving the commit map.
How do you turn the extracted code into a working repository and reconnect consumers?
First decide what the new repository is. Keep a single-project Nx workspace if the library still benefits from Nx caching, generators or module-boundary lint rules. If it is a small package with one build step, drop Nx and use plain package.json scripts. That gives contributors one less tool to learn.
Recreate the root files the extracted project relied on but never owned: tsconfig.base.json, the shared ESLint and Prettier configs, .gitignore, and the test runner config. Install dependencies at the exact versions recorded in the monorepo lockfile, not the latest ones. If you upgrade during the move and something breaks, you cannot tell whether the split or the upgrade caused it. Run build, test and lint, and get them green before you change anything else.
Next, publish to your public or private registry. Give the package explicit metadata: a scoped name such as @acme/billing-core, a starting version of 1.0.0, a files allowlist, an exports map, and publishConfig.registry pointing at the intended registry. Name one owner for the changelog. Consumers now upgrade on purpose, so they need release notes to do it.
Then update the monorepo:
- Swap the dependency. Remove the
@acme/billing-corepath alias fromtsconfig.base.json. Add"@acme/billing-core": "^1.0.0"to the consumers' dependencies. - Delete the original folder in a separate commit. Name the new repository in the commit message, so
git logon the old path explains where the code went. - Clean up references. Remove the path from
CODEOWNERSand from any CI path filters.
How do you sequence the cutover and verify the split worked?
- Announce a cut-off. Give owners a date after which nothing merges into the project's path on
main. Anything merged after that point is work that someone has to port by hand or that gets lost. - Re-run the filter on the latest
main. Start from a fresh clone and run the samegit filter-repoinvocation you scripted earlier. Push the result as the new repository's first history. Do not try to sync an extraction made weeks ago. Rewritten commits have different hashes from the originals, so merging upstream changes into an old extraction never applies cleanly. - Port open pull requests. In the monorepo, export each branch with
git format-patch main..feature-branch -- libs/payments. In the new repo, apply the patches withgit am -p3, which strips thea/libs/payments/prefix so the paths match the new root. Authorship and commit messages carry over. - Land the removal commit in the monorepo, and only after the new repo builds.
| Approach | Cost at cutover | Risk |
|---|---|---|
| Sync an old extraction | Manual conflict resolution | Silently dropped commits |
| Re-run filter at cut-off | One scripted run | Low, because it is repeatable |
Verification checklist:
nx graphshows no project, import path, or implicit dependency that still points at the removed project.nx affectedstill resolves its base in CI, and the pipeline passes.- The new repository's CI is green on its first commit.
- The tags and release notes that matter are carried over or recreated.
- A scan of the new repo's full history finds no secrets and no unrelated paths.
This sequencing saves engineering time because the extraction runs once against a frozen target, so no work merged during the move is lost and nobody has to repeat the split.
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 split nx 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
.envby 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.