Effection Logo
@effection-contrib/websocketv1.0.1thefrontside/effection-contrib
JSR BadgeNPM Badge with published versionBundle size badgeDependency count badgeTree shaking support badge
import { } from "@effection-contrib/websocket"

WebSocket

A streamlined WebSocket client for Effection programs that transforms the event-based WebSocket API into a clean, resource-oriented stream.

Why Use this API?

Traditional WebSocket API require managing multiple event handlers (open, close, error, message) which can become complex and error-prone.

This package simplifies WebSocket usage by:

  • Providing a clean stream-based interface
  • Handling connection state management automatically
  • Implementing proper error handling
  • Ensuring resource cleanup

Basic Usage

import { each, main } from "effection";
import { useWebSocket } from "@effection-contrib/websocket";

await main(function* () {
  // Connection is guaranteed to be open when this returns
  let socket = yield* useWebSocket("ws://websocket.example.org");

  // Send messages to the server
  socket.send("Hello World");

  // Receive messages using a simple iterator
  for (let message of yield* each(socket)) {
    console.log("Message from server", message);
    yield* each.next();
  }
});

Features

  • Ready-to-use Connections: useWebSocket() returns only after the connection is established
  • Automatic Error Handling: Socket errors are properly propagated to your error boundary
  • Stream-based API: Messages are delivered through a simple stream interface
  • Clean Resource Management: Connections are properly cleaned up when the operation completes

Advanced Usage

Custom WebSocket Implementations

For environments without native WebSocket support (like Node.js < 21), you can provide your own WebSocket implementation:

import { createWebSocket } from "my-websocket-client";
import { each, main } from "effection";
import { useWebSocket } from "@effection-contrib/websocket";

await main(function* () {
  let socket = yield* useWebSocket(() =>
    createWebSocket("ws://websocket.example.org")
  );

  for (let message of yield* each(socket)) {
    console.log("Message from server", message);
    yield* each.next();
  }
});

API Reference

interface WebSocketResource<T> extends Stream<MessageEvent<T>, CloseEvent>

Handle to a WebSocket object that can be consumed as an Effection stream. It has all the same properties as the underlying WebSocket apart from the event handlers. Instead, the resource itself is a subscribale stream. When the socket is closed, the stream will complete with a CloseEvent

A WebSocketResource does not have an explicit close method. Rather, the underlying socket will be automatically closed when the resource passes out of scope.

Type Parameters

T

Properties

binaryTypereadonly: BinaryType

the type of data that this websocket accepts

bufferedAmmountreadonly: number

No documentation available.

extensionsreadonly: string

No documentation available.

protocolreadonly: string

No documentation available.

readyStatereadonly: number

No documentation available.

urlreadonly: string

No documentation available.

Methods

send(data: WebSocketData): void

No documentation available.

function useWebSocket<T>(url: string, protocols?: string): Operation<WebSocketResource<T>>

Create a WebSocket resource using the native WebSocket constructor available on the current platform.

The resource will not be returned until a connection has been succesffuly established with the server and the open has been received. Once initialized, it will crash if it receives an error event at any time.

Once created, the websocket resource can be use to consume events from the server:

let socket = yield* useWebSocket("ws://websocket.example.org");

for (let event of yield* each(socket)) {
  console.log('event data: ', event.data);
  yield* each.next();
}

Type Parameters

T

Parameters

url: string

protocolsoptional: string

  • A single string or an array of strings representing the sub-protocol(s) that the client would like to use, in order of preference. If it is omitted, an empty array is used by default, i.e. []. For more details, see

Return Type

Operation<WebSocketResource<T>>

an operation yielding a WebSocketResource

function useWebSocket<T>(create: () => WebSocket): Operation<WebSocketResource<T>>

Create a WebSocket resource, but delegate the creation of the underlying websocket to a function of your choice. This is necessary on platforms that do not have a global WebSocket constructor such as NodeJS <= 20.

The resource will not be returned until a connection has been succesffuly established with the server and the open has been received. Once initialized, it will crash if it receives an error event at any time.

Once created, the websocket resource can be use to consume events from the server:

import * as ws from 'ws';

function* example() {
  let socket = yield* useWebSocket(() => new ws.WebSocket("ws://websocket.example.org"));

  for (let event of yield* each(socket)) {
    console.log('event data: ', event.data);
    yield* each.next();
  }
}

Type Parameters

T

Parameters

create: () => WebSocket

  • a function that will construct the underlying WebSocket object that this resource wil use

Return Type

Operation<WebSocketResource<T>>

an operation yielding a WebSocketResource