Pub / Sub

CrossWS supports native pub-sub API integration. A peer can be subscribed to a set of named channels using peer.subscribe(<name>). Messages can be published to a channel using peer.publish(<name>, <message>).

Native pub/sub is currently only available for Bun and Node.js.
import { defineHooks } from "crossws";

const hooks = defineHooks({
  open(peer) {
    // Send welcome to the new client
    peer.send("Welcome to the server!");

    // Join new client to the "chat" channel

    // Notify every other connected client
    peer.publish("chat", `[system] ${peer} joined!`);

  message(peer, message) {
    // The server re-broadcasts incoming messages to everyone
    peer.publish("chat", `[${peer}] ${message}`);

  close(peer) {
    peer.publish("chat", `[system] ${peer} has left the chat!`);