What are the Nx library types: non-buildable, buildable, and publishable?
Nx libraries fall into three types. The difference is not what the code does, but whether the library can be compiled on its own and what that compilation produces.
A non-buildable library has no build target. Applications import it through a path alias in the workspace's base TypeScript config, and the application's own build compiles the library's source files as if they lived inside the app. There is no intermediate artifact. This keeps configuration minimal, but every app build recompiles every library it touches.
A buildable library has its own build target that emits compiled output, typically JavaScript and type declarations, to an output directory. Nx can cache that output and, when incremental builds are configured, let the app consume it instead of recompiling the source. That reuse is the whole point of making a library buildable.
A publishable library is a buildable library that also carries what a package registry needs. That means a package name that is valid for the registry, a version, and an import path that matches the published name, so consumers outside the workspace resolve it the same way internal code does.
| Adds to config | Non-buildable | Buildable | Publishable |
|---|---|---|---|
| Build target | No | Yes | Yes |
| Output path / cached outputs | No | Yes | Yes |
| Library tsconfig used for emitting | No (type-check/lint only) | Yes | Yes |
| Package metadata (name, version) | No | Sometimes, for dependency info | Required |
| Registry-valid import path | No | No | Yes |
Generator flags, default executors, and how outputs are wired differ across Nx versions and plugins. Check what your workspace actually generates rather than assuming the table maps one-to-one onto your files.
How do non-buildable libraries and incremental builds actually work?
With a non-buildable library, the app imports it through a path alias in the workspace's base tsconfig. A typical entry in compilerOptions.paths maps @acme/billing-core to libs/billing-core/src/index.ts. The alias points at a TypeScript source file, not a compiled artifact. When the app builds, its compiler or bundler follows the alias, reads the library's source, and compiles it as part of the app. Nx sees one build target, so it caches one result. Change a single line in any library the app imports, and the app's cache key changes, and everything is recompiled together.
An incremental build changes what the alias resolves to:
- Source consumption.
apps/apiimports@acme/billing-core, which resolves tolibs/billing-core/src/index.ts. The app's compiler transpiles the library in the same build, and Nx caches only the app build. - Output consumption.
apps/apiimports@acme/billing-core, which resolves to the library's built output, such as.jsplus.d.tsfiles. That output comes from the library's ownbuildtarget, and Nx caches it separately.
In the second model, Nx runs each library's build before the app's, typically through a dependsOn: ["^build"] rule. Libraries untouched by a change hash the same as before, so Nx restores their outputs from the local or remote cache instead of rebuilding them. Only affected libraries and the app do real work.
Adding a build target to a library does not change how the app resolves imports. If the app's build still follows the base tsconfig paths to src/, the app compiles library source exactly as before, and the library builds become extra work. The app's build configuration must point resolution at the built outputs. How you do that depends on the executor or bundler, so check what your app target actually reads.
// tsconfig.base.json (workspace root): the alias points at library SOURCE
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@acme/billing-core": ["libs/billing-core/src/index.ts"]
}
}
}
SOURCE CONSUMPTION (non-buildable library)
apps/api/src/main.ts
import { invoice } from '@acme/billing-core'
|
| resolved through tsconfig.base.json paths
v
libs/billing-core/src/index.ts <- .ts source, compiled inside the app build
|
v
[ api:build ] -> one task, one cache entry for app + all imported libs
OUTPUT CONSUMPTION (incremental build)
[ billing-core:build ] -> dist/libs/billing-core (.js + .d.ts)
| own task, own cache entry; restored from the
| local or remote cache if its inputs are unchanged
| runs first via dependsOn: ["^build"]
v
apps/api/src/main.ts
import { invoice } from '@acme/billing-core'
|
| app build configured to resolve the alias to built output,
| not to libs/billing-core/src (method depends on executor/bundler)
v
[ api:build ] -> compiles only app code; reads prebuilt library output
A base tsconfig path alias that sends imports to library source, contrasted with an incremental setup where the app build resolves the same alias to the library's separately built and cached output.
When do incremental builds save time, and when do they cost more?
Whether skipping unchanged libraries pays off depends on how per-library overhead compares with the compile work that caching avoids. Each buildable library has a fixed cost even when its code is small: a process starts, type checking runs, output is written, and a cache entry is stored or restored.
Illustrative estimate (assumed numbers, not a benchmark). Assume an app with N = 40 libraries, compile cost c = 6 s per library, fixed overhead o = 4 s per library build, restore cost r = 0.5 s per cache hit, app compile a = 20 s, k = 2 changed libraries, and remote cache hit rate h = 0.9.
- From source:
T_src = a + N·c + o= 20 + 240 + 4 = 264 s - Incremental:
T_inc = a + (k + (N−k)(1−h))·(o + c) + (N−k)·h·r= 20 + 5.8 × 10 + 34.2 × 0.5 ≈ 95 s
| Scenario (same formula) | From source | Incremental |
|---|---|---|
| Large, stable libs, h = 0.9 | 264 s | ≈ 95 s |
| Small libs (c = 1 s), h = 0.9 | 64 s | ≈ 66 s |
| Cold or local-only cache (h = 0) | 264 s | 420 s |
If you change a shared low-level library, every library that depends on it is invalidated, so k grows toward N. Without a shared remote cache, each CI runner and each developer pays the cold-cache row on first build.
The opposite limit also applies. A very large app compiled as one unit can exhaust memory or run into type-checker limits. In that case, splitting the app into buildable units may be the only fix, even if the per-library overhead makes it slower on paper.
Why does dependency graph shape matter more than library count?
Library count is a weak predictor of rebuild cost. What matters is where a change lands. When a library near the bottom of the graph changes, every buildable library that depends on it, directly or transitively, has a new input hash and must rebuild. A shared-utils package with forty dependents turns a one-line fix into forty compilations. A leaf library with no dependents rebuilds only itself. Depth makes this worse, because each layer rebuilds only after the layer below it finishes, so tall graphs serialize work that parallel agents cannot absorb.
Buildable status also spreads. Incremental builds compile a library against the built output of its dependencies, so a buildable library's dependencies generally need to be buildable too. Marking one mid-level library as buildable can force build targets onto everything beneath it. A decision about one library becomes a refactor across the workspace.
Finding hot spots
Run nx graph and look for nodes with high fan-in that sit low in the graph. Then check what a typical change actually triggers. Running nx affected -t build against a branch that touches only a shared utility shows how many projects get pulled in. If routine commits to one library keep producing large affected sets, that library is your cost center.
These boundaries can conflict with ownership. Splitting a library to shrink its blast radius may cut across a team's domain, or create dependencies that your enforce-module-boundaries tags forbid. Settle the ownership and tagging model first, then tune the build around it.
#!/usr/bin/env bash
# Locate rebuild hot spots: low-level libraries with high fan-in.
set -euo pipefail
# 1. Export the project graph as JSON instead of opening the browser view.
npx nx graph --file=graph.json
# 2. Count direct dependents (fan-in) per workspace project.
# External npm packages are excluded; only workspace libraries matter here.
jq -r '
.graph.dependencies
| [ .[][] | .target | select(startswith("npm:") | not) ]
| group_by(.)
| map({project: .[0], dependents: length})
| sort_by(-.dependents)
| .[:10][]
| "\(.dependents)\t\(.project)"
' graph.json
# 3. Inspect one suspect visually: its dependents and dependencies only.
# (Opens the interactive graph focused on this project.)
# npx nx graph --focus=shared-utils
# 4. Measure blast radius for a branch that touches only shared-utils.
# Lists every project the change pulls in, without running any builds.
npx nx show projects --affected --base=main --head=HEAD
# 5. Of those, which have a build target and will actually recompile?
npx nx show projects --affected --with-target=build --base=main --head=HEAD | wc -l
# 6. When the list looks right, run the builds themselves.
# npx nx affected -t build --base=main --head=HEAD
Exports the Nx project graph to rank libraries by direct fan-in with jq. It then lists the projects, including those with a build target, that a branch touching one shared library would pull into a rebuild.
How does each library type affect backend service deployment?
Deployment is where the library types stop being an internal build detail and start shaping what ships.
With non-buildable libraries, the service's bundler resolves library imports through TypeScript path aliases and compiles that source straight into the service output. Each deployable gets one self-contained bundle. The Docker image needs that bundle, the runtime, and the third-party packages the code actually imports. Because internal libraries never exist as separate packages, nothing internal has to be installed, versioned, or copied into the image.
Buildable libraries add an intermediate artifact. Each library compiles to its own output directory, and the service build consumes that output instead of raw source. The final image can look the same as in the non-buildable case if the bundler inlines everything. If it does not, the Dockerfile has to copy each library's build output and keep import resolution working at runtime. That adds layers, and a stale library artifact can end up in a fresh image.
Publishable libraries leave the monorepo. Consumers install them from a registry at a pinned version, which brings semantic versioning, changelogs, and release automation. It also brings version skew. A service inside the repo builds against current source. An external consumer may run a release from months ago. A breaking change can pass every in-repo check and still fail in production for that consumer.
| Library type | Service image contains | Declared dependencies | Main deployment risk |
|---|---|---|---|
| Non-buildable | One bundle with library code inlined | Third-party packages only | Large bundles if imports aren't pruned |
| Buildable | Bundle, or bundle plus copied library outputs | Third-party packages; internal libs as build artifacts | Stale or missing library artifacts |
| Publishable | Library installed from registry | Pinned library version plus its own dependencies | Version skew between published and in-repo consumers |
When should you make an Nx library buildable or publishable, and when should you avoid it?
Start from non-buildable libraries and Nx's computation cache. That combination already skips unchanged work at the task level, and it adds no build targets, output paths, or artifact wiring for anyone to maintain.
When to make a library buildable
Make a library buildable only when all three of these conditions hold:
- It is large. Its compile step is a real share of each consumer's build time.
- It changes rarely compared with the apps that use it. A prebuilt artifact gets reused across many app builds instead of being rebuilt next to them.
- It slows several apps. If only one app imports it, the saving is small and you pay the setup cost anyway.
When to make a library publishable
Make a library publishable only when something outside the workspace has to install it, such as another repository, an external team, or a deployment that pulls from a registry. Publishing brings versioning and release discipline with it. Internal reuse does not justify that cost.
When to avoid buildable libraries
- Maintenance and config drift. Every buildable library has its own build config, tsconfig paths, and output settings. These slowly diverge from the apps that consume them.
- Weak remote caching. If CI agents can't share cached outputs, each agent rebuilds the libraries itself. The incremental benefit mostly disappears.
- Developer experience costs:
- Stale outputs can mask source changes that should have shown up.
- Go-to-definition can jump to emitted
.d.tsfiles instead of the source. - Source maps need extra care to point back to the original code.
- Local dev often needs a separate watch process for each library.
Alternatives worth trying first
If one large app is the bottleneck, split it into separate apps along its deployment boundaries. Also check the cache configuration first. Accurate inputs and named inputs often recover the time that buildable libraries were supposed to save.
How do you measure whether buildable libraries help your pipeline?
Start with a baseline before converting anything. Pick two or three representative changes from recent history: a one-line fix in a leaf library, a change to a widely shared library, and an edit inside an app. Replay each one on a branch and record three numbers per change.
Cold duration
Run nx affected -t build --skip-nx-cache against a fixed base commit. The --skip-nx-cache flag forces every task to execute, so the result shows the true cost of the work your graph schedules. Run it several times on the same CI runner class and take the median, because shared runners vary.
Warm duration and cache behavior
Run nx affected -t build again with the cache enabled. Nx marks cached tasks in its terminal output and prints a summary of how many tasks it restored from cache out of the total. A buildable library only pays off if its build is a cache hit on most changes that touch other code. If small edits invalidate it anyway, check its inputs before blaming the library type.
Task count
Count how many build tasks the affected run schedules. Each buildable library adds a task with its own overhead. A larger task count with a lower wall-clock time can still be a win. A larger task count with the same wall-clock time is pure cost.
Convert one library, repeat the same changes, and compare. Keep the conversion only where the warm and affected-change numbers improve. This limits refactoring effort to the libraries where the data shows a gain.
#!/usr/bin/env bash
# Measure one replayed change: cold median, warm run, and affected project count.
# Run on the same CI runner class before and after converting a library.
set -euo pipefail
BASE="${BASE:-a1b2c3d}" # fixed base commit (placeholder SHA)
HEAD="${HEAD:-HEAD}" # branch with the replayed change
RUNS="${RUNS:-3}" # repeat cold runs; shared runners vary
OUT="nx-measure-$(date +%Y%m%d-%H%M%S)"
mkdir -p "$OUT"
# Cold: --skip-nx-cache forces every scheduled build task to execute.
for i in $(seq 1 "$RUNS"); do
start=$(date +%s)
npx nx affected -t build --base="$BASE" --head="$HEAD" --skip-nx-cache \
> "$OUT/cold-$i.log" 2>&1
echo $(( $(date +%s) - start )) >> "$OUT/cold-seconds.txt"
done
# Median of the cold runs (middle value after sorting).
median=$(sort -n "$OUT/cold-seconds.txt" | awk '{a[NR]=$1} END {print a[int((NR+1)/2)]}')
# Warm: same command with the cache enabled. The previous cold runs populated it.
start=$(date +%s)
npx nx affected -t build --base="$BASE" --head="$HEAD" > "$OUT/warm.log" 2>&1
warm=$(( $(date +%s) - start ))
# Affected projects for this change. Dependency builds that Nx also schedules
# are not included here; read the run summary in the logs for the full task total.
affected=$(npx nx show projects --affected --base="$BASE" --head="$HEAD" | wc -l)
echo "cold median: ${median}s | warm: ${warm}s | affected projects: ${affected}"
echo "Run summary with cache restore counts:"
tail -n 15 "$OUT/warm.log"
A bash script that replays one change against a fixed base commit, records the median cold duration with --skip-nx-cache and a warm duration with the cache enabled, counts affected projects, and keeps the logs so you can compare the Nx run summaries before and after converting a library.
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 buildable libraries, 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.