What does Bun do inside an Nx workspace?
Bun can take on three roles in an Nx workspace, and each is a separate decision. As a package manager, bun install resolves dependencies, populates node_modules, and writes the Bun lockfile in place of npm, pnpm or Yarn. As a runtime, bun run and bun <file> execute scripts and TypeScript entry points directly. As a test runner, bun test replaces Jest or Vitest for the projects you choose.
Nx keeps doing the same work it does today. It builds the project graph, schedules targets in dependency order, computes cache hashes and decides which projects are affected by a change. Bun runs underneath individual targets. It does not replace the orchestrator.
+---------------------------------------------------+
| Nx CLI / daemon / plugins (runs on Node) |
| project graph · task scheduling · cache · affected|
+---------------------------------------------------+
| | |
install step target command test target
v v v
+-------------+ +---------------+ +-------------+
| bun install | | bun run / bun | | bun test |
| lockfile | | <file> | | |
+-------------+ +---------------+ +-------------+
This article adopts the roles in that order because each one depends on less than the next. Switching the package manager changes only how node_modules gets built. Switching the runtime changes how your code executes. Switching the test runner changes test semantics, mocks and coverage output. Taking them one at a time means a regression points to a single change, and you can revert that change without undoing the others.
Nx itself and most of its plugins still expect Node to be installed, so adopting Bun adds a second toolchain to your machines and CI images. It does not remove Node.
+------------------------------------------------------------------+
| Nx CLI / daemon / plugins (runs on Node) |
| project graph | task scheduling | cache hashing | affected |
+------------------------------------------------------------------+
| | |
install step target command test target
| | |
v v v
+------------------+ +--------------------+ +------------------+
| bun install | | bun run/bun <file> | | bun test |
| package manager | | runtime | | test runner |
| node_modules | | scripts and TS | | in place of |
| + bun lockfile | | entry points | | Jest or Vitest |
+------------------+ +--------------------+ +------------------+
| | |
v v v
+------------------------------------------------------------------+
| Node: required by Nx and plugins + Bun: added toolchain |
+------------------------------------------------------------------+
Nx, its daemon and its plugins run on Node and keep the project graph, scheduling, caching and affected detection, while Bun runs underneath individual targets as the package manager, script runtime and test runner, so the machine needs both toolchains.
Who should adopt Bun in Nx, and when should you avoid it?
Bun is worth that cost when it replaces something you would otherwise maintain separately. Backend services that already run on Bun in production gain the most, because the workspace finally matches the deploy target. Teams whose CI time is dominated by dependency installs or by small, fast unit tests also benefit, since Bun's installer and test runner are the parts most likely to shorten a feedback loop. Small-to-medium suites written against describe/it/expect with few mocks usually port with minor edits.
Delay adoption if your workspace leans on the official Nx Jest, Vitest, webpack or esbuild plugins and their generators. Those generators scaffold Node-oriented configuration, and you would have to maintain the Bun equivalents by hand. Large Jest suites that use module mocking, fake timers or jsdom environments rarely port cleanly, because Bun's Jest compatibility does not cover every edge case. Native addons built against Node's ABI may fail to load or need rebuilding. Developing on Bun while deploying on Node causes environment drift: code that passes locally can hit runtime differences in production. Finally, confirm that your Nx version parses Bun's lockfile before you rely on it. If it does not, the project graph and affected detection can silently miss dependency changes.
| Role | What you gain | What you give up | Main risk |
|---|---|---|---|
| Package manager | Faster installs, single lockfile | Mature npm/pnpm tooling around the lockfile | Nx misreading the Bun lockfile, giving a wrong project graph |
| Runtime | Native TypeScript execution, fast startup | Exact Node API parity | Drift between Bun in dev and Node in production |
| Test runner | Fast runs, built-in expect |
Nx Jest/Vitest generators and executors | Mocking, timer and DOM behavior differing from Jest |
How do you set up Bun as the package manager for an Nx workspace?
Start at the root package.json. List your project globs in the workspaces field, for example apps/* and libs/*. Then reference internal packages with the workspace: protocol, such as "@acme/db": "workspace:*". This makes Bun link the local copy instead of fetching a published version from the registry, and it makes an unresolvable internal dependency fail at install time.
Delete package-lock.json, pnpm-lock.yaml and yarn.lock, then run bun install. Nx infers the package manager from whichever lockfile sits at the root. A leftover lockfile from another tool can make Nx pick the wrong one, and the project graph will then disagree with what is actually installed.
Invoke Nx through the installed package, using bunx nx or a root script such as bun run build. This changes only the launcher. The Nx CLI and its daemon still run on Node, so you need Node installed on developer machines and CI agents.
Lockfile format
Older Bun releases write a binary bun.lockb, and newer ones write a text bun.lock. You cannot review or hand-merge the binary file. When it conflicts, regenerate it with bun install. Teammates on different Bun versions can rewrite the lockfile back and forth on every install, so pin one Bun version for the whole team and CI. Before committing, check which format your Bun writes and confirm your Nx version can parse it.
trustedDependencies
Bun skips dependency lifecycle scripts unless the package is trusted. The usual candidates are native addons and packages that download platform binaries. When a needed script is skipped, the install still succeeds, and the failure shows up later at runtime as a missing binary or .node file. Run bun pm untrusted to list the blocked scripts. Add the packages you have reviewed to trustedDependencies, either by hand or with bun pm trust <package>, and reinstall.
#!/usr/bin/env bash
# Switch an existing Nx workspace to Bun as the package manager.
set -euo pipefail
# 1. Root package.json: workspace globs, internal links, trusted scripts.
# (Shown as a full file for clarity; merge into your real one.)
cat > package.json <<'EOF'
{
"name": "acme-monorepo",
"private": true,
"workspaces": ["apps/*", "libs/*"],
"scripts": { "build": "nx run-many -t build" },
"dependencies": { "@acme/db": "workspace:*" },
"trustedDependencies": ["@acme/native-addon"]
}
EOF
# 2. Remove other tools' lockfiles so Nx detects Bun from the root lockfile.
rm -f package-lock.json pnpm-lock.yaml yarn.lock
# 3. Install. This writes bun.lockb or bun.lock, depending on your Bun version.
bun --version
bun install
ls bun.lock* # confirm which format was written before committing
# 4. List dependency lifecycle scripts that Bun skipped.
bun pm untrusted
# 5. After reviewing a package, trust it. This adds it to trustedDependencies
# and runs its skipped scripts.
bun pm trust @acme/native-addon
# 6. Run Nx through the installed package. Only the launcher changes;
# the Nx CLI and daemon still require Node.
node --version
bunx nx show projects
bun run build
Converts an Nx workspace to Bun: it declares workspaces and workspace: links, removes the other tools' lockfiles, installs, reviews and trusts the blocked lifecycle scripts, and then invokes Nx through Bun while Nx itself still runs on Node.
How do you run bun test as a cached Nx target?
Define the target with the nx:run-commands executor in each project's project.json, setting command to bun test and cwd to {projectRoot}. The cwd matters because Bun discovers test files and reads bunfig.toml relative to the directory it runs in. Without it, a run started from the workspace root can pick up the wrong config or tests from other projects. If you prefer inferred targets, add a test script to the project's package.json. Nx runs that script from the project directory automatically, and you configure caching in nx.json.
Caching only works if Nx knows everything that can change the result. Declare these as inputs:
- the project's source and test files
- the project's
bunfig.toml - the root lockfile, as
{workspaceRoot}/bun.lock, orbun.lockbin older setups
If bunfig.toml enables coverage, list its coverage directory as an output, for example {projectRoot}/coverage. That way a cache hit restores the report instead of leaving it missing.
Bun strips TypeScript types and runs the code without checking them, so a passing bun test says nothing about type errors. Add a separate typecheck target that runs tsc --noEmit -p tsconfig.json. Then, in targetDefaults, mark test, typecheck and build as cacheable with matching inputs. Give build a dependsOn on typecheck so CI can run nx affected -t test typecheck build as one pipeline.
Expect gaps when you port Jest suites to bun:test:
- Function mocks:
jest.fnand spies mostly work. - Module mocks: these use
mock.module, which does not have the same hoisting semantics asjest.mock. - Fake timers: coverage is incomplete.
- Snapshots: they may need regenerating.
- DOM tests: these need a preload such as happy-dom configured in
bunfig.toml.
{
"name": "api",
"targets": {
"test": {
"executor": "nx:run-commands",
"cache": true,
"options": { "command": "bun test", "cwd": "{projectRoot}" },
"inputs": [
"{projectRoot}/src/**/*",
"{projectRoot}/test/**/*",
"{projectRoot}/bunfig.toml",
"{workspaceRoot}/bun.lock"
],
"outputs": ["{projectRoot}/coverage"]
},
"typecheck": {
"executor": "nx:run-commands",
"cache": true,
"options": { "command": "bunx tsc --noEmit -p tsconfig.json", "cwd": "{projectRoot}" },
"inputs": [
"{projectRoot}/src/**/*",
"{projectRoot}/test/**/*",
"{projectRoot}/tsconfig.json",
"{workspaceRoot}/bun.lock"
]
},
"build": {
"executor": "nx:run-commands",
"cache": true,
"dependsOn": ["typecheck"],
"options": { "command": "bun build ./src/index.ts --outdir dist", "cwd": "{projectRoot}" },
"inputs": ["{projectRoot}/src/**/*", "{workspaceRoot}/bun.lock"],
"outputs": ["{projectRoot}/dist"]
}
}
}
A project.json with cached test, typecheck and build targets. Each target runs from the project root and declares explicit inputs and outputs. Build depends on typecheck, so tsc catches the type errors that Bun skips.
How do you make Nx caching and affected detection work with Bun?
Nx builds its project graph from your source files and from the lockfile. The lockfile becomes "external nodes": one per package version, linked to the projects that import them. When the lockfile changes between two commits, Nx compares the old and new versions, finds which packages moved, and marks the projects that depend on them as affected. If your Nx version cannot parse Bun's lockfile, the graph still builds but those external nodes are missing or incomplete. The failure is silent. A dependency bump may mark nothing as affected, or it may fall back to marking everything, and neither shows up as an error. Check that your Nx version supports the lockfile format your Bun version writes. Newer Bun releases write a text bun.lock, and older ones write a binary bun.lockb.
As a safety net, add {workspaceRoot}/bun.lock and {workspaceRoot}/bunfig.toml to sharedGlobals in nx.json, and reference sharedGlobals from your default named input. bunfig.toml controls test preloads, registry and install behavior, so a change there should invalidate cached results.
Verify it
- Bump one dependency used by a single project and run
nx affected -t test. Only that project and its dependents should run. - Run
nx graphand confirm the package appears as an external node. - Edit
bunfig.toml, then rerun. You should see cache misses across the board.
Make CI reproducible
- Install strictly. Run
bun install --frozen-lockfileso CI fails if the lockfile and the manifests disagree. - Cache both layers. Cache Bun's install cache (
~/.bun/install/cacheby default) alongside the Nx cache. - Pin Bun. Use the same Bun version in CI setup and in local tool-version files.
- Pin Node too. The Nx CLI and daemon still run on Node, so provision and pin it the same way.
- Run the same commands. Use the
nx affectedcommands developers run locally, with explicit--baseand--head.
{
"$schema": "./node_modules/nx/schemas/nx-schema.json",
"namedInputs": {
"sharedGlobals": [
"{workspaceRoot}/bun.lock",
"{workspaceRoot}/bunfig.toml"
],
"default": ["{projectRoot}/**/*", "sharedGlobals"],
"production": [
"default",
"!{projectRoot}/**/*.test.ts",
"!{projectRoot}/**/*.spec.ts"
]
},
"targetDefaults": {
"build": {
"dependsOn": ["^build"],
"inputs": ["production", "^production"],
"cache": true
},
"test": {
"inputs": ["default", "^production"],
"cache": true
}
}
}
An nx.json that puts bun.lock and bunfig.toml in sharedGlobals and feeds them into the default input, so changing either file invalidates cached build and test results.
How do you migrate one project to Bun and roll back safely?
Treat the migration as a trial on one project rather than a workspace-wide switch.
Migration checklist
- Pick a low-risk project. Choose a library with plain unit tests and few mocks, timers or DOM dependencies. That way a failure points at Bun, not at test complexity.
- Add
bun testas a second target. Keep the existing Jest or Vitest target. Running both on the same commit gives you a direct comparison. - Compare results on your own repo. Check the pass/fail counts first. Then time cold runs (
--skip-nx-cache) and warm runs separately. Any speedup is only worth something if your test suite, CI machines and cache hit rate show it, so don't rely on numbers from elsewhere. - Fix compatibility gaps. Common sources are module mocking, fake timers, snapshot formats and config-driven transforms. If a fix needs a workaround in every file, count that as a cost.
- Switch CI to the new target. Keep the old target defined so you can still run it.
- Retire the old target only after a stable period. Wait until you have seen flaky-test patterns and a dependency upgrade or two.
Rollback by role
- Package manager: Restore the previous lockfile and the
packageManagerfield, delete Bun's lockfile, and reinstall cleanly. - Runtime: Revert any executor or command changes so targets invoke Node again.
- Tests: Point CI back at the retained Jest or Vitest target.
- Install scripts: Remove any
trustedDependenciesentries you added inpackage.json.
Weigh the cost
Nx caching already skips most repeated test runs, and remote caching cuts install time further. Set any gain against the cost of hand-maintaining targets and losing the plugin generators and migrations that keep official executors up to date.
What are the alternatives to using Bun in an Nx workspace?
Four combinations are realistic, and they differ mainly in how far you step outside the paths Nx officially maintains.
| Option | Plugin support | Lockfile reviewability | Nx graph compatibility risk | Toolchain count | Maintenance cost |
|---|---|---|---|---|---|
| npm, pnpm or Yarn with official Nx test plugins | Full: generators, executors, migrations | Text lockfiles with readable diffs | Low | One runtime, one package manager | Lowest; nx migrate covers most upgrades |
| Bun as package manager only, Node runtime, Jest or Vitest | Test plugins unchanged | Depends on the lockfile format your Bun version writes | Moderate; lockfile parsing drives the graph | Two | Low to moderate |
| Bun runtime for selected services | Mixed; Bun projects use hand-written targets | Unchanged if you keep the existing package manager | Low to moderate, limited to those projects | Two runtimes | Moderate; two sets of runtime behaviour to test |
All-in: install, runtime and bun test |
Few official integrations | As in the package-manager-only row | Highest | One | Highest; you maintain the targets yourself |
The "package manager only" option is a common first step. Install speed improves, and test execution stays on tooling that Nx migrations already handle. Its risk comes from how Nx reads the lockfile to build the project graph, so verify affected detection after every Bun upgrade.
Running Bun only on selected services fits teams that want a faster startup or Bun's built-in APIs for a few backend processes. The rest of the repo is unaffected.
Large teams that depend on generators and automated migrations should stay on an established package manager. Small teams that are comfortable owning their target definitions can go all-in, as long as they accept that every Nx upgrade needs manual checking.
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 bun workspace, 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.