Bun: runtime, bundler & tests

VerifiedSafe

Practical guide to Bun: installation, package management with bun.lock, HTTP servers via Bun.serve, tests, and Node.js migration, including common pitfalls.

Sby Skills Guide Bot
DevelopmentIntermediate
11/16/2026
Claude CodeCursorWindsurfCopilotCodex
#bun#javascript-runtime#package-manager#typescript#http-server

Recommended for

Automated summary

Walks an agent through installing and using Bun as a JavaScript/TypeScript runtime, package manager, bundler and test runner.

Strengths

  • Precise, version-checked commands for installing Bun, scaffolding a project, managing dependencies and enforcing lockfile consistency in CI.
  • A complete, internally consistent server example combining Bun.serve(), parameterised routes, bun:sqlite and Bun.password.
  • Explicit security hygiene: binding to loopback by default, reading the install script before running it, handling trustedDependencies and install.minimumReleaseAge.
  • Calls out Node.js compatibility gaps and the migration from the binary lockfile to the text-based bun.lock.

Limitations

  • The bundler and test runner are advertised in the description but no bun build or bun test commands or examples are actually provided.
  • Node.js compatibility caveats are flagged but never enumerated, leaving the agent without a concrete decision criterion.
  • The source text cuts off mid-sentence on Bun.password.verify, so the authentication guidance is incomplete.
When to use it

Use it when starting or migrating a JS/TS project to Bun, managing dependencies with bun install, or writing an HTTP API with Bun.serve.

When not to use it

Skip it if you need real guidance on bundling or testing with Bun, or if the target environment requires Node.js semantics that Bun has not been shown to match.

Security analysis

Safe
Quality score90/100

The skill is documentation for Bun with normal development commands (installing packages, running a local server, tests, bundling). It explicitly advises against piping the Bun install script directly into a shell and recommends binding development servers to loopback. The sample password is clearly illustrative, and there is no obfuscation, destructive command, credential exfiltration, or safety-disabling instruction.

No concerns found

How this analysis is made

Examples

Scaffold a Bun API server
Create a new Bun project with bun init, then write a server.ts using Bun.serve with a /health route and a /api/users/:id route backed by bun:sqlite, bound to 127.0.0.1 on port 3000.
Migrate a Node project to Bun
Switch this Node.js repo over to Bun: convert the binary bun.lockb to bun.lock, run bun install, and tell me which dependencies need entries in trustedDependencies because they rely on postinstall scripts.
Harden dependency installs in CI
Set up our CI install step with Bun using a frozen lockfile and bun audit, and configure install.minimumReleaseAge in bunfig.toml so brand-new package releases are held back.

name: bun description: >- Assists with using Bun as an all-in-one JavaScript/TypeScript runtime, package manager, bundler, and test runner. Use when building HTTP servers, managing packages, running tests, or migrating from Node.js. Trigger words: bun, bun serve, bun install, bun test, bun build, javascript runtime, bun runtime. license: Apache-2.0 compatibility: "Bun 1.4 on macOS, Linux or Windows (x64, arm64)" metadata: author: terminal-skills repository: https://github.com/oven-sh/bun version: "1.1.0" category: development tags: "bun, javascript-runtime, package-manager, bundler, typescript"

Bun

Overview

Bun is a single binary that is a JavaScript/TypeScript runtime, a package manager, a bundler and a Jest-compatible test runner. It runs .ts and .tsx files directly, reads .env files, and ships built-ins such as Bun.serve(), bun:sqlite and Bun.password. It targets Node.js compatibility, so most npm packages work, but not every Node API behaves identically. Checked against Bun 1.4.4.

Instructions

Install and start a project

npm install -g bun            # or: brew install oven-sh/bun/bun   (macOS, Linux)
bun --version                 # 1.4.x
bun init -y                   # package.json, tsconfig.json, index.ts, bun.lock
bun run index.ts              # run TypeScript directly; add --hot to reload on change

Bun also publishes an install script at https://bun.com/install; if you use it, download it, read it, then run it, rather than piping it into a shell. A package manager is simpler. On Windows use scoop install bun or npm install -g bun.

Packages

bun install                   # reads package.json, writes bun.lock (text lockfile, readable diffs)
bun add zod                   # add a dependency; bun add -d typescript for dev
bun remove zod
bun install --frozen-lockfile # CI: fail if package.json and bun.lock disagree
bun audit                     # vulnerability check; bun outdated lists newer versions
bunx prisma generate          # run a package binary without installing it globally

Bun does not run postinstall and similar lifecycle scripts of dependencies, except for a built-in allow list of popular packages. If a package needs one (native builds), list it in "trustedDependencies" in package.json and reinstall. To hold back brand-new releases, set install.minimumReleaseAge (seconds) in bunfig.toml. A project still on the old binary bun.lockb migrates with bun install --save-text-lockfile --frozen-lockfile --lockfile-only, then delete bun.lockb.

HTTP server

Bun.serve() takes a routes map with :param segments and per-method handlers; fetch handles everything else.

// server.ts
import { Database } from "bun:sqlite";

const db = new Database("app.db");
db.run("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, email TEXT UNIQUE, hash TEXT)");

const server = Bun.serve({
  port: 3000,
  hostname: "127.0.0.1", // bind to loopback unless the service must be reachable from outside
  routes: {
    "/health": new Response("ok"),
    "/api/users/:id": (req) => {
      const user = db.query("SELECT id, email FROM users WHERE id = ?1").get(req.params.id);
      return user ? Response.json(user) : new Response("Not found", { status: 404 });
    },
    "/api/users": {
      POST: async (req) => {
        const { email, password } = await req.json();
        const hash = await Bun.password.hash(password); // argon2id by default
        db.query("INSERT INTO users (email, hash) VALUES (?1, ?2)").run(email, hash);
        return Response.json({ email }, { status: 201 });
      },
    },
  },
  fetch() {
    return new Response("Not found", { status: 404 });
  },
});
console.log(`listening on ${server.url}`);

WebSockets: call server.upgrade(req) inside fetch and add a websocket: { message(ws, msg) { ws.send(...) } } handler to the same Bun.serve() options. Bun.password.verify(password, hash) checks a hash.

Tests

bun test finds *.test.ts files and supports describe, it, expect, snapshots and --coverage.

// mailer.ts
export async function sendWelcome(email: string) { /* send the mail */ }

// signup.ts
import { sendWelcome } from "./mailer";
export async function signup(email: string) {
  await sendWelcome(email);
  return { email, welcomed: true };
}
// signup.test.ts
import { describe, expect, it, mock } from "bun:test";

mock.module("./mailer", () => ({ sendWelcome: mock(async () => {}) })); // before importing the code under test

describe("signup", () => {
  it("welcomes the new user", async () => {
    const { signup } = await import("./signup");
    expect(await signup("mara@acme-corp.net")).toEqual({ email: "mara@acme-corp.net", welcomed: true });
  });
});

Bundle and compile

// build.ts — run with: bun run build.ts
const result = await Bun.build({
  entrypoints: ["./src/index.tsx"],
  outdir: "./dist",
  target: "browser", // "bun" or "node" for server code
  splitting: true,
  minify: true,
});
if (!result.success) console.error(result.logs);

CLI equivalent: bun build ./src/index.tsx --outdir dist --minify. bun build ./server.ts --compile --outfile dist/api produces a single self-contained executable.

Files and environment

Bun.file("data.json").json() reads and await Bun.write("out.txt", text) writes. new Bun.Glob("src/**/*.ts").scan(".") lists files. .env, .env.local and .env.<NODE_ENV> load automatically into Bun.env and process.env, so dotenv is not needed.

Examples

Example 1: Build an API server with only built-ins

User prompt: "Create a small REST API with Bun: POST /api/users stores an email and a hashed password, GET /api/users/:id returns a user."

The agent runs bun init -y, writes server.ts with Bun.serve() routes, bun:sqlite for storage and Bun.password.hash() for passwords, and starts it with bun run server.ts. It checks the result with curl -X POST -H 'content-type: application/json' -d '{"email":"mara@acme-corp.net","password":"correct-horse-9271"}' http://127.0.0.1:3000/api/users, which returns {"email":"mara@acme-corp.net"} with status 201, and shows that an unknown path returns 404.

Example 2: Move an Express project from Node.js to Bun

User prompt: "Switch my Express project from Node.js to Bun and make CI faster."

The agent deletes package-lock.json, runs bun install to create bun.lock, changes the scripts to bun run src/index.ts and bun test, and removes dotenv and ts-node. It runs the existing Jest tests under bun test, fixes the few that rely on Jest-only APIs, then sets the CI install step to bun install --frozen-lockfile. If a dependency fails on a missing Node API, it keeps that service on Node and reports the package name.

Guidelines

  • Commit bun.lock; use bun install --frozen-lockfile in CI
  • Dependency lifecycle scripts are blocked by default; add only packages you trust to trustedDependencies
  • Bun.serve() listens on all interfaces unless hostname is set; bind to 127.0.0.1 behind a reverse proxy
  • Prefer Bun.password over adding bcrypt packages, and do not store plain passwords
  • bun:sqlite is for embedded, single-process storage; use a server database for multi-instance deployments
  • Node compatibility is high but incomplete: test native addons and unusual node: APIs before switching production
  • Do not benchmark-claim from marketing numbers; measure your own workload
  • Use bunx instead of npx, and bun run <script> instead of npm run <script>

From the file to a first result

The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.

View the source and supporting files

This download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.

1. Download the file

Download SKILL.md

From the root of a test project, save the file as .skill-downloads/bun-runtime-bundler-tests-mwirmdv8/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.

Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.

mkdir -p '.skill-downloads/bun-runtime-bundler-tests-mwirmdv8' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/bun-runtime-bundler-tests-mwirmdv8/download' --output '.skill-downloads/bun-runtime-bundler-tests-mwirmdv8/SKILL.md.part' && mv '.skill-downloads/bun-runtime-bundler-tests-mwirmdv8/SKILL.md.part' '.skill-downloads/bun-runtime-bundler-tests-mwirmdv8/SKILL.md'

2. Check prerequisites

Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.

Environment declared by the author: Bun 1.4 on macOS, Linux or Windows (x64, arm64)

No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.

The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.

3. Load the skill

After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.

Claude Code
test -f '.skill-downloads/bun-runtime-bundler-tests-mwirmdv8/SKILL.md' && test -s '.skill-downloads/bun-runtime-bundler-tests-mwirmdv8/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/bun' && cp -R '.skill-downloads/bun-runtime-bundler-tests-mwirmdv8' '.claude/skills/bun'

Cursor
test -f '.skill-downloads/bun-runtime-bundler-tests-mwirmdv8/SKILL.md' && test -s '.skill-downloads/bun-runtime-bundler-tests-mwirmdv8/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/bun' && cp -R '.skill-downloads/bun-runtime-bundler-tests-mwirmdv8' '.cursor/skills/bun'

Codex
test -f '.skill-downloads/bun-runtime-bundler-tests-mwirmdv8/SKILL.md' && test -s '.skill-downloads/bun-runtime-bundler-tests-mwirmdv8/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/bun' && cp -R '.skill-downloads/bun-runtime-bundler-tests-mwirmdv8' '.agents/skills/bun'

OpenSkills

OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.

Official OpenSkills installation
openskills install './.skill-downloads/bun-runtime-bundler-tests-mwirmdv8'

openskills read 'bun-runtime-bundler-tests-mwirmdv8'

Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.

For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.

openskills sync

Manual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.

4. Try a first task

Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:

Read .skill-downloads/bun-runtime-bundler-tests-mwirmdv8/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.

Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.

Related skills