The @solid-primitives/websocket package provides several primitives to establish, maintain, and operate WebSocket connections in SolidJS.
All primitives return an extended WebSocket instance that includes a .message property. This property is an accessor for the last received message, allowing you to react to incoming data easily.
Connection Lifecycle Management
createWS(url, protocols?): Sets up a connection that automatically disconnects when the Solid component/scope is cleaned up.makeWS(url, protocols?): Sets up a connection with a buffered send (allows calling .send() before the connection is fully open).createReconnectingWS(url, protocols?, options?): A connection that automatically reconnects if it is involuntarily closed, but disconnects on cleanup.makeReconnectingWS(url, protocols?, options?): Similar to createReconnectingWS, but requires manual cleanup.makeHeartbeatWS(reconnectingWS, options?): Wraps a reconnecting WebSocket to send periodic heartbeat messages and reconnect if the server fails to respond.
const ws = createWS("ws://localhost:5000");
const state = createWSState(ws);
const states = ["Connecting", "Connected", "Disconnecting", "Disconnected"];
ws.send("it works");
// Accessing the last message via the .message accessor
createEffect(on(ws.message, msg => console.log(msg), { defer: true }));
return <p>Connection: {states[state()]}</p>;