
This guide details the process of migrating existing Node.js microservices to Bun 1.2 for production deployment. We will cover HTTP server migration, bun:sqlite integration, WebSocket server implementation, npm package compatibility, native C++ addon considerations, Node.js API gap mitigation, and Docker containerization with performance benchmarks.
Bun 1.2 offers significant performance advantages over Node.js, primarily due to its underlying Zig implementation and JavaScriptCore engine. Key benefits include:
bun install, bun run, bun test, and bun build streamline development workflows.bun:sqlite, bun:ffi, bun:serve provide highly optimized primitives.Bun's native HTTP server (Bun.serve) is a high-performance alternative to Node.js's http module or frameworks like Express. It's designed for minimal overhead.
// src/node-server.ts
import express from 'express';
import { readFileSync } from 'fs';
import path from 'path';
const app = express();
const port = process.env.PORT ? parseInt(process.env.PORT) : 3000;
app.use(express.json());
app.get('/', (req, res) => {
res.send('Hello from Node.js Express!');
});
app.get('/data', (req, res) => {
try {
const data = readFileSync(path.join(__dirname, '../data.json'), 'utf8');
res.json(JSON.parse(data));
} catch (error) {
console.error('Error reading data:', error);
res.status(500).send('Internal Server Error');
}
});
app.listen(port, () => {
console.log(`Node.js Express server listening on port ${port}`);
});
Bun.serve) EquivalentMigrating to Bun.serve involves adapting request/response handling. Bun's Request and Response objects are Web-standard Request and Response objects.
// src/bun-server.ts
import { readFileSync } from 'fs';
import path from 'path';
const port = process.env.PORT ? parseInt(process.env.PORT) : 3000;
const server = Bun.serve({
port,
async fetch(req: Request): Promise<Response> {
const url = new URL(req.url);
if (url.pathname === '/') {
return new Response('Hello from Bun!', { status: 200 });
}
if (url.pathname === '/data') {
try {
const dataPath = path.join(import.meta.dir, '../data.json');
const data = readFileSync(dataPath, 'utf8');
return new Response(data, {
headers: { 'Content-Type': 'application/json' },
status: 200,
});
} catch (error) {
console.error('Error reading data:', error);
return new Response('Internal Server Error', { status: 500 });
}
}
// Example for POST request with JSON body
if (url.pathname === '/submit' && req.method === 'POST') {
try {
const body = await req.json();
console.log('Received JSON body:', body);
return new Response(JSON.stringify({ message: 'Data received', data: body }), {
headers: { 'Content-Type': 'application/json' },
status: 200,
});
} catch (error) {
console.error('Error parsing JSON body:', error);
return new Response('Bad Request: Invalid JSON', { status: 400 });
}
}
return new Response('Not Found', { status: 404 });
},
error(error: Error): Response {
console.error('Bun server error:', error);
return new Response('Internal Server Error', { status: 500 });
},
});
console.log(`Bun server listening on port ${server.port}`);
Note the use of import.meta.dir for path resolution, which is Bun's equivalent to Node.js's __dirname.
bun:sqliteBun provides a highly optimized, native SQLite client via bun:sqlite. This eliminates the need for external npm packages like sqlite3 or better-sqlite3, which often involve native C++ addons and compilation steps.
better-sqlite3) Example// src/node-sqlite.ts
import Database from 'better-sqlite3';
import path from 'path';
const dbPath = path.join(__dirname, '../data.db');
const db = new Database(dbPath);
db.exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL
);
`);
export function insertUser(name: string, email: string) {
const stmt = db.prepare('INSERT INTO users (name, email) VALUES (?, ?)');
const info = stmt.run(name, email);
return info.lastInsertRowid;
}
export function getUsers() {
const stmt = db.prepare('SELECT * FROM users');
return stmt.all();
}
// Example usage
if (require.main === module) {
insertUser('Alice', 'alice@example.com');
insertUser('Bob', 'bob@example.com');
console.log('Users:', getUsers());
db.close();
}
bun:sqlite) Equivalentbun:sqlite offers a similar API surface, making migration straightforward.
// src/bun-sqlite.ts
import { Database } from 'bun:sqlite';
import path from 'path';
const dbPath = path.join(import.meta.dir, '../data.db');
const db = new Database(dbPath);
db.run(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL
);
`);
export function insertUser(name: string, email: string) {
const query = db.query('INSERT INTO users (name, email) VALUES (?, ?)');
const result = query.run(name, email);
// Bun's result object for INSERT operations might differ slightly
// For SQLite, lastInsertRowid is often available on the database object or via PRAGMA
// For simplicity, we'll assume a successful run implies insertion.
// A more robust solution would query for the last_insert_rowid()
const lastIdQuery = db.query('SELECT last_insert_rowid() as id;');
return (lastIdQuery.get() as { id: number }).id;
}
export function getUsers() {
const query = db.query('SELECT * FROM users');
return query.all();
}
// Example usage
if (import.meta.main) {
insertUser('Charlie', 'charlie@example.com');
insertUser('David', 'david@example.com');
console.log('Users:', getUsers());
db.close();
}
Bun's Bun.serve also includes first-class support for WebSockets, providing a high-performance, integrated solution.
ws library) Example// src/node-ws.ts
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', ws => {
console.log('Client connected (Node.js WS)');
ws.on('message', message => {
console.log(`Received: ${message}`);
ws.send(`Echo: ${message}`);
});
ws.on('close', () => console.log('Client disconnected (Node.js WS)'));
ws.on('error', error => console.error('WebSocket error (Node.js WS):', error));
});
console.log('Node.js WebSocket server listening on port 8080');
Bun.serve WebSocket) EquivalentBun's WebSocket API is integrated directly into Bun.serve, using a websocket configuration object.
// src/bun-ws.ts
const server = Bun.serve({
port: 8080,
fetch(req, server) {
const url = new URL(req.url);
if (url.pathname === '/ws') {
const success = server.upgrade(req, {
data: {
// Optional: attach any data to the WebSocket connection
connectedAt: Date.now(),
},
});
if (success) {
return; // Bun handles the WebSocket connection
}
}
return new Response('Not Found', { status: 404 });
},
websocket: {
open(ws) {
console.log(`Client connected (Bun WS). Connected at: ${ws.data.connectedAt}`);
ws.send('Welcome to Bun WebSocket!');
},
message(ws, message) {
console.log(`Received: ${message}`);
ws.send(`Echo: ${message}`);
},
close(ws, code, message) {
console.log(`Client disconnected (Bun WS). Code: ${code}, Message: ${message}`);
},
error(ws, error) {
console.error('WebSocket error (Bun WS):', error);
},
// Optional: perMessageDeflate, maxPayloadLength, idleTimeout
// idleTimeout: 30, // seconds
},
});
console.log(`Bun WebSocket server listening on port ${server.port}`);
Bun aims for high compatibility with existing npm packages. Most pure JavaScript packages will work without modification.
This is where compatibility can be challenging. Node.js native addons (.node files) are compiled against Node.js's N-API (Node-API) and V8 engine. Bun uses JavaScriptCore and its own FFI (Foreign Function Interface) for native interactions.
bun:ffi: For critical performance-sensitive operations, you might need to rewrite the native logic using bun:ffi to call into a shared library (.so, .dylib, .dll) compiled specifically for Bun. This is a complex undertaking.bcrypt (Native Addon)bcrypt is a common package that uses native C++ addons for performance.
// src/node-bcrypt.ts
import bcrypt from 'bcrypt';
async function hashPassword(password: string) {
const saltRounds = 10;
const hashedPassword = await bcrypt.hash(password, saltRounds);
console.log('Hashed password (Node.js):', hashedPassword);
return hashedPassword;
}
async function verifyPassword(password: string, hash: string) {
const isMatch = await bcrypt.compare(password, hash);
console.log('Password match (Node.js):', isMatch);
return isMatch;
}
if (require.main === module) {
(async () => {
const hash = await hashPassword('mysecretpassword');
await verifyPassword('mysecretpassword', hash);
await verifyPassword('wrongpassword', hash);
})();
}
When running bun install bcrypt, Bun will attempt to install it. If it fails to build the native addon, you'll see an error. For such cases, you might need to use a pure JS alternative or a different approach.
bcrypt with potential issues)Bun can sometimes run Node.js native addons if they are pre-compiled for the correct architecture and N-API version, but this is not guaranteed and often fails. A safer approach is to use a pure JS alternative or a different library.
For bcrypt, a pure JS implementation like bcryptjs is often a viable fallback, though it will be slower.
// src/bun-bcryptjs.ts
import bcrypt from 'bcryptjs'; // Using bcryptjs for Bun compatibility
async function hashPassword(password: string) {
const saltRounds = 10;
const hashedPassword = await bcrypt.hash(password, saltRounds);
console.log('Hashed password (Bun/bcryptjs):', hashedPassword);
return hashedPassword;
}
async function verifyPassword(password: string, hash: string) {
const isMatch = await bcrypt.compare(password, hash);
console.log('Password match (Bun/bcryptjs):', isMatch);
return isMatch;
}
if (import.meta.main) {
(async () => {
const hash = await hashPassword('mysecretpassword');
await verifyPassword('mysecretpassword', hash);
await verifyPassword('wrongpassword', hash);
})();
}
While Bun aims for high Node.js compatibility, some APIs are not fully implemented or behave differently.
child_process: Most common functions like exec, spawn, fork are supported. Edge cases or specific options might differ.vm module: Limited support. If your application heavily relies on vm.runInContext or similar, this might be a blocker.domain module: Deprecated in Node.js, not supported in Bun.cluster module: Bun does not have a direct equivalent for cluster. For multi-core utilization, you'd typically run multiple Bun processes and use a load balancer, or leverage Bun's built-in multi-threading for certain tasks (though not for HTTP server scaling in the same way cluster works).fs module: Largely compatible, but some less common options or synchronous variants might have subtle differences. Always test file system heavy operations.net / tls: Basic client/server functionality is present, but advanced configurations might require adjustments.Mitigation Strategy:
Containerizing Bun applications is straightforward. The official oven/bun Docker images provide a lean base.
# Dockerfile.node
FROM node:20-alpine AS base
WORKDIR /app
COPY package.json bun.lockb* ./
RUN npm install --frozen-lockfile
COPY . .
EXPOSE 3000
CMD ["node", "src/node-server.ts"]
# Dockerfile.bun
FROM oven/bun:1.2.0-alpine AS base
WORKDIR /app
COPY package.json bun.lockb* ./
# Bun automatically installs dependencies on 'bun run' if not present,
# but explicit install is good practice for build stage.
RUN bun install --frozen-lockfile
COPY . .
EXPOSE 3000
CMD ["bun", "run", "src/bun-server.ts"]
We'll compare image size and runtime memory usage for a simple HTTP server.
docker build -t node-app -f Dockerfile.node .
docker build -t bun-app -f Dockerfile.bun .
docker images | grep "node-app\|bun-app"
docker stats):
docker run -d --name node-server -p 3001:3000 node-app
docker run -d --name bun-server -p 3002:3000 bun-app
docker stats --no-stream node-server bun-server
# Stop containers after collecting stats
docker stop node-server bun-server && docker rm node-server bun-server
| Metric | Node.js (20-alpine) | Bun (1.2.0-alpine) | Notes |
|---|---|---|---|
| Image Size | ~180 MB | ~100 MB | Bun's base image is significantly smaller. |
| Startup Time | ~500 ms | ~50 ms | Bun is orders of magnitude faster. |
| Memory Usage | ~30 MB | ~10 MB | For a simple HTTP server, Bun uses less. |
| RPS (ab -c 50 -n 10000) | ~2500 RPS | ~7000 RPS | Bun.serve is highly optimized. |
Note: These are illustrative benchmarks. Actual results depend heavily on application complexity, workload, and hardware.
Error: Cannot find module '...':
tsconfig.json paths are not correctly configured for Bun.tsconfig.json paths are correctly mapped and baseUrl is set.package.json exports field for imported packages.bun install or npm install if using a mix.node_modules resolution can be stricter; ensure all dependencies are explicitly listed.require(), ensure the file extension is present (e.g., require('./module.js')).Native Addon Failures:
.node file) directly with Bun.bcryptjs instead of bcrypt).bun:ffi (advanced).process.env Differences:
process.env is largely compatible, but some Node.js-specific environment variables might not be present or behave identically.Buffer API Inconsistencies:
Buffer, its underlying implementation might have subtle differences from Node.js's, especially with older or less common Buffer methods.Uint8Array and TextEncoder/TextDecoder where possible.Buffer manipulation.fs.watch / fs.watchFile Behavior:
Bun.serve vs. Node.js HTTP Server keepAliveTimeout:
Bun.serve has an idleTimeout for WebSockets and a general connection timeout. Node.js has keepAliveTimeout. Default values and behavior might differ.idleTimeout in Bun.serve for WebSockets.fetch handler if needed.A development team is migrating a Node.js microservice to Bun 1.2. The microservice frequently scales up and down based on traffic spikes and is deployed as serverless functions. Which of Bun's core advantages would provide the most significant immediate benefit in this specific production scenario?
Q: Can I use existing Node.js frameworks like Express or NestJS with Bun?
Bun.serve for HTTP handling. For optimal performance, migrate HTTP endpoints to Bun.serve directly or use a Bun-native framework. bun install will typically handle framework dependencies.Q: How does Bun handle TypeScript compilation in production?
.ts files with bun run src/index.ts. For production, bun build can compile your TypeScript into JavaScript, which can then be run. This eliminates the need for tsc or ts-node.Q: What about database drivers other than SQLite (e.g., PostgreSQL, MySQL)?
pg, mysql2, sequelize, prisma). These are typically pure JavaScript or rely on standard network protocols, so they generally work well with Bun. bun install will manage their dependencies.Q: Is bun:ffi a viable replacement for all native Node.js addons?
bun:ffi is powerful but requires significant effort. You need to write C/C++/Rust code, compile it into a shared library (.so, .dylib, .dll), and then define the function signatures in TypeScript for bun:ffi to call. It's a solution for performance-critical, isolated native logic, not a drop-in replacement for complex Node.js addons.Q: How do I debug a Bun application in production?
--inspect or --inspect-brk (e.g., bun --inspect src/index.ts) and connect a debugger (like VS Code's debugger or Chrome DevTools). This provides a familiar debugging experience similar to Node.js.Clean AI CLI logs, build cron expressions, decode JWTs, and calculate chmod permissions offline.

Low-latency global backends with Turso and libSQL: embedded SQLite replicas, edge read consistency, and HTTP replication protocol benchmarks.
Read more
Migrating from Redis to Valkey 8: zero-downtime replication cutover, throughput and latency benchmarks, and cluster slot compatibility.
Read more
A comprehensive guide to modern database seeding strategies using Prisma and TypeScript. We explore idempotency, Faker.js integration, complex relational data handling, and performance optimization for large seed scripts.
Read more