Getting Started

CrossWS provides a cross-platform API 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 javascript and WebSocket runtimes is challenging because there is no single standard for WebSocket servers. You often need to go into many details of diffrent API implementations and it also makes switching from one runtime costly. CrossWS is a solution to this!

CrossWS API is still under development and can change.

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:

// https://crossws.unjs.io/adapters
import wsAdapter from "crossws/adapters/<adapter>";

import { defineHooks } from "crossws";

const websocket = wsAdapter({
  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 { crossws } from "https://esm.sh/crossws";