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.
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:
const response = await fetch ( "https://api.example.com/data" );
const data = await response . json ();
fetch()
Global function for HTTP requests:
fetch ( url : string | URL | Request , options ?: RequestInit ): Promise < Response >
Request
HTTP request representation:
const req = new Request ( "https://api.example.com" , {
method: "POST" ,
headers: { "Content-Type" : "application/json" },
body: JSON . stringify ({ key: "value" })
});
Response
HTTP response representation:
const res = new Response ( "Hello World" , {
status: 200 ,
headers: { "Content-Type" : "text/plain" }
});
HTTP headers management:
const headers = new Headers ();
headers . set ( "Content-Type" , "application/json" );
headers . append ( "X-Custom-Header" , "value" );
See fetch documentation for more details.
Streams API
Bun implements the Web Streams specification:
ReadableStream
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
const writable = new WritableStream ({
write ( chunk ) {
console . log ( "Writing:" , chunk );
}
});
const writer = writable . getWriter ();
await writer . write ( "data" );
await writer . close ();
const transformer = new TransformStream ({
transform ( chunk , controller ) {
controller . enqueue ( chunk . toUpperCase ());
}
});
See Streams API documentation for complete reference.
URL & URLSearchParams
Parse and manipulate URLs:
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"
Handle form data:
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:
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:
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:
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() .
Web Crypto API
Cryptographic operations:
// 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:
const encoder = new TextEncoder ();
const bytes = encoder . encode ( "Hello 世界" );
const decoder = new TextDecoder ( "utf-8" );
const text = decoder . decode ( bytes );
Web performance APIs:
// 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:
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:
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 for all methods.
Event APIs
EventTarget
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:
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
fetch() Learn about HTTP requests with fetch
Streams Work with Web Streams API
WebSocket Real-time communication
Bun APIs Explore Bun-specific APIs