Bun
All-in-one JavaScript/TypeScript toolkit: runtime, package manager, test runner, bundler.
Quick Navigation
| Topic |
Reference |
| Package Manager |
references/package-manager.md |
| Project Setup |
references/project-scaffolding.md |
| Development |
references/development.md |
| Module System |
references/module-system.md |
| TypeScript & JSX |
references/typescript-jsx.md |
| Configuration |
references/bunfig.md |
| HTTP Server |
references/http-server.md |
| Browser Automation |
references/webview.md |
| WebSockets |
references/websockets.md |
| File I/O |
references/file-io.md |
| SQLite |
references/sqlite.md |
| S3 Storage |
references/s3.md |
| Redis |
references/redis.md |
| Low-Level Network |
references/networking-low-level.md |
| Fetch API |
references/fetch.md |
| Shell Scripts |
references/shell.md |
| Spawn Process |
references/spawn.md |
| Workers |
references/workers.md |
| Native FFI |
references/native-interop.md |
| C/C++ Compile |
references/cc.md |
| Transpiler |
references/transpiler.md |
| Plugins |
references/plugins.md |
| FS Router |
references/file-system-router.md |
| Environment Vars |
references/env.md |
| Utilities |
references/utilities.md |
| Node.js Compat |
references/nodejs-compat.md |
When to Use Bun
- Running TypeScript/JSX without build step
- Fast HTTP server with native routing
- Headless browser automation with native input events
- SQLite database (embedded, no deps)
- WebSocket server/client
- S3-compatible storage (AWS, R2, MinIO)
- Redis caching/pub-sub
- Cross-platform shell scripts
- In-process cron scheduling
- Markdown parsing (v1.3.8+)
- Native library calls via FFI
Core Advantages
- 4x faster startup than Node.js
- Native TypeScript/JSX — no tsconfig needed
- ESM + CommonJS — both work seamlessly
- Web APIs built-in — fetch, WebSocket, etc.
- 30x faster installs than npm
Quick Start
# Run TypeScript directly
bun run index.ts
# Install packages
bun install
# Run package.json script
bun run dev
# Execute package binary
bunx cowsay "Hello"
# Run tests
bun test
# Build for production
bun build ./index.ts --outdir ./dist
# Bundle analysis for LLMs (v1.3.8+)
bun build ./index.ts --metafile-md --outdir ./dist
Critical Rules
| Don't |
Do |
http.createServer() |
Bun.serve() |
fs.readFileSync() |
Bun.file().text() |
better-sqlite3 |
bun:sqlite |
child_process.exec() |
Bun.$ or Bun.spawn() |
dotenv |
Built-in .env support |
Release Highlights (1.4.x)
- Rust rewrite: first release of the Rust port. Lower peak memory (mimalloc allocator, 13-48% less under load), ~2x faster startup, 5x lower idle CPU, and 1,500+ more passing Node.js test-suite tests.
- HTTP/2 & HTTP/3:
Bun.serve() serves HTTP/1.1 and HTTP/2 on the same port via ALPN over TLS (v1.4.1); HTTP/3 is experimental via http3: true. fetch() can use HTTP/2/3 clients behind feature flags.
- Serve static directories:
routes: { "/static/*": { dir: "./public" } } with sendfile, ETag, Range, conditional requests, and index.html.
- CLI:
bun run --parallel for concurrent scripts; bun audit fix, bun dedupe, bun prune, bun pm diff, bun pm licenses for package maintenance.
bun test: --parallel, --isolate, --shard=M/N, --timings, --changed (diff-based), --retry, and jest.useFakeTimers().
bun build: built-in React Compiler (--react-compiler), barrel-import optimization, tree-shaking through export * as and dynamic import(), --min-chunk-size, and module preloading.
bun install: --linker=isolated global virtual store, --offline / --prefer-offline, bun add --catalog, nested overrides, and selfContained workspaces.
- New runtime APIs:
Bun.Terminal (PTY), Bun.Archive (tar), Bun.JSON5/JSONL/JSONC/XML/TOML parsers, streaming Bun.write(path, response), WebSocket.pause()/resume(), crypto.argon2, and post-quantum ML-DSA/ML-KEM in crypto.subtle.
Release Highlights (1.3.14)
Bun.Image: built-in image decoding, transforms, and encoding for common formats with no npm dependency or native addon build step.
- Test workflow: the
1.3.13 line improves dependency-aware filtering for changed-file test runs, which matters when you rely on partial local verification.
- Patch-line runtime work:
1.3.13-1.3.14 continues compatibility and performance work on top of the 1.3.12 WebView/cron/Markdown release line.
Release Highlights (1.3.12)
Bun.WebView: native headless browser automation with WebKit on macOS and Chrome/Chromium via CDP on all platforms.
Bun.cron() callback mode: in-process scheduler with no-overlap execution, UTC semantics, hot-reload cleanup, and Disposable job handles.
- Markdown in terminal:
bun ./file.md and Bun.markdown.ansi() make terminal-native rendering a first-class workflow.
- Networking/runtime: UDP error/truncation handling, Node-compatible unix-socket lifecycle, proxy tunnel reuse, and
Bun.serve() accept/perf improvements.
Essential Recipes
HTTP Server
Bun.serve({
port: 3000,
fetch(req) {
const url = new URL(req.url);
if (url.pathname === "/api/data") {
return Response.json({ ok: true });
}
return new Response("Not Found", { status: 404 });
},
});
File Operations
// Read
const content = await Bun.file("data.txt").text();
// Write
await Bun.write("output.txt", "Hello World");
// JSON
const config = await Bun.file("config.json").json();
SQLite
import { Database } from "bun:sqlite";
const db = new Database("app.db");
db.run("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)");
const insert = db.prepare("INSERT INTO users (name) VALUES (?)");
insert.run("Alice");
const users = db.query("SELECT * FROM users").all();
WebSocket Server
Bun.serve({
fetch(req, server) {
if (server.upgrade(req)) return;
return new Response("Upgrade failed", { status: 400 });
},
websocket: {
message(ws, message) {
ws.send(`Echo: ${message}`);
},
},
});
Shell Commands
import { $ } from "bun";
// Simple command
const files = await $`ls -la`.text();
// With variables (auto-escaped)
const name = "my file.txt";
await $`cat ${name}`;
// Piping
await $`cat data.csv | grep "pattern" | wc -l`;
S3 Storage
import { s3 } from "bun";
// Upload
await s3.file("uploads/doc.pdf").write(data);
// Download
const content = await s3.file("uploads/doc.pdf").text();
// Presigned URL
const url = s3.presign("uploads/doc.pdf", { expiresIn: 3600 });
Redis
import { redis } from "bun";
await redis.set("key", "value");
const value = await redis.get("key");
await redis.expire("key", 3600);
Testing
import { expect, test, describe } from "bun:test";
describe("math", () => {
test("2 + 2 = 4", () => {
expect(2 + 2).toBe(4);
});
});
Configuration (bunfig.toml)
[run]
watch = true
[install]
registry = "https://registry.npmjs.org"
[test]
coverage = true
Environment Variables
# .env files loaded automatically
DATABASE_URL=postgres://localhost/mydb
// Access
Bun.env.DATABASE_URL;
process.env.DATABASE_URL;
import.meta.env.DATABASE_URL;
Links
1---2name: bun3description: Bun JavaScript/TypeScript runtime and all-in-one toolkit. Covers runtime, package manager, bundler, test runner, HTTP server, WebSockets, SQLite, S3, Redis, file I/O, shell scripting, FFI, Markdown parser. Use when running JS/TS with Bun, managing packages, bundling, testing, or using Bun-specific APIs. Keywords: bun, bunx, bun install, bun run, bun test, bun build, Bun.serve, Bun.file, bun:sqlite, Bun.markdown.4---5
6# Bun
7
8All-in-one JavaScript/TypeScript toolkit: runtime, package manager, test runner, bundler.
9
10## Quick Navigation
11
12| Topic | Reference |
13| ------------------ | ------------------------------------ |
14| Package Manager | `references/package-manager.md` |
15| Project Setup | `references/project-scaffolding.md` |
16| Development | `references/development.md` |
17| Module System | `references/module-system.md` |
18| TypeScript & JSX | `references/typescript-jsx.md` |
19| Configuration | `references/bunfig.md` |
20| HTTP Server | `references/http-server.md` |
21| Browser Automation | `references/webview.md` |
22| WebSockets | `references/websockets.md` |
23| File I/O | `references/file-io.md` |
24| SQLite | `references/sqlite.md` |
25| S3 Storage | `references/s3.md` |
26| Redis | `references/redis.md` |
27| Low-Level Network | `references/networking-low-level.md` |
28| Fetch API | `references/fetch.md` |
29| Shell Scripts | `references/shell.md` |
30| Spawn Process | `references/spawn.md` |
31| Workers | `references/workers.md` |
32| Native FFI | `references/native-interop.md` |
33| C/C++ Compile | `references/cc.md` |
34| Transpiler | `references/transpiler.md` |
35| Plugins | `references/plugins.md` |
36| FS Router | `references/file-system-router.md` |
37| Environment Vars | `references/env.md` |
38| Utilities | `references/utilities.md` |
39| Node.js Compat | `references/nodejs-compat.md` |
40
41## When to Use Bun
42
43- Running TypeScript/JSX without build step
44- Fast HTTP server with native routing
45- Headless browser automation with native input events
46- SQLite database (embedded, no deps)
47- WebSocket server/client
48- S3-compatible storage (AWS, R2, MinIO)
49- Redis caching/pub-sub
50- Cross-platform shell scripts
51- In-process cron scheduling
52- **Markdown parsing** (v1.3.8+)
53- Native library calls via FFI
54
55## Core Advantages
56
57- **4x faster startup** than Node.js
58- **Native TypeScript/JSX** — no tsconfig needed
59- **ESM + CommonJS** — both work seamlessly
60- **Web APIs built-in** — fetch, WebSocket, etc.
61- **30x faster installs** than npm
62
63## Quick Start
64
65```bash
66# Run TypeScript directly
67bun run index.ts
68
69# Install packages
70bun install
71
72# Run package.json script
73bun run dev
74
75# Execute package binary
76bunx cowsay "Hello"
77
78# Run tests
79bun test
80
81# Build for production
82bun build ./index.ts --outdir ./dist
83
84# Bundle analysis for LLMs (v1.3.8+)
85bun build ./index.ts --metafile-md --outdir ./dist
86```
87
88## Critical Rules
89
90| Don't | Do |
91| ---------------------- | ------------------------ |
92| `http.createServer()` | `Bun.serve()` |
93| `fs.readFileSync()` | `Bun.file().text()` |
94| `better-sqlite3` | `bun:sqlite` |
95| `child_process.exec()` | `Bun.$` or `Bun.spawn()` |
96| `dotenv` | Built-in `.env` support |
97
98## Release Highlights (1.4.x)
99
100- **Rust rewrite**: first release of the Rust port. Lower peak memory (mimalloc allocator, 13-48% less under load), ~2x faster startup, 5x lower idle CPU, and 1,500+ more passing Node.js test-suite tests.
101- **HTTP/2 & HTTP/3**: `Bun.serve()` serves HTTP/1.1 and HTTP/2 on the same port via ALPN over TLS (v1.4.1); HTTP/3 is experimental via `http3: true`. `fetch()` can use HTTP/2/3 clients behind feature flags.
102- **Serve static directories**: `routes: { "/static/*": { dir: "./public" } }` with sendfile, ETag, Range, conditional requests, and index.html.
103- **CLI**: `bun run --parallel` for concurrent scripts; `bun audit fix`, `bun dedupe`, `bun prune`, `bun pm diff`, `bun pm licenses` for package maintenance.
104- **`bun test`**: `--parallel`, `--isolate`, `--shard=M/N`, `--timings`, `--changed` (diff-based), `--retry`, and `jest.useFakeTimers()`.
105- **`bun build`**: built-in React Compiler (`--react-compiler`), barrel-import optimization, tree-shaking through `export * as` and dynamic `import()`, `--min-chunk-size`, and module preloading.
106- **`bun install`**: `--linker=isolated` global virtual store, `--offline` / `--prefer-offline`, `bun add --catalog`, nested overrides, and `selfContained` workspaces.
107- **New runtime APIs**: `Bun.Terminal` (PTY), `Bun.Archive` (tar), `Bun.JSON5`/`JSONL`/`JSONC`/`XML`/`TOML` parsers, streaming `Bun.write(path, response)`, `WebSocket.pause()`/`resume()`, `crypto.argon2`, and post-quantum ML-DSA/ML-KEM in `crypto.subtle`.
108
109## Release Highlights (1.3.14)
110
111- **`Bun.Image`**: built-in image decoding, transforms, and encoding for common formats with no npm dependency or native addon build step.
112- **Test workflow**: the `1.3.13` line improves dependency-aware filtering for changed-file test runs, which matters when you rely on partial local verification.
113- **Patch-line runtime work**: `1.3.13`-`1.3.14` continues compatibility and performance work on top of the `1.3.12` WebView/cron/Markdown release line.
114
115## Release Highlights (1.3.12)
116
117- **`Bun.WebView`**: native headless browser automation with WebKit on macOS and Chrome/Chromium via CDP on all platforms.
118- **`Bun.cron()` callback mode**: in-process scheduler with no-overlap execution, UTC semantics, hot-reload cleanup, and `Disposable` job handles.
119- **Markdown in terminal**: `bun ./file.md` and `Bun.markdown.ansi()` make terminal-native rendering a first-class workflow.
120- **Networking/runtime**: UDP error/truncation handling, Node-compatible unix-socket lifecycle, proxy tunnel reuse, and `Bun.serve()` accept/perf improvements.
121
122## Essential Recipes
123
124### HTTP Server
125
126```ts
127Bun.serve({
128 port: 3000,
129 fetch(req) {
130 const url = new URL(req.url);
131 if (url.pathname === "/api/data") {
132 return Response.json({ ok: true });
133 }
134 return new Response("Not Found", { status: 404 });
135 },
136});
137```
138
139### File Operations
140
141```ts
142// Read
143const content = await Bun.file("data.txt").text();
144
145// Write
146await Bun.write("output.txt", "Hello World");
147
148// JSON
149const config = await Bun.file("config.json").json();
150```
151
152### SQLite
153
154```ts
155import { Database } from "bun:sqlite";
156
157const db = new Database("app.db");
158db.run("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)");
159
160const insert = db.prepare("INSERT INTO users (name) VALUES (?)");
161insert.run("Alice");
162
163const users = db.query("SELECT * FROM users").all();
164```
165
166### WebSocket Server
167
168```ts
169Bun.serve({
170 fetch(req, server) {
171 if (server.upgrade(req)) return;
172 return new Response("Upgrade failed", { status: 400 });
173 },
174 websocket: {
175 message(ws, message) {
176 ws.send(`Echo: ${message}`);
177 },
178 },
179});
180```
181
182### Shell Commands
183
184```ts
185import { $ } from "bun";
186
187// Simple command
188const files = await $`ls -la`.text();
189
190// With variables (auto-escaped)
191const name = "my file.txt";
192await $`cat ${name}`;
193
194// Piping
195await $`cat data.csv | grep "pattern" | wc -l`;
196```
197
198### S3 Storage
199
200```ts
201import { s3 } from "bun";
202
203// Upload
204await s3.file("uploads/doc.pdf").write(data);
205
206// Download
207const content = await s3.file("uploads/doc.pdf").text();
208
209// Presigned URL
210const url = s3.presign("uploads/doc.pdf", { expiresIn: 3600 });
211```
212
213### Redis
214
215```ts
216import { redis } from "bun";
217
218await redis.set("key", "value");
219const value = await redis.get("key");
220await redis.expire("key", 3600);
221```
222
223### Testing
224
225```ts
226import { expect, test, describe } from "bun:test";
227
228describe("math", () => {
229 test("2 + 2 = 4", () => {
230 expect(2 + 2).toBe(4);
231 });
232});
233```
234
235## Configuration (bunfig.toml)
236
237```toml
238[run]
239watch = true
240
241[install]
242registry = "https://registry.npmjs.org"
243
244[test]
245coverage = true
246```
247
248## Environment Variables
249
250```bash
251# .env files loaded automatically
252DATABASE_URL=postgres://localhost/mydb
253```
254
255```ts
256// Access
257Bun.env.DATABASE_URL;
258process.env.DATABASE_URL;
259import.meta.env.DATABASE_URL;
260```
261
262## Links
263
264- [Documentation](https://bun.sh/docs)
265- [Releases](https://github.com/oven-sh/bun/releases)
266- [GitHub](https://github.com/oven-sh/bun)
267- [Discord](https://bun.sh/discord)