Guide

Hooks

Using hooks, you can define a WebSocket server that works across runtimes with the same syntax.

Crossws provides a cross-platform API to define WebSocket servers. An implementation with these hooks works across runtimes without needing you to go into details of each of them. You only define the life-cycle hooks that you only need.

Using defineHooks() wrapper is optional and for type support and code auto completion.
import { defineHooks } from "crossws";

const hooks = defineHooks({
  upgrade(req) {
    console.log(`[ws] upgrading ${req.url}...`)
    return {
      headers: {}
    }
  }

  open(peer) {
    console.log(`[ws] open: ${peer}`);
  },

  message(peer, message) {
    console.log("[ws] message", peer, message);
    if (message.text().includes("ping")) {
      peer.send("pong");
    }
  },

  close(peer, event) {
    console.log("[ws] close", peer, event);
  },

  error(peer, error) {
    console.log("[ws] error", peer, error);
  },
};