Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 39 ยท Runtime Basics

Web APIs and Built-in Utilities

Use the web-standard globals Bun implements (fetch, URL, streams, crypto) and its own utilities - Bun.sleep, Bun.hash, Bun.password, Bun.spawn and the Bun.$ shell - with worked examples.

A runtime is more useful the less you have to install. Bun ships two layers of built-ins. The first is the web platform: the same fetch, URL, Headers, streams and Web Crypto objects you use in a browser. The second is the Bun global, a toolbox of fast helpers for sleeping, hashing, comparing, spawning processes and running shell commands. This lesson tours both so you know what is already there before you reach for an npm package.

Web-standard globals

You can use all of these without an import:

Area Globals
HTTP fetch, Request, Response, Headers
URLs URL, URLSearchParams, URLPattern
Streams ReadableStream, WritableStream, TransformStream
Encoding TextEncoder, TextDecoder, atob, btoa, Blob, File, FormData
Crypto crypto.subtle, crypto.randomUUID(), crypto.getRandomValues()
Timing setTimeout, setInterval, queueMicrotask, performance.now()
Misc structuredClone, AbortController, AbortSignal.timeout(), WebSocket, BroadcastChannel, console

Because these match the specifications, code written for the browser or for edge platforms (Cloudflare Workers, Deno) usually runs on Bun unchanged.

fetch

TypeScript
const response = await fetch("https://api.example.com/users?limit=2", {
  headers: { Accept: "application/json" },
  signal: AbortSignal.timeout(5000),
});

if (!response.ok) {
  throw new Error(`HTTP ${response.status}`);
}

const users = await response.json();
console.log(users);

Always check response.ok: fetch only rejects on network failures, not on 404 or 500. The AbortSignal.timeout(5000) cancels the request after five seconds. Bun's fetch also accepts a few extras, such as a proxy option and unix sockets, and it can read file: and data: URLs.

Request, Response, Headers and URL

These classes are also how you build servers (next chapter) and how you unit test them without any network. Here is a runnable example that uses only web standards:

Node.js Request, Response, Headers and URL (works the same on Bun and Node 24)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Timing and sleeping

setTimeout works as expected. Bun adds a promise-friendly sleeper:

TypeScript
await Bun.sleep(500);            // pause for 500 ms
Bun.sleepSync(100);              // blocks the thread: rarely a good idea

const start = Bun.nanoseconds(); // high resolution counter since process start
await Bun.sleep(10);
console.log(`${(Bun.nanoseconds() - start) / 1e6} ms`);

Bun.sleep also accepts a Date to wait until. The standard performance.now() is equally valid for measuring durations.

Hashing and passwords

Two different problems are often confused:

  • A fast hash (checksums, cache keys, deduplication) should be quick.
  • A password hash must be deliberately slow and salted.
TypeScript
// fast, non-cryptographic: good for cache keys and hash maps
const id = Bun.hash("some string");      // a number (64-bit Wyhash by default)

// cryptographic digests
const sha = new Bun.CryptoHasher("sha256").update("hello").digest("hex");
console.log(sha);
// 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

// passwords: argon2id by default, salt included in the output
const hash = await Bun.password.hash("correct horse battery staple");
console.log(await Bun.password.verify("correct horse battery staple", hash)); // true
console.log(await Bun.password.verify("wrong", hash));                         // false

Store the string Bun.password.hash returns. It contains the algorithm, parameters and salt, so verify needs nothing else. You can pass { algorithm: "bcrypt", cost: 10 } to produce bcrypt hashes for compatibility with older systems.

The SHA-256 above is deterministic and you can reproduce it with Web Crypto, which Bun implements too:

Node.js SHA-256 with Web Crypto (same API as Bun)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Other handy helpers

TypeScript
Bun.version;                        // "1.2.20"
Bun.main;                           // path of the entry file
Bun.env;                            // environment variables
Bun.which("git");                   // full path to an executable, or null
Bun.deepEquals({ a: [1] }, { a: [1] });    // true
Bun.escapeHTML("<b>Tom & Jerry</b>");      // "&lt;b&gt;Tom &amp; Jerry&lt;/b&gt;"
Bun.randomUUIDv7();                 // time-ordered UUID, good for database keys
Bun.inspect({ a: 1, b: [2, 3] });   // like console.log, but returns a string
Bun.gzipSync(new TextEncoder().encode("repeat ".repeat(100)));   // compression
Bun.stringWidth("hello");           // terminal column width

You do not need to memorise these. The point is that common chores each have a one-line, native implementation.

Running other programs: Bun.spawn

Bun.spawn starts a child process and gives you its streams:

TypeScript
const proc = Bun.spawn(["git", "rev-parse", "--short", "HEAD"], {
  stdout: "pipe",
  stderr: "inherit",
});

const output = await new Response(proc.stdout).text();
const exitCode = await proc.exited;
console.log(`commit ${output.trim()} (exit ${exitCode})`);

Arguments are an array, so no quoting problems. stdout: "pipe" makes proc.stdout a readable stream; "inherit" forwards to your terminal; "ignore" discards. Bun.spawnSync blocks and returns everything at once, which suits short scripts.

The Bun shell

Bun.$ is a tagged template that runs shell commands in a cross-platform shell built into Bun, so the same script works on Windows, macOS and Linux:

TypeScript
import { $ } from "bun";

const branch = await $`git branch --show-current`.text();
console.log(`on branch ${branch.trim()}`);

await $`mkdir -p dist && cp README.md dist/`;

const name = "my file.txt";
await $`touch ${name}`;   // interpolated values are escaped: safe against injection

Useful methods: .text(), .json(), .lines(), .quiet() to suppress output, and .nothrow() to avoid throwing on a non-zero exit. By default, a failing command throws a ShellError carrying the exit code. Pipes (|), redirects (>) and && all work.

Because interpolated values are escaped for you, $ is safer than building a command string and calling child_process.exec with user input.

A stand-in: spawn a process on Node

Node's child_process gives you the same capability in a different shape. This stand-in starts a child Node process and collects its output, the pattern Bun.spawn replaces:

Node.js Stand-in: collecting a child process's output (Node 24)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

When to use what

  • Use web standards (fetch, URL, Request) when the code might also run elsewhere.
  • Use Bun.* helpers when you know the code targets Bun and want speed or convenience.
  • Use node: modules when a library expects them or you need an API Bun does not duplicate.

Writing portable code first and Bun-specific code at the edges keeps your options open.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens when fetch receives a 404 response?

    fetch rejects only on network failure. HTTP error statuses still resolve, so you must check them.
  2. 2. Which Bun API is designed for hashing passwords?

    Bun.password.hash uses argon2id (or bcrypt) with a salt; Bun.hash is a fast non-cryptographic hash.
  3. 3. Why is Bun.$ safer than concatenating a command string?

    Values placed in the template are escaped, which prevents shell injection.
  4. 4. Which call pauses an async function for 500 ms without blocking the thread?

    await Bun.sleep(ms) yields to the event loop; sleepSync blocks.

Summary

  • Bun implements web standards as globals: fetch, Request, Response, URL, streams, crypto.subtle, AbortSignal and more.
  • Always check response.ok; add timeouts with AbortSignal.timeout.
  • Bun.sleep, Bun.hash, Bun.CryptoHasher, Bun.password, Bun.deepEquals, Bun.which and others replace small packages.
  • Bun.spawn runs child processes with streams; Bun.$ runs cross-platform shell commands with escaped interpolation.
  • Prefer web standards for portability and Bun.* for convenience.

Next: Watch Mode and Hot Reloading