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.
Install crossws
and srvx
in your project:
npm i crossws srvx
yarn add crossws srvx
pnpm i crossws srvx
bun i crossws srvx
deno i crossws srvx
A simple WebSocket server looks like this:
server.mjs
// Works with Bun, Deno and Node.js (also Cloudflare or SSE as fallback)
import { serve } from "crossws/server";
serve({
websocket: {
open(peer) {
console.log("[ws] open", peer);
peer.send({ user: "server", message: `Welcome ${peer}!` });
},
message(peer, message) {
console.log("[ws] message", message);
if (message.text().includes("ping")) {
peer.send({ user: "server", message: "pong" });
} else {
peer.send({ user: peer.toString(), message: message.toString() });
}
},
close(peer, event) {
console.log("[ws] close", peer, event);
},
error(peer, error) {
console.log("[ws] error", peer, error);
},
},
fetch: () =>
fetch(
"https://raw.githubusercontent.com/h3js/crossws/refs/heads/main/playground/public/index.html",
).then(
(res) =>
new Response(res.body, { headers: { "Content-Type": "text/html" } }),
),
});
Then, run the server using your favorite runtime:
node server.mjs
deno run --allow-env --allow-net server.mjs
bun run server.mjs
When using crossws/server
, export conditions automatically resolve the right runtime adapter and integrate with 💥 srvx. You can alternatively, manually integrate crossws with Adapters.
See Hooks for more usage details.
Hooks API is exactly same on all runtimes. See Adapters for integration details.