Getting Started

crossws provides a cross-platform toolkit to define well-typed WebSocket apps that can then be integrated into various WebSocket servers using built-in adapters.

Writing a realtime WebSocket server that can work in different runtimes is challenging because there is no single standard for WebSocket servers. You often need to go into many details of different API implementations and it also makes switching from one runtime costly. crossws is a solution to this!

Quick Start

You can try crossws with online playground using unjs/h3 + unjs/listhen or alternatively integrate crossws with your own framework.

A simple WebSocket implementation looks like this:

import { defineHooks } from "crossws";
import crossws from "crossws/adapters/<adapter>";

const ws = crossws({
  hooks: {
    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);
    },
  },
});
See Hooks for more usage details.
Hooks API is exactly same on all runtimes. See Adapters for integration details.

Using Package

You can install crossws from npm in your project:

npm i crossws

Alternatively you can import it from CDN:

import { defineHooks } from "https://esm.sh/crossws";
import crossws from "https://esm.sh/crossws/adapters/<adapter>";