Part of the alepha package. Import from alepha/websocket.
npm install alepha
Provides real-time bidirectional communication using WebSockets.
The WebSockets module enables building real-time applications using the $websocket primitive
on class properties. It provides automatic connection management, message routing, type-safe
message handling, and seamless integration with other Alepha modules.
On the server side (Node.js), it uses the 'ws' library to create a WebSocket server. On the client side (browser), it uses the native WebSocket API.
Primitives are functions that define and configure various aspects of your application. They follow the convention of starting with $ and return configured primitive instances.
For more details, see the Primitives documentation.
Channel primitive options / export interface ChannelPrimitiveOptions< TClient extends TWSObject, TServer extends TWSObject,
{ /** WebSocket endpoint path (e.g., "/ws/chat") / path: string;
/** Optional description for documentation / description?: string;
/** Message schemas for bidirectional communication / schema: { /** Optional room ID schema validation Default: t.text() (any string) Can be enforced at application level: t.uuid(), t.regex(/^[a-f0-9-]{36}$/) / roomId?: TString;
/**
Messages from server to client
This is what clients will receive
/
in: TClient;
/**
Messages from client to server
This is what the server will receive
/
out: TServer;
}; }
/** Defines a WebSocket channel with specified client and server message schemas.
Channels must be defined as class properties to be registered in the Alepha context. They define the "vocabulary" for communication - the schema for messages flowing in both directions (server→client and client→server).
1class ChatController { 2 // Channel must be defined inside a class 3 chatChannel = $channel({ 4 path: "/ws/chat", 5 description: "Real-time chat channel", 6 schema: { 7 // Server → Client messages 8 in: t.union([ 9 t.object({10 type: t.const("append"),11 content: t.text(),12 username: t.text()13 }),14 t.object({15 type: t.const("system"),16 message: t.text()17 })18 ]),19 // Client → Server messages20 out: t.object({21 content: t.text()22 })23 }24 });25 26 chat = $websocket({27 channel: this.chatChannel,28 handler: async ({ message, reply }) => {29 await reply({30 message: { type: "append", content: message.content, username: "user" }31 });32 }33 });34}
1// Define channel in a class for browser context 2class ChatClient { 3 chatChannel = $channel({ 4 path: "/ws/chat", 5 schema: { in: inSchema, out: outSchema } 6 }); 7} 8 9// Use in React component10function Chat() {11 const client = useInject(ChatClient);12 const chat = useRoom({ roomId: "lobby", channel: client.chatChannel, handler: ... }, []);13}
Defines a WebSocket server endpoint for a specific channel.
Server-side only. Creates a WebSocket endpoint that:
1class ChatController { 2 chat = $websocket({ 3 channel: chatChannel, 4 handler: async ({ connectionId, userId, roomId, message, reply }) => { 5 // Broadcast to all in room except sender 6 await reply({ 7 message: { 8 type: "append", 9 username: userId,10 content: message.content11 },12 exceptSelf: true13 });14 }15 });16 17 async broadcastAnnouncement(roomId: string, text: string) {18 await this.chat.emit({19 roomId,20 message: {21 type: "append",22 username: "System",23 content: text24 }25 });26 }27}