Bun

interface

WebSocketHandler

interface WebSocketHandler<T>

Create a server-side ServerWebSocket handler for use with Bun.serve

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.

  • publishToSelf?: boolean

    Should ws.publish() also send a message to ws (itself), if it is subscribed?

  • sendPings?: boolean

    Should the server automatically send and respond to pings to clients?

  • code: number,
    reason: string
    ): void | Promise<void>;

    Called when a connection is closed.

    @param ws

    The websocket that was closed

    @param code

    The close code

    @param reason

    The 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 ws

    The websocket that is ready for more data

  • message: string | Buffer<ArrayBuffer>
    ): 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 of binaryType.

    • if nodebuffer, then the message is a Buffer.
    • if arraybuffer, then the message is an ArrayBuffer.
    • if uint8array, then the message is a Uint8Array.
    @param ws

    The websocket that sent the message

    @param message

    The message received

  • ): void | Promise<void>;

    Called when a connection is opened.

    @param ws

    The websocket that was opened

  • data: Buffer
    ): void | Promise<void>;

    Called when a ping is sent.

    @param ws

    The websocket that received the ping

    @param data

    The data sent with the ping

  • data: Buffer
    ): void | Promise<void>;

    Called when a pong is received.

    @param ws

    The websocket that received the ping

    @param data

    The data sent with the ping