alepha@docs:~/docs/reference/primitives$
cat $channel.md | pretty1 min read
#$channel
#Import
typescript
1import { $channel } from "alepha/websocket";
#Overview
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).
#Options
| Option | Type | Required | Description |
|---|---|---|---|
path |
string |
Yes | WebSocket endpoint path (e.g., "/ws/chat") |
description |
string |
No | Optional description for documentation |
schema |
Object |
Yes | Message schemas for bidirectional communication |
roomId |
TString |
No | Optional room ID schema validation Default: t.text() (any string) Can be enforced at application level: t.uuid(), t.regex(/^[a-f0-9-]{36}$/) |
in |
TClient |
Yes | Messages from server to client This is what clients will receive |
out |
TServer |
Yes | Messages from client to server This is what the server will receive |
#Examples
Server-side with $websocket
typescript
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}
Browser-side with useRoom
typescript
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}