Create a server-side ServerWebSocket handler for use with Bun.serve
Symbol
WebSocketHandler
interface WebSocketHandler<T = undefined>
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.Default is
false
. - idleTimeout?: number
Sets the the number of seconds to wait before timing out a connection due to no messages or pings.
Default is 2 minutes, or
120
in seconds. - 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.
Default is
false
. - publishToSelf?: boolean
Should
ws.publish()
also send a message tows
(itself), if it is subscribed?Default is
false
. - sendPings?: boolean
Should the server automatically send and respond to pings to clients?
Default is
true
. Called when a connection is closed.
@param wsThe websocket that was closed
@param codeThe close code
@param reasonThe close reason
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
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
Called when a connection is opened.
@param wsThe websocket that was opened
Called when a ping is sent.
@param wsThe websocket that received the ping
@param dataThe data sent with the ping
Called when a pong is received.
@param wsThe websocket that received the ping
@param dataThe data sent with the ping