What is an Nx library split and why does a shared utils package need one?
A shared utils library usually starts small: a date formatter, a retry wrapper, a logger factory. Over time it absorbs every helper that has no obvious home, and every app and library in the workspace ends up importing from it. It becomes a dependency magnet. The cause is not bad code. A single project boundary simply cannot express which consumers need which pieces.
That matters because Nx computes affected scope at the project level, not the function level. Edit one line in a string helper, and Nx treats the whole utils project as changed. Every project that depends on it, directly or transitively, is marked affected. CI then rebuilds, retests and relints all of them, even services that only ever used the logger. Each change also has a wider blast radius than it should. Reviewers cannot easily tell which consumers a change can actually break, so they either check everything or check nothing.
An Nx library split replaces that one library with several cohesive libraries. Each has a narrow purpose and an explicit dependency direction. Apps depend only on what they use, and the graph shows that accurately.
BEFORE AFTER
api ──────┐ api ─────► logging, http-client, validation
worker ───┼──► shared-utils worker ──► logging, date-time
web ──────┘ web ─────► validation, date-time
(test targets) ──► testing
After the split, a change to date-time affects worker and web, but not api.
BEFORE: one project boundary, every app depends on all of it
+-----+ +--------+ +-----+
| api | | worker | | web |
+--+--+ +----+---+ +--+--+
| | |
+----------+---------+
v
+--------------+
| shared-utils | edit any helper -> api, worker, web affected
+--------------+
AFTER: each app depends only on the libraries it uses
api worker web tests
| | | |
+-------------+ | | | |
| logging |<------+-------+ | |
+-------------+ | | | |
| date-time |<------|-------+-------+ |
+-------------+ | | | |
| validation |<------+-------|-------+ |
+-------------+ | | | |
| http-client |<------+ | | |
+-------------+ | | | |
| testing |<------|-------|-------|-------+
+-------------+
+ = depends on -|- = lines cross, no dependency
edit date-time -> worker, web affected; api is not
Before the split, any edit to shared-utils marks every app as affected; after it, each app depends only on the logging, date-time, validation, http-client and testing libraries it uses, so a date-time change reaches only worker and web.
Who should split a shared utils library, and when should you avoid it?
That smaller blast radius only pays off if your pipeline acts on it. The teams that benefit are platform and backend teams whose CI already runs nx affected against a correct base commit, usually the merge-base with the main branch. Their utils library also needs many consumers and frequent edits. In that setup, every change to shared-utils currently rebuilds and retests most of the workspace, and a split reduces that directly.
Postpone the split in these cases:
- CI runs every target on every PR. The graph gets more precise, but nothing reads it.
- The workspace is small. With a handful of projects, "affected" and "everything" are nearly the same set.
- Many branches touch the library right now. Moving files during heavy parallel work produces merge conflicts that cost more than the split saves.
Over-splitting is a risk too. Each new library adds project configuration, a tsconfig path alias and a graph node. Twenty single-file libraries make engineers stop and work out where a helper belongs and which alias to import. That added cognitive load can outweigh the CI time recovered.
Try cheaper fixes first:
| Option | Effort | Effect on affected scope | Risk |
|---|---|---|---|
| Fix CI's affected base configuration | Low | Large if CI currently runs everything | Low |
| Narrow barrel exports | Low | None directly, but it shrinks the public API you would later split | Low |
| Module boundary rules on the existing library | Low–medium | None, but it stops coupling from growing | Low |
| Split into a few coarse libraries | Medium | Significant | Medium |
| Split into many fine-grained libraries | High | Marginal gains over the coarse split | High |
How do you measure who imports what before choosing boundaries?
Opinions about where a utils library "naturally" divides are cheap. Usage data is what matters. Collect four signals before drawing any boundary.
Who depends on it. Run nx graph --focus=shared-utils to isolate the library and its direct dependents. Count the dependents and note which kinds of projects they are: API services, workers, CLIs, frontends. A library imported by every service is a different problem from one used by three.
What they import. The project graph records that a dependency exists. It does not record which parts of the library are used. To find that, search import statements with something like rg "from '@acme/shared-utils" --glob '*.ts'. Group the results by consumer and by subpath or symbol. If consumers import only from the root barrel, list the named symbols instead.
How often each area changes. Run git log --oneline --since="6 months ago" -- libs/shared-utils/src/logging for each subdirectory. This shows where churn concentrates. A volatile module bundled with stable ones forces every consumer to rebuild whenever the volatile module changes.
What one change costs today. Make a representative edit, such as changing a logging helper, then run nx show projects --affected --base=main. Record the count. That number is your baseline for the comparison in section 7.
Read the results together as a co-usage map:
- Symbols that the same consumers always import together belong in the same library.
- Symbols with disjoint consumer sets are candidates for separate libraries.
- High-churn modules with many consumers produce the largest affected-scope reductions when you isolate them, so split those first.
#!/usr/bin/env bash
# Diagnosis pass for libs/shared-utils. Run from the workspace root on a clean checkout of main.
set -euo pipefail
# 1. Who depends on it: open the project graph focused on the library and its dependents.
nx graph --focus=shared-utils
# 2. What they import: count imports per consumer project and per subpath.
# -N (no line numbers) keeps output as path:match; awk reduces path to apps/<name> or libs/<name>.
rg -N -o --no-heading "from '@acme/shared-utils[^']*'" -g '*.ts' apps libs \
| awk -F: '{ split($1, p, "/"); print p[1] "/" p[2], $2 }' \
| sort | uniq -c | sort -rn > import-map.txt
# If everything comes from the root barrel, list the named symbols instead.
rg -U -N -o --no-heading "import \{[^}]*\} from '@acme/shared-utils'" -g '*.ts' apps libs \
> barrel-symbols.txt
# 3. How often each area changes: commit count per subdirectory over six months.
for dir in libs/shared-utils/src/*/; do
count=$(git log --oneline --since="6 months ago" -- "$dir" | wc -l)
printf '%5d %s\n' "$count" "$dir"
done | sort -rn > churn.txt
# 4. What one change costs today: make a throwaway edit to a logging helper.
# Affected detection includes uncommitted changes when only --base is given.
echo '// baseline probe' >> libs/shared-utils/src/logging/format.ts
nx show projects --affected --base=main | tee affected-baseline.txt
echo "Affected projects: $(wc -l < affected-baseline.txt)"
# Revert the probe so it never gets committed.
git restore libs/shared-utils/src/logging/format.ts
A diagnosis script that collects four signals for a shared utils library before any split: the focused project graph, an import map per consumer and subpath, per-directory churn from git log, and a baseline count of affected projects for one representative logging edit.
How should you choose split boundaries, tags and dependency rules?
Use that consumer data to draw boundaries around code that is imported together and changes together. Avoid splitting by file type. A string-utils library mixes unrelated callers, so every edit marks all of them affected. Groupings like logging, date/time, validation, HTTP clients and test helpers match how teams actually use and change the code.
Two other cuts matter. First, separate dependency-free code from code that pulls in heavy packages, so a service that needs one pure function does not inherit an HTTP or schema library. Second, keep test-only utilities such as fixtures, fakes and builders out of production libraries entirely.
| Candidate library | Tags | May depend on | Runtime weight |
|---|---|---|---|
util-core |
scope:shared, type:util |
nothing | none (pure functions) |
util-datetime |
scope:shared, type:util |
type:util |
light |
util-logging |
scope:shared, type:util |
type:util |
logger package |
data-access-http |
scope:shared, type:data-access |
type:util |
HTTP client |
testing-fixtures |
scope:shared, type:testing |
type:util, type:data-access |
dev-only |
Declare these tags in each project.json. Enforce them with @nx/enforce-module-boundaries through depConstraints, where each sourceTag lists the tags it may import via onlyDependOnLibsWithTags. Leave type:testing out of every production type's allowed list.
The required direction is strict:
- New libraries never import from the old utils package. Otherwise the old package stays in every affected graph.
- New libraries never form cycles with each other. The rule reports circular imports between projects.
Start with constraints that cover only the new libraries and tighten them later. Rules made too strict too early push developers toward eslint-disable comments. Once suppressions are routine, nobody trusts the rule, and boundaries erode quietly.
// libs/util-datetime/project.json declares its tags:
// { "name": "util-datetime", "tags": ["scope:shared", "type:util"] }
// The old utils package is tagged ["scope:legacy"] so new code can be fenced off from it.
// eslint.config.js (flat config) at the workspace root
const nx = require('@nx/eslint-plugin');
module.exports = [
...nx.configs['flat/base'],
{
files: ['**/*.ts', '**/*.js'],
rules: {
'@nx/enforce-module-boundaries': [
'error',
{
depConstraints: [
// New shared libs may only import other shared libs, never scope:legacy.
{ sourceTag: 'scope:shared', onlyDependOnLibsWithTags: ['scope:shared'] },
// Pure helpers stay free of heavier layers.
{ sourceTag: 'type:util', onlyDependOnLibsWithTags: ['type:util'] },
// HTTP clients may use utils but not test helpers.
{ sourceTag: 'type:data-access', onlyDependOnLibsWithTags: ['type:util'] },
// Test helpers may build on production code; nothing above lists type:testing.
{
sourceTag: 'type:testing',
onlyDependOnLibsWithTags: ['type:util', 'type:data-access'],
},
// No constraint for scope:legacy yet: tighten it after migration starts.
],
},
],
},
},
];
Tags declared in a project.json and a flat-config @nx/enforce-module-boundaries setup whose depConstraints keep new shared libraries away from the legacy utils package and keep type:testing out of production libraries, while the rule's built-in check reports cycles between projects.
How does the Nx move generator work, and how do you migrate incrementally?
Each step below is its own pull request, so any one of them can be reviewed in isolation and reverted without unwinding the others.
Step 1: Create the target library
Generate an empty library first, for example nx g @nx/js:library, with the name and directory you chose. The generator creates the project configuration and adds a path alias to the root tsconfig. Merge this before moving any code so the alias and tags are settled ahead of time.
Step 2: Move one cohesive module
If you are relocating an entire project, use the move generator (nx g @nx/workspace:move). It updates project configuration, tsconfig path aliases, and import paths in workspace TypeScript files. Most splits carve files out of a library instead. For those, move the files by hand and rewrite imports deliberately, with a search you can review in the diff.
Step 3: Shim, then migrate in batches
Re-export the moved symbols from the old entry point so existing consumers keep compiling. Then migrate consumer imports a few projects at a time. Remove the shim last, once nothing imports through it.
What generators miss
Generators and codemods can skip:
- dynamic
import()calls - string-based references
jest.mockpaths- non-TypeScript consumers
- code outside the workspace
Because the project graph cannot see these, affected scope is unreliable here. For the first migration, run a full nx run-many -t lint test, plus typecheck if your projects define it, across every project.
Generator names and flags differ between Nx releases. Confirm them with --help and --dry-run against your installed version.
# Confirm generator names and flags for your installed Nx version first.
npx nx g @nx/js:library --help
npx nx g @nx/workspace:move --help
# PR 1: create the empty target library. Preview first, then run for real.
npx nx g @nx/js:library --directory=libs/shared/date-utils --dry-run
npx nx g @nx/js:library --directory=libs/shared/date-utils
# PR 2a (whole-project relocation only): the move generator updates
# project config, tsconfig path aliases and TS import paths.
npx nx g @nx/workspace:move --project=legacy-dates \
--destination=libs/shared/date-utils --dry-run
# PR 2b (carving files out of a library): move by hand so the diff shows it.
git mv libs/shared/utils/src/lib/date libs/shared/date-utils/src/lib/date
# PR 3: keep the old entry point compiling with a temporary re-export shim.
# Append it to the old entry point; remove it in the final PR.
echo "export * from '@acme/shared/date-utils'; // TEMP shim" \
>> libs/shared/utils/src/index.ts
# Find references the project graph and codemods cannot see:
# dynamic import(), jest.mock paths and other string-based references.
git grep -nE "(import\(|jest\.mock\(|require\()['\"]@acme/shared/utils" -- .
git grep -n "shared/utils/src/lib/date" -- .
# First migration: verify every project, not just affected ones,
# and bypass the cache so nothing is skipped on a stale result.
# Drop typecheck from the list if your projects do not define that target.
npx nx run-many -t lint test typecheck --skip-nx-cache
# Later batches, once the pattern is proven, can use affected scope.
npx nx affected -t lint test typecheck --base=origin/main
The commands for each PR in an incremental split: creating the library, moving the code with the generator or by hand, adding the re-export shim, searching for string-based references the generators miss, and running a full run-many verification across all projects.
How do you handle barrel files, re-export shims and circular dependencies?
A split only pays off if each new library exposes a small, deliberate surface. If libs/utils-date/src/index.ts does export * from './lib', consumers can reach every internal helper, and the graph records a dependency on the whole library rather than the two functions actually used. Over time the new libraries fill up with tangled imports again and recreate the monolith. Export named symbols explicitly, such as export { formatIsoDate, parseIsoDate } from './lib/iso';, and keep everything else internal.
Re-export shims need a deadline. A shim that leaves the old utils entry point forwarding to the new libraries keeps every consumer compiling, but it also keeps every old dependency edge in the graph. Any change to a new library still marks every project that imports the shim as affected, so the affected scope stays the same until consumers import the new paths directly. Give each shim an owner and a removal date. Mark it with a @deprecated JSDoc comment, which most editors surface. Add a lint rule such as ESLint's no-restricted-imports so that new imports of the old path fail review.
Splitting also exposes cycles that were hidden inside one package. There are three common fixes:
- Extract the shared piece into a lower-level library that both sides depend on.
- Invert the dependency. For example,
utils-httpdeclaresinterface RetryPolicy { shouldRetry(err: unknown): boolean }, andutils-configimplements it, soutils-httpno longer imports config. - Merge two pieces that change together and were never really separate.
Each of these fixes is real refactoring, not a mechanical move. Budget for them separately, or a schedule planned as a file shuffle will slip.
Does the split actually save CI and engineering time?
Run nx show projects --affected for the same representative change before and after the split, such as a one-line edit to the logging helper. Compare the two project lists. The drop in that count measures the gain. The number of new libraries you created does not.
Illustrative estimate (assumed numbers, not a benchmark). Assume the logging change affected 40 projects before and 6 after. Assume each affected project costs 3 CI minutes and the team lands 20 such changes a month.
Saved minutes/month = (affected before − affected after) × minutes per project × changes per month = (40 − 6) × 3 × 20 = 2,040.
Weigh that against the engineer-hours the migration took. CI savings pay back slowly. Smaller review scope usually pays back sooner, because each PR touches fewer owners.
Smaller projects mean a change invalidates fewer cache entries. Making them buildable is a separate decision with its own costs:
| Aspect | Buildable / publishable | Non-buildable |
|---|---|---|
| Build output | Own artifact, cached separately | Compiled inside the consuming app |
| Build ordering | Adds nodes to the task graph | No extra build tasks |
| Versioning | Needs versions if published | None; consumers use source |
| Release coordination | Cross-library releases to plan | Ships with the app |
Keep libraries non-buildable unless something outside the workspace consumes them or app build times demand it.
To finish the migration:
- Delete the old library, or freeze it with a lint rule that bans new imports from it.
- Add a CODEOWNERS entry for each new library.
- Document where new utilities belong so the monolith doesn't regrow.
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 split library, 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.