Nx Bun Integration
Integrate Bun runtime into Nx monorepos with deterministic plugin setup, executor configuration, migration from Node.js toolchains, and cache-aware build/test workflows; use when adding the nx-bun plugin, converting projects, or standardizing Bun targets across Nx workspaces.
npx skills add github:pantheon-org/tekhne --skill repository-mgmt--nx--bun-integrationNavigation hub for integrating Bun into Nx workspaces.
When to Use
- You are adding Bun projects to an existing Nx workspace.
- You are converting Node.js projects to Bun executors.
- You need cache-aware build, run, and test targets with
@nx-bun/nx. - You need predictable migration guidance for package-manager and runtime changes.
When Not to Use
- The task is Bun runtime API usage without Nx integration concerns.
- The workspace is intentionally standardized on Node.js executors only.
Workflow
- Install
@nx-bun/nxand initialize the plugin. - Generate or convert projects to Bun executors.
- Configure cache inputs and outputs for build/test targets.
- Validate serve, build, and test on one project: run
nx build my-api && nx test my-api && nx serve my-apiand confirm all three exit with code 0 before proceeding. If validation fails: check executor configuration inproject.json, runnx resetto clear stale cache, and retry. Resolve all failures before rolling out. - Roll out to affected projects and enforce anti-pattern checks.
Quick Commands
Install and Initialize Plugin
bun add -D @nx-bun/nx
nx g @nx-bun/nx:init --unitTestRunner=bun
Expected: plugin is installed and generators/executors are available.
Generate Bun Application
nx g @nx-bun/nx:application api --directory=apps/backend --tags=runtime:bun,type:app
Expected: Bun-ready app with Nx project configuration.
Convert Existing Project
nx g @nx-bun/nx:convert-to-bun --project=my-api
Expected: project targets move to Bun executors while preserving Nx target structure.
Verify Build/Test/Run
nx build my-api
nx test my-api
nx serve my-api
Expected: build outputs generated, tests run under Bun test runner, serve target starts.
Run Affected in CI-style
bun nx affected -t lint,test,build --base=main --parallel=3
Expected: only changed projects execute with Nx scheduling.
Anti-Patterns
NEVER mix npm/yarn installs with Bun in the same migration scope
- WHY: mixed lockfiles and resolver behavior cause drift and non-reproducible installs.
- BAD:
npm installafterbun addin a Bun-migrated workspace. - GOOD: use Bun consistently for migrated projects and clean old lockfiles per migration policy.
NEVER run Jest and bun test on the same suite without boundary
- WHY: duplicate test ownership creates inconsistent results and CI noise.
- BAD: keep Jest target unchanged while adding
@nx-bun/nx:testto same files. - GOOD: split test ownership by project/path and decommission old target deliberately.
NEVER skip cache metadata on Bun build/test targets
- WHY: missing outputs/inputs reduces cache hit reliability and slows CI.
- BAD: executor configured with no
outputsand no tuned inputs. - GOOD: declare outputs and reference production/default named inputs as appropriate.
NEVER assume SQLite behavior is identical to Node DB wrappers
- WHY: transaction handling and connection patterns differ across libraries.
- BAD: copy Node pooling assumptions directly into Bun SQLite implementation.
- GOOD: use Bun SQLite patterns validated in reference examples.
NEVER rely on hot reload defaults for production validation
- WHY: hot/watch modes hide startup and lifecycle differences seen in production runs.
- BAD: validate only with
hot: truelocal serve. - GOOD: run non-hot production-oriented build and run validation before release.
Gotchas
Bun.spawnis async and returns a handle; choose stdout/stderr piping explicitly.- Migration can leave stale lockfiles; remove obsolete lockfiles as part of a controlled cutover.
- Nx daemon/cache can mask executor changes; use
nx resetafter plugin updates.
References
| Topic | Reference |
|---|---|
| Bun runtime APIs, SQLite, and WebSockets | references/bun-runtime-api.md |
| Nx executor and caching configuration | references/nx-executor-configuration.md |
| Node.js to Bun migration checklist | references/migration-from-node.md |
| Bun testing in Nx | references/testing-with-bun.md |
Explicit NEVER/WHY/consequence triplets with side-by-side bad/good examples. Generic warnings score low — concrete failure modes with real impact (security, correctness, performance) score high.
Runtime validation via eval scenarios proving the skill actually changes agent behaviour. Requires evals/ directory, instructions.json, ≥3 scenarios, and ≥80% instruction coverage in summary.json.
Appropriate rigidity for the skill type: strict rules for critical/security skills, balanced steps for process skills, flexible options for tool skills. Mismatched calibration (too rigid or too loose) reduces score.
Expert-only knowledge the AI couldn't derive on its own — domain-specific patterns, production gotchas, decision frameworks, and non-obvious tool behaviour. High scores mean <5% redundancy with what the model already knows.
A clear philosophy plus numbered step-by-step workflows with explicit entry/exit points. Should answer: what is the core principle, how to execute it, and when (and when not) to apply it.
Rich activation keywords and trigger scenarios in the description so the skill fires when needed. Best descriptions read like an exhaustive list of the tasks and concepts that should invoke this skill.
Copy-paste-ready code, complete runnable examples, real file paths and commands. Pseudocode and abstract descriptions score low — concrete, executable content scores high.
SKILL.md as a <100-line navigation hub pointing to focused references/ files. Content should be lazy-loaded on demand, not front-loaded. Includes actionable 'When to Use' conditions per reference.
Proper frontmatter, single-task focus, activation keywords, and cross-harness portability. Skills must work across 40+ agentic harnesses without hardcoded paths or agent-specific references.
Expert-only knowledge the AI couldn't derive on its own — domain-specific patterns, production gotchas, decision frameworks, and non-obvious tool behaviour. High scores mean <5% redundancy with what the model already knows.
A clear philosophy plus numbered step-by-step workflows with explicit entry/exit points. Should answer: what is the core principle, how to execute it, and when (and when not) to apply it.
Explicit NEVER/WHY/consequence triplets with side-by-side bad/good examples. Generic warnings score low — concrete failure modes with real impact (security, correctness, performance) score high.
Proper frontmatter, single-task focus, activation keywords, and cross-harness portability. Skills must work across 40+ agentic harnesses without hardcoded paths or agent-specific references.
SKILL.md as a <100-line navigation hub pointing to focused references/ files. Content should be lazy-loaded on demand, not front-loaded. Includes actionable 'When to Use' conditions per reference.
Appropriate rigidity for the skill type: strict rules for critical/security skills, balanced steps for process skills, flexible options for tool skills. Mismatched calibration (too rigid or too loose) reduces score.
Rich activation keywords and trigger scenarios in the description so the skill fires when needed. Best descriptions read like an exhaustive list of the tasks and concepts that should invoke this skill.
Copy-paste-ready code, complete runnable examples, real file paths and commands. Pseudocode and abstract descriptions score low — concrete, executable content scores high.
No eval scenarios available.
Bun Runtime API Notes for Nx Projects
Use this reference when implementing runtime details after selecting the Nx Bun integration workflow.
Bun.serve in Nx Applications
- Prefer explicit host and port configuration for deterministic local and CI behavior.
- Keep request handling logic in project libs when possible to preserve testability.
Example:
Bun.serve({
port: Number(process.env.PORT ?? 3000),
fetch() {
return new Response("ok");
},
});
Bun.file and Bun.write
- Use
Bun.file()for read operations and avoid unnecessary Node fs wrappers. - Use
Bun.write()for generated artifacts when writing from scripts or codegen tasks.
const text = await Bun.file("./config.json").text();
await Bun.write("./dist/status.txt", "ready\n");
SQLite Integration Notes
- Use prepared statements for user-provided values.
- Wrap multi-statement write flows in explicit transaction blocks.
const stmt = db.prepare("SELECT * FROM users WHERE id = ?");
const user = stmt.get(userId);
WebSocket Considerations
- Validate payloads before state mutation.
- Keep room/session lifecycle logic separate from protocol adapters.
- Ensure disconnect handling is deterministic in long-running Bun servers.
Runtime Caveats
- Container memory limits can expose different behavior vs local hot reload.
- Verify production startup path without watch mode before release.
Migration from Node.js Tooling to Bun in Nx
Use this checklist to migrate safely and keep CI deterministic.
Migration Checklist
- Install and initialize
@nx-bun/nx. - Choose migration scope (single project, bounded set, or full workspace).
- Convert target executors using
convert-to-bun. - Standardize package-manager usage for migrated scope.
- Validate run/build/test targets and cache behavior.
- Remove obsolete scripts and lockfiles per policy.
Compatibility Notes
- Some Node-centric dependencies may assume Node runtime behavior.
- Validate native modules and startup scripts before broad rollout.
- Keep mixed-runtime boundaries explicit through project tags.
Package Manager Transition
- Move from
npm/yarncommands tobuncommands for migrated projects. - Avoid parallel lockfile ownership in the same migration boundary.
Rollout Strategy
- Start with one low-risk application.
- Capture CI timing and failure-mode differences.
- Expand migration only after baseline stability is verified.
Nx Executor Configuration with nx-bun Plugin
Use this reference for detailed target configuration.
Core Executors
@nx-bun/nx:run: run/serve applications with Bun runtime@nx-bun/nx:build: bundle applications/libraries@nx-bun/nx:test: execute tests with Bun test runner
Example Target Configuration
{
"targets": {
"build": {
"executor": "@nx-bun/nx:build",
"outputs": ["{options.outputPath}"],
"options": {
"entrypoints": ["apps/api/src/main.ts"],
"outputPath": "dist/apps/api",
"target": "bun",
"format": "esm"
}
},
"serve": {
"executor": "@nx-bun/nx:run",
"options": {
"buildTarget": "api:build",
"hot": true,
"watch": true
}
},
"test": {
"executor": "@nx-bun/nx:test",
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
"options": {
"timeout": 5000,
"bail": true
}
}
}
}
Caching Strategy
- Always define
outputsfor cacheable targets. - Keep named inputs consistent with repo standards.
- Include shared config artifacts (
bunfig.toml,tsconfig.base.json) where relevant.
Example nx.json excerpt:
{
"targetDefaults": {
"build": {
"cache": true,
"inputs": ["production", "^production"]
},
"test": {
"cache": true,
"inputs": ["default", "^production"]
}
}
}
Verification
bun nx show project <name> --webto inspect inferred/effective targets.nx resetafter executor/plugin updates.
Testing with Bun in Nx Workspaces
Use this reference for Bun test runner integration details.
Test Target Basics
@nx-bun/nx:test runs tests with Bun’s built-in runner and supports standard Nx invocation.
nx test my-lib
nx test my-lib --watch
nx test my-lib --timeout=10000
Suggested Options
bail: fail fast to shorten feedback loops.timeout: tune per-project for integration-heavy suites.watch: local development only.
Coverage and Outputs
- Configure coverage output paths for predictable artifact collection.
- Keep coverage directories under workspace conventions.
Avoiding Jest Conflicts
- Do not maintain duplicate test targets for the same files.
- During migration, keep clear project/path ownership for each runner.
CI Guidance
- Prefer non-watch execution.
- Run
nx affected -t testto reduce CI load. - Record flaky test behavior before and after runner migration.