new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Bun · all subjects

runtime/http

41 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

POST request with fetch in Bun

To send a POST request, pass an options object with method: "POST", body: JSON.stringify({...}), and headers: { "Content-Type": "application/json" }. Call response.json() to read the JSON response.

GET request with fetch in Bun

To send a GET request, call fetch() with a URL string. The returned response object has a text() method to read the response as an HTML string.

fetch API available in Bun

Bun implements the Web-standard fetch API for sending HTTP requests. This allows developers to use the standard fetch() function to make HTTP calls, consistent with the browser and Node.js APIs.

Serve a file in HTTP response

Use Bun.file(path) to get a file object, then pass it to new Response() to serve the file. For example, new Response(Bun.file(import.meta.path)) serves the current file. import.meta.path contains the absolute path to the current module.

HTTP JSON response

Use Response.json(object) to send a JSON response with the correct content-type header. For example, Response.json({ some: "buns", for: "you" }) serializes the object to JSON.

Receive JSON in POST request

In an async fetch handler, check req.method === "POST" and await req.json() to receive and parse JSON data from the request body.

Receive form data in POST request

In an async fetch handler, check req.method === "POST" and await req.formData() to receive form-encoded data. Call .get(fieldName) on the returned object to access individual form fields by name.

HTTP text/plain response

Return new Response("text content") to send a plain text response with the default content-type of text/plain.

HTTP redirect response

Use Response.redirect(url, statusCode) to send a redirect response. For example, Response.redirect("/source", 301) redirects to /source with a 301 status code.

HTTP 404 not found response

Return new Response("message", { status: 404 }) to send a 404 not found response with a custom message.

SSE endpoint Content-Type header

To implement a Server-Sent Events (SSE) endpoint in Bun, return a Response whose body is a streaming source and set the Content-Type header to text/event-stream.

Stream file as HTTP Response using Bun.file()

Bun.file() reads a file from disk and returns a BunFile instance, which can be passed directly to the new Response constructor to stream the file as an HTTP response.

Bun.file() basic usage with Response

The code example shows: const path = "/path/to/file.txt"; const file = Bun.file(path); const resp = new Response(file);

Bun automatically sets Content-Type header from file

When a BunFile is passed to the Response constructor, Bun reads the file extension and automatically sets the appropriate Content-Type header. For example: package.json gets application/json;charset=utf-8, .txt files get text/plain;charset=utf-8, .tsx files get text/javascript;charset=utf-8, and .png files get image/png.

Content-Type examples for common file types

Bun.file() sets these Content-Type headers: .json files → application/json;charset=utf-8; .txt files → text/plain;charset=utf-8; .tsx files → text/javascript;charset=utf-8; .png files → image/png.

Static file server example with Bun.serve()

A complete static file server implementation: Bun.serve({ async fetch(req) { const path = new URL(req.url).pathname; const file = Bun.file(path); return new Response(file); } });

Response accepts Node.js Readable streams as body

In Bun, a Response object accepts a Node.js Readable stream as its body. This works because Bun's Response accepts any async iterable as its body, and Node.js streams implement the async iterable protocol.

Streaming HTTP server with Node.js Readable example

The following example demonstrates creating a streaming HTTP server using Node.js Readable streams. It imports Readable from the stream module, creates a server with serve() listening on port 3000, and returns a Response with a Readable stream created from an array of strings as the body: ```ts import { Readable } from "stream"; import { serve } from "bun"; serve({ port: 3000, fetch(req) { return new Response(Readable.from(["Hello, ", "world!"]), { headers: { "Content-Type": "text/plain" }, }); }, }); ```

Response accepts async generator function as body

In Bun, a Response can accept an async generator function as its body, allowing you to stream data to the client as it becomes available rather than waiting for the entire response to be ready.

Async generator function in Response example

Example of streaming HTTP response using an async generator function: ```ts Bun.serve({ port: 3000, fetch(req) { return new Response( // An async generator function async function* () { yield "Hello, "; await Bun.sleep(100); yield "world!"; // you can also yield a TypedArray or Buffer yield new Uint8Array(["\n".charCodeAt(0)]); }, { headers: { "Content-Type": "text/plain" } }, ); }, }); ``` This demonstrates yielding strings and TypedArray data with asynchronous delays between yields.

Response accepts Symbol.asyncIterator object

A Response can accept any async iterable object directly as its body. This includes objects with a Symbol.asyncIterator method that returns an async generator.

Symbol.asyncIterator in Response example

Example of streaming HTTP response using an async iterable object with Symbol.asyncIterator: ```ts Bun.serve({ port: 3000, fetch(req) { return new Response( { [Symbol.asyncIterator]: async function* () { yield "Hello, "; await Bun.sleep(100); yield "world!"; }, }, { headers: { "Content-Type": "text/plain" } }, ); }, }); ``` This shows how to pass an object implementing the async iterable protocol directly to Response.

Response body can yield strings, TypedArray, or Buffer

When streaming a Response using async generators, you can yield strings, TypedArray objects (like Uint8Array), or Buffer objects as the response body.

Response constructor accepts Node.js Readable stream

The Response constructor in Bun accepts a Node.js Readable stream as the body parameter.

Response constructor accepts Node.js Readable streams

A Response object can be constructed with a Node.js Readable stream as the body parameter.

response.json() method for Readable streams

The response.json() method can be awaited to parse the body of a Response containing a Node.js Readable stream and return it as a JavaScript object.

Response.bytes() method

The bytes() method is available on Response objects in Bun. It returns a Promise<Uint8Array> containing the body data. When the Response is constructed with a Node.js Readable stream, bytes() will read the entire stream and return it as a Uint8Array.

WebSocket contextual data example with socketId

Example of storing a socketId in WebSocket contextual data: ```ts Bun.serve({ fetch(req, server) { const success = server.upgrade(req, { data: { socketId: Math.random(), }, }); if (success) return undefined; }, websocket: { data: {} as { socketId: number }, async message(ws, message) { console.log(`Received ${message} from ${ws.data.socketId}`); }, }, }); ```

Reading cookies and headers to identify WebSocket clients

To identify connecting WebSocket clients, read cookies and headers from the incoming request during the upgrade process. Extract identifying information like tokens or user IDs from the request headers, then store this data in the contextual data object passed to server.upgrade().

WebSocket contextual data example with user authentication

Example of storing user authentication data in WebSocket contextual data: ```ts type WebSocketData = { createdAt: number; token: string; userId: string; }; Bun.serve({ async fetch(req, server) { const cookies = parseCookies(req.headers.get("Cookie")); const token = cookies["X-Token"]; const user = await getUserFromToken(token); const upgraded = server.upgrade(req, { data: { createdAt: Date.now(), token: cookies["X-Token"], userId: user.id, }, }); if (upgraded) return undefined; }, websocket: { data: {} as WebSocketData, async message(ws, message) { await saveMessageToDatabase({ message: String(message), userId: ws.data.userId, }); }, }, }); ```

WebSocket contextual data with server.upgrade()

When upgrading an HTTP connection to WebSocket using server.upgrade(), pass a data parameter containing per-socket contextual data. This data is then available on the WebSocket instance as the data property in websocket handlers.

server.upgrade() data parameter signature

server.upgrade(req, { data: {...} }) accepts a data property in the options object. The data value is an arbitrary object that will be stored and accessible as ws.data in websocket message, close, and drain handlers.

TypeScript WebSocket data type annotation

When using TypeScript with Bun's WebSocket API, specify the type of ws.data by setting the data property in the websocket options object to an empty object with the desired type using 'as' keyword: data: {} as { socketId: number }

WebSocket close handler receives ws parameter

The close handler for WebSocket receives the ws parameter, which represents the disconnected socket. This allows cleanup operations like unsubscribing from channels.

WebSocket server.publish() method signature

Publish a message to a channel from the server using server.publish(<name>, <message>). The name parameter is a string identifying the channel, and message is the data to publish to all subscribers of that channel.

WebSocket socket.unsubscribe() method signature

Unsubscribe a socket from a named channel using socket.unsubscribe(<name>). The name parameter is a string identifying the channel to unsubscribe from.

Bun WebSocket pub-sub example: single-channel chat server

Example of a WebSocket chat server that uses Bun's native pub-sub functionality. The server subscribes new connections to a channel named 'the-group-chat' in the open handler, re-broadcasts incoming messages to the channel in the message handler, and publishes a leave message when a connection closes. Each socket has data attached containing the username from cookies.

WebSocket open handler receives ws parameter

The open handler for WebSocket receives the ws parameter, which represents the connected socket. The ws object contains the data property (which holds the data passed during upgrade) and methods like subscribe() and unsubscribe().

WebSocket message handler signature

The message handler receives two parameters: ws (the WebSocket connection) and message (the message data sent by the client).

WebSocket socket.subscribe() method signature

Subscribe a socket to a named channel using socket.subscribe(<name>). The name parameter is a string identifying the channel to subscribe to.

Bun WebSocket native pub-sub capability

Bun's server-side WebSocket API includes native pub-sub functionality built-in. This allows subscribing sockets to named channels and publishing messages to those channels efficiently.

Give your agent this brain