> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/zhcndoc/bun/llms.txt
> Use this file to discover all available pages before exploring further.

# Web APIs

> Bun implements web standard APIs for compatibility and familiarity

Bun implements many web standard APIs, making it easier to write code that works across browsers, Node.js, and Bun. These APIs follow the specifications defined by WHATWG and W3C.

## Fetch API

Bun implements the complete Fetch API for making HTTP requests:

```typescript theme={null}
const response = await fetch("https://api.example.com/data");
const data = await response.json();
```

### fetch()

Global function for HTTP requests:

```typescript theme={null}
fetch(url: string | URL | Request, options?: RequestInit): Promise<Response>
```

### Request

HTTP request representation:

```typescript theme={null}
const req = new Request("https://api.example.com", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ key: "value" })
});
```

### Response

HTTP response representation:

```typescript theme={null}
const res = new Response("Hello World", {
  status: 200,
  headers: { "Content-Type": "text/plain" }
});
```

### Headers

HTTP headers management:

```typescript theme={null}
const headers = new Headers();
headers.set("Content-Type", "application/json");
headers.append("X-Custom-Header", "value");
```

See [fetch documentation](/guides/http/fetch) for more details.

## Streams API

Bun implements the Web Streams specification:

### ReadableStream

```typescript theme={null}
const stream = new ReadableStream({
  start(controller) {
    controller.enqueue("chunk 1");
    controller.enqueue("chunk 2");
    controller.close();
  }
});

for await (const chunk of stream) {
  console.log(chunk);
}
```

### WritableStream

```typescript theme={null}
const writable = new WritableStream({
  write(chunk) {
    console.log("Writing:", chunk);
  }
});

const writer = writable.getWriter();
await writer.write("data");
await writer.close();
```

### TransformStream

```typescript theme={null}
const transformer = new TransformStream({
  transform(chunk, controller) {
    controller.enqueue(chunk.toUpperCase());
  }
});
```

See [Streams API documentation](/api/streams) for complete reference.

## URL & URLSearchParams

Parse and manipulate URLs:

```typescript theme={null}
const url = new URL("https://example.com/path?key=value#hash");
console.log(url.hostname);    // "example.com"
console.log(url.pathname);    // "/path"
console.log(url.searchParams.get("key")); // "value"

const params = new URLSearchParams("key1=value1&key2=value2");
params.append("key3", "value3");
console.log(params.toString()); // "key1=value1&key2=value2&key3=value3"
```

## FormData

Handle form data:

```typescript theme={null}
const form = new FormData();
form.append("name", "John");
form.append("file", Bun.file("image.png"));

// Send with fetch
await fetch("https://api.example.com/upload", {
  method: "POST",
  body: form
});
```

## Blob

Binary data handling:

```typescript theme={null}
const blob = new Blob(["Hello ", "World"], { type: "text/plain" });
const text = await blob.text();
const buffer = await blob.arrayBuffer();
```

Bun extends Blob with additional methods:

```typescript theme={null}
blob.size          // Size in bytes
blob.type          // MIME type
blob.text()        // Read as text
blob.json()        // Parse as JSON
blob.arrayBuffer() // Read as ArrayBuffer
blob.stream()      // Get ReadableStream
blob.slice()       // Extract portion
```

## WebSocket

Real-time communication:

```typescript theme={null}
const ws = new WebSocket("wss://echo.websocket.org");

ws.addEventListener("open", () => {
  ws.send("Hello");
});

ws.addEventListener("message", (event) => {
  console.log("Received:", event.data);
});
```

For server-side WebSocket, use [Bun.serve()](/api/websockets).

## Web Crypto API

Cryptographic operations:

```typescript theme={null}
// Generate random values
const array = new Uint8Array(16);
crypto.getRandomValues(array);

// Generate UUID
const uuid = crypto.randomUUID();

// Hashing
const data = new TextEncoder().encode("Hello");
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
```

## TextEncoder / TextDecoder

Convert between strings and bytes:

```typescript theme={null}
const encoder = new TextEncoder();
const bytes = encoder.encode("Hello 世界");

const decoder = new TextDecoder("utf-8");
const text = decoder.decode(bytes);
```

## Performance

Web performance APIs:

```typescript theme={null}
// High-resolution time
performance.now(); // Microsecond precision

// Measure operations
const start = performance.now();
await someOperation();
const duration = performance.now() - start;
console.log(`Took ${duration}ms`);
```

## Timers

Standard timer functions:

```typescript theme={null}
setTimeout(() => console.log("Delayed"), 1000);
setInterval(() => console.log("Repeating"), 1000);
setImmediate(() => console.log("Immediate"));

// Clear timers
const id = setTimeout(() => {}, 1000);
clearTimeout(id);
```

## Console

Standard console methods:

```typescript theme={null}
console.log("Message");
console.error("Error");
console.warn("Warning");
console.table([{ a: 1, b: 2 }]);
console.time("operation");
// ... code ...
console.timeEnd("operation");
```

See [Console API documentation](/api/console) for all methods.

## Event APIs

### EventTarget

```typescript theme={null}
const target = new EventTarget();

target.addEventListener("custom", (event) => {
  console.log("Event data:", event.detail);
});

target.dispatchEvent(new CustomEvent("custom", {
  detail: { key: "value" }
}));
```

### AbortController / AbortSignal

Cancel operations:

```typescript theme={null}
const controller = new AbortController();
const signal = controller.signal;

fetch("https://api.example.com", { signal })
  .catch((err) => {
    if (err.name === "AbortError") {
      console.log("Request cancelled");
    }
  });

// Cancel after 5 seconds
setTimeout(() => controller.abort(), 5000);
```

## Additional Web APIs

Bun implements many other web standards:

* **atob() / btoa()**: Base64 encoding/decoding
* **structuredClone()**: Deep copy objects
* **queueMicrotask()**: Schedule microtask
* **MessageChannel / MessagePort**: Message passing
* **BroadcastChannel**: Cross-context messaging

## Browser Compatibility

Bun's web APIs are designed to be compatible with browser implementations. Code using these APIs can often run unchanged in browsers.

However, some APIs have server-specific behavior:

* **fetch()** supports `file://` URLs and Unix domain sockets
* **WebSocket** has server-side implementation in Bun.serve()
* **Performance** APIs may have different precision

## Next Steps

<CardGroup cols={2}>
  <Card title="fetch()" icon="arrow-right-arrow-left" href="/guides/http/fetch">
    Learn about HTTP requests with fetch
  </Card>

  <Card title="Streams" icon="water" href="/api/streams">
    Work with Web Streams API
  </Card>

  <Card title="WebSocket" icon="circle-nodes" href="/api/websockets">
    Real-time communication
  </Card>

  <Card title="Bun APIs" icon="bolt" href="/runtime/bun-apis">
    Explore Bun-specific APIs
  </Card>
</CardGroup>
