WebSocketHandler

Bun

Symbol

WebSocketHandler

interface WebSocketHandler<T = undefined>

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.

    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 to ws (itself), if it is subscribed?

    Default is false.

  • sendPings?: boolean

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

    Default is true.

  • close(ws: ServerWebSocket<T>, 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

  • drain(ws: ServerWebSocket<T>): 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(ws: ServerWebSocket<T>, message: string | Buffer<ArrayBufferLike>): 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

  • open(ws: ServerWebSocket<T>): void | Promise<void>

    Called when a connection is opened.

    @param ws

    The websocket that was opened

  • ping(ws: ServerWebSocket<T>, 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

  • pong(ws: ServerWebSocket<T>, 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