Enable compression for WebSocket messages

Set the perMessageDeflate parameter to enable the permessage-deflate WebSocket extension. Bun then negotiates compression with clients that support it. Messages sent with ws.send() are still uncompressed unless you opt in per message (see below).

server.ts
Bun.serve({
  // ...
  websocket: {
    // enable compression
    perMessageDeflate: true,
  },
});

To enable compression for individual messages, pass true as the second parameter to ws.send(). This requires perMessageDeflate to be enabled; otherwise Bun sends the message uncompressed.

server.ts
Bun.serve({
  // ...
  websocket: {
    perMessageDeflate: true,
    async message(ws, message) {
      // send a compressed message
      ws.send(message, true);
    },
  },
});