Create a server-side ServerWebSocket handler for use with Bun.serve
interface
WebSocketHandler
interface WebSocketHandler<T>
import { websocket, serve } from "bun";
serve<{name: string}>({
port: 3000,
websocket: {
open: (ws) => {
console.log("Client connected");
},
message: (ws, message) => {
console.log(`${ws.data.name}: ${message}`);
},
close: (ws) => {
console.log("Client disconnected");
},
},
fetch(req, server) {
const url = new URL(req.url);
if (url.pathname === "/chat") {
const upgraded = server.upgrade(req, {
data: {
name: new URL(req.url).searchParams.get("name"),
},
});
if (!upgraded) {
return new Response("Upgrade failed", { status: 400 });
}
return;
}
return new Response("Hello World");
},
});
- backpressureLimit?: number
Sets the maximum number of bytes that can be buffered on a single connection.
Default is 16 MB, or
1024 * 1024 * 16
in bytes. - closeOnBackpressureLimit?: boolean
Sets if the connection should be closed if
backpressureLimit
is reached. - data?: T
Specify the type for the ServerWebSocket.data property on connecting websocket clients. You can pass this value when you make a call to Server.upgrade.
This pattern exists in Bun due to a TypeScript limitation (#26242)
Bun.serve({ websocket: { data: {} as { name: string }, // ← Specify the type of `ws.data` like this message: (ws, message) => console.log(ws.data.name, 'says:', message); }, // ... });
- idleTimeout?: number
Sets the the number of seconds to wait before timing out a connection due to no messages or pings.
- maxPayloadLength?: number
Sets the maximum size of messages in bytes.
Default is 16 MB, or
1024 * 1024 * 16
in bytes. - perMessageDeflate?: boolean | { compress: boolean | WebSocketCompressor; decompress: boolean | WebSocketCompressor }
Sets the compression level for messages, for clients that supports it. By default, compression is disabled.
- code: number,reason: string): void | Promise<void>;
Called when a connection is closed.
@param wsThe websocket that was closed
@param codeThe close code
@param reasonThe close reason
- ): void | Promise<void>;
Called when a connection was previously under backpressure, meaning it had too many queued messages, but is now ready to receive more data.
@param wsThe websocket that is ready for more data
- ): void | Promise<void>;
Called when the server receives an incoming message.
If the message is not a
string
, its type is based on the value ofbinaryType
.- if
nodebuffer
, then the message is aBuffer
. - if
arraybuffer
, then the message is anArrayBuffer
. - if
uint8array
, then the message is aUint8Array
.
@param wsThe websocket that sent the message
@param messageThe message received
- if
- @param ws
The websocket that was opened
- @param ws
The websocket that received the ping
@param dataThe data sent with the ping
- @param ws
The websocket that received the ping
@param dataThe data sent with the ping