Skip to main content

Migrazione da Node.js a Bun: gotchas

Migrating from Node.js to Bun without surprises: package manager and lockfiles, CommonJS versus ES Modules, divergent APIs, async behavior, and native addons.

What do you think about this article?

Migrazione da Node.js a Bun: gotchas
Bun Runtime 2027Photos:Brett SaylesPexels

At a Glance

Migrating from Node.js to Bun without surprises: package manager and lockfiles, CommonJS versus ES Modules, divergent APIs, async behavior, and native addons.

Migrating from Node.js to Bun: Common Gotchas

Migrating from Node.js to Bun is an important architectural decision that promises superior performance and a more modern developer experience. However, the transition is not always straightforward. Bun, although built on WebKit JSC (the same engine as Safari), introduces significant differences in runtime behavior, module management, and npm ecosystem compatibility. This article analyzes the most common gotchas developers encounter during migration, providing concrete strategies to avoid or resolve them.

Based on experiences from teams that have already completed this transition, we have identified 12 recurring problem categories: differences in built-in APIs, package manager handling, divergent async behaviors, dependency compatibility, and test setup configuration. Ignoring these aspects can lead to insidious bugs that manifest only in production, loss of expected performance, and prolonged debugging cycles.

What You'll Discover in This Article

  • The 3 critical gotchas that impact migration more than others
  • Differences in memory management and garbage collection
  • Common npm library incompatibilities and how to resolve them
  • Testing strategies with Bun (Bun test vs Jest compatibility)
  • TypeScript configuration and project setup
  • Monitoring performance post-migration
  • When to migrate and when to stay on Node.js

Gotcha #1: Package Manager and Diverging Lockfiles

The first and most impactful gotcha concerns package management. Bun includes a proprietary package manager (bun install) that differs significantly from npm and yarn. Bun's lockfile (bun.lockb, binary format) is not compatible with npm-lock.json.

When migrating a Node.js project to Bun, you must choose: continue using npm with Bun as runtime, or adopt bun install as your package manager. The choice has profound implications:


# Scenario 1: Bun runtime + npm/yarn package manager
bun install --from=npm    # Converts package-lock.json to bun.lockb
npm install                # But then npm resynchronizes the lock

# Scenario 2: Bun runtime + Bun package manager (pure)
rm package-lock.json bun.lockb
bun install                # Creates bun.lockb from scratch
    

The problem emerges when teams use mixed tools: one developer with npm, another with bun install. This causes lockfile conflicts and different resolution of transitive dependencies. In our observations, teams that **maintain npm as package manager but use Bun for execution** report the best balance between compatibility and performance.

Gotcha #2: CommonJS vs ES Modules

Bun has better ES module support than Node.js, but also differences in CommonJS fallback. Many legacy libraries still use CommonJS, and Bun's behavior in resolving require() is different from Node.js.


// File: utils.mjs (ES module)
export const sum = (a, b) => a + b;

// File: app.js (CommonJS)
// Node.js (works)
const { sum } = require('./utils.mjs');

// Bun (might fail or behave differently)
// Solution: use dynamic import explicitly
const { sum } = await import('./utils.mjs');
    

Another issue: libraries that check the "exports" field in package.json and conditionally choose CommonJS vs ESM based on require() vs import. Bun might choose a different branch than Node.js, causing different versions of the same module in the dependency graph.

Gotcha #3: Divergent Built-in APIs

Bun implements a subset of Node.js APIs, but also introduces new proprietary APIs. Missing built-in APIs are often a surprise:


// Node.js (works)
import { createReadStream } from 'fs';
const stream = createReadStream('file.txt');
stream.on('data', (chunk) => { ... });

// Bun: Streams work but behavior differs slightly
// Bun prefers Web Streams model (ReadableStream)
import { createReadStream } from 'fs';
const file = Bun.file('file.txt');
const stream = file.stream();

// Another: Node.js events.EventEmitter
// Bun has native EventTarget (Web API) but Node.js has EventEmitter
// Compatibility: Bun polyfills EventEmitter, but this binding behavior may differ
    

Environment variables, URL resolution, path handling — these aspects all have subtle differences. For example, Bun resolves relative paths from the project root (where bunfig.toml lives), not always from the current file like Node.js.

Gotcha #4: Async Behavior and Microtask Queue

Bun and Node.js have slightly different lifespans for microtasks. This impacts Promise chains, setTimeout/setImmediate ordering, and final process cleanup.


// Execution order differs between Node.js and Bun
Promise.resolve()
  .then(() => console.log('microtask 1'))
  .then(() => console.log('microtask 2'));

setImmediate(() => console.log('immediate'));
setTimeout(() => console.log('timeout'), 0);

// Node.js order: microtask 1, microtask 2, timeout, immediate
// Bun order: microtask 1, microtask 2, immediate, timeout
// Note: final lifeloop behavior is CRITICAL
    

If your app relies on the specific order of event loop phases (setImmediate before setTimeout), migration to Bun will break behavior. This is particularly critical in apps that close database connections or file streams on termination.

Gotcha #5: Native Dependencies and Node Addons

Bun does NOT natively support Node.js addons (libraries compiled with node-gyp, like sqlite3, bcrypt, etc.). If your project depends on compiled addons, migration to Bun is blocked until the library introduces Bun-native bindings.


# These work on Node.js (with precompiled binary npm)
npm install sqlite3
npm install bcrypt

# On Bun, they may fail:
bun install sqlite3   # May compile with issues
bun install bcrypt    # May not find binding for Bun

# Solution: Use pure JavaScript alternatives
# instead of sqlite3: use better-sqlite3 Wasm or bun native bindings (if available)
# instead of bcrypt: try @noble/hashes (pure JS) for hashing, though slower
    

Gotcha #6: Testing Framework and Setup

Bun includes an integrated test runner (bun test), but Jest remains the gold standard for compatibility. Many projects inherit consolidated Jest configuration, and migrating to Bun test runner requires test rewriting.


// File: test/sum.test.js
// Jest style (Node.js)
const { sum } = require('../utils');
describe('sum', () => {
  it('adds two numbers', () => {
    expect(sum(2, 3)).toBe(5);
  });
});

// Bun test style (integrated)
import { describe, it, expect } from 'bun:test';
import { sum } from '../utils';
describe('sum', () => {
  it('adds two numbers', () => {
    expect(sum(2, 3)).toBe(5);
  });
});

// Critical difference: setup/teardown, mocking, snapshot testing
// Bun has fewer plugins and less flexibility than Jest at this time
    

If you use Jest with complex plugins (ts-jest, @testing-library, jest-mock-extended), porting to Bun test is not trivial. I recommend running both test runners during migration to validate equivalence.

Gotcha #7: Memory Management and Long-Running Processes

Bun uses WebKit's garbage collector (SamplingHeapProfiler), different from V8. In long-running processes (Express server, background worker), memory leak detection behavior differs. Memory profiling tools and heap snapshot formats are incompatible.


# Node.js: Generates V8 heap snapshot (analyzable with Chrome DevTools)
node --heap-prof app.js

# Bun: No equivalent of heap-prof, memory profiling is manual
# Solution: Monitor via external metrics (Prometheus + node-exporter)
# or use Bun built-in memory tracking
console.log('Memory usage:', Bun.memory()); // { rss, heapUsed, heapTotal }
    

For long-running apps (production server), I recommend load testing before adopting Bun. Verify memory footprint, GC pause time, and behavior under stress.

Gotcha #8: Environment Configuration and Dotenv

Bun has built-in .env support via Bun.env, but differs from dotenv npm + Node.js behavior:


# Node.js
NODE_ENV=production node app.js

# Bun (auto-loads from .env)
bun app.ts

# But command-line variables:
# Node.js: variables go before the command
NODE_ENV=test node app.js

# Bun: especially for bun-specific args, different
NODE_ENV=test bun app.ts
    

Gotcha #9: HTTP/HTTPS and Certificates

Bun.serve() is the native way for HTTP, but libraries like Express/Fastify that use require('http') work, with slightly different behavior in buffering and chunking.


// Express on Node.js
const express = require('express');
const app = express();
app.get('/data', (req, res) => {
  res.json({ message: 'hello' });
});
app.listen(3000);

// Express on Bun (works, but lower performance than Bun.serve)
// Solution: Use Bun.serve and manual porting for maximum performance
export default {
  port: 3000,
  async fetch(req) {
    const url = new URL(req.url);
    if (url.pathname === '/data') {
      return Response.json({ message: 'hello' });
    }
    return new Response('404');
  }
};
    

Gotcha #10: Build Tools and Transpilation

Bun includes an integrated transpiler (for TypeScript, JSX), but build tools like Webpack, Vite, etc. have divergent behaviors when run on Bun runtime vs Node.js runtime.

Additionally, if your project has a Makefile or build script that invokes npm scripts, it might fail on Bun because PATH and environment variables are different.

Gotcha #11: Debugging and Profiling

Node.js inspector protocol (used by Chrome DevTools, VS Code debugger) is supported by Bun only partially. Integrated debuggers may not work like on Node.js.


# Node.js debugging
node --inspect app.js
# Chrome DevTools connects to chrome://inspect

# Bun debugging (supported but less mature)
bun --inspect app.ts
# Limited support, different from Node.js
    

Gotcha #12: Deploy Pipeline and CI/CD

If you use GitHub Actions, GitLab CI or other CI/CD with official Node.js Docker image, transitioning to Bun requires changing the base image or manually installing Bun. Dockerfile must be rewritten.

Recommended Migration Strategies

Decision Matrix: When to Migrate to Bun

Scenario Migration Recommended Risk
Greenfield app with zero native dependencies ✓ Yes Low
Stable Node.js app with native dependencies (sqlite3, bcrypt) ✗ No High — blocking
Simple CLI tool (no compiled dependencies) ✓ Yes Low
Consolidated Express/Fastify server with large test suite ~ Maybe Medium — requires porting and validation
Monolith backend with many microservices ✗ No High — runtime fragmentation

Pre-Migration Checklist

Before deciding on migration, run this checklist:

  • Audit npm dependencies: identify which use Node addons (npm list | grep gyp)
  • Verify Bun support for all critical libraries
  • Setup parallelized test: run Jest and Bun test simultaneously for delta detection
  • Measure performance baseline (startup, memory, throughput) on Node.js
  • Identify critical testing, debugging, deploy requirements
  • Plan rollback strategy (there must be an easy way back)

FAQ: Frequently Asked Questions about Bun Migration

Q: Will Bun replace Node.js?
A: Unlikely in the medium term. Bun is an excellent alternative for specific use cases (CLI, scripts, greenfield), but Node.js remains the standard runtime for production web apps due to mature ecosystem and stability. Bun is a choice, not a mandatory replacement.

Q: If I use Express on Bun, do I really get the performance boost?
A: No, not fully. The bottleneck becomes the Express framework, not the runtime. Bun shines when you use Bun.serve() for HTTP server. If porting to Bun.serve, you gain 2-5x throughput; if staying with Express, the gain is marginal (~10-20%).

Q: Can I use Bun for only some services in a monolith?
A: Yes, but carefully. If one is Node.js and one is Bun, you must manage divergent behaviors, different dependency versions, and operational complexity. I recommend starting with an isolated microservice (e.g., a CLI tool or worker) to validate the solution.

Q: How long does a typical migration take?
A: Depends on codebase size and dependency complexity. For small apps (<5k LOC, few dependencies): 1-2 weeks. For medium codebase (20-50k LOC): 1-2 months with parallelized testing. For large apps (100k+ LOC, many dependencies): 2-3 months, and risk increases significantly.

Q: If I encounter a bug during migration, who helps?
A: The Bun community is active, but commercial support is still limited. I recommend documenting bugs well, contributing to Bun repo if possible, and having a ready rollback plan to Node.js.

Commenti

Caricamento commenti...

Sign in to comment

Discuss this article in the community

Join the Telegram group to discuss with other developers, ask questions and share your experiences.

Did you like this article?

Explore other content on the blog or discover my projects