> ## Documentation Index
> Fetch the complete documentation index at: https://docs.wsx.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# Server API Reference

> Complete reference for WSX server-side APIs

## WSXServer

The main server class that manages WebSocket connections and request handling.

### Constructor

```typescript theme={null}
new WSXServer(adapter: WSXServerAdapter)
```

Creates a new WSX server instance with the provided adapter.

**Parameters:**

* `adapter` - A WSXServerAdapter implementation (Express, Hono, or custom)

**Example:**

```javascript theme={null}
import { WSXServer } from "@wsx-sh/core";
import { createExpressAdapter } from "@wsx-sh/express";

const adapter = createExpressAdapter();
const wsx = new WSXServer(adapter);
```

### Methods

#### on()

Register handlers for WebSocket requests.

```typescript theme={null}
on(handler: string, handlerFunction: WSXHandler): WSXServer
on(handlerFunction: WSXHandler): WSXServer
```

**Parameters:**

* `handler` (optional) - Handler name to match against `wx-send` attribute
* `handlerFunction` - Function to handle the request

**Returns:** WSXServer instance for chaining

**Examples:**

```javascript theme={null}
// Named handler
wsx.on("update-user", async (request, connection) => {
  return {
    id: request.id,
    target: request.target,
    html: `<div>User updated</div>`,
  };
});

// Catch-all handler
wsx.on(async (request, connection) => {
  console.log(`Received: ${request.handler}`);
  return {
    id: request.id,
    target: request.target,
    html: `<div>Handled: ${request.handler}</div>`,
  };
});
```

#### onJson()

Register handlers for JSON message channels. Accepts either a specific channel or a catch-all handler.

```typescript theme={null}
onJson(channel: string, handler: WSXJSONHandler): WSXServer
onJson(handler: WSXJSONHandler): WSXServer
```

**Parameters:**

* `channel` (optional) - JSON channel name to handle
* `handler` - Function invoked with `WSXJSONMessage` objects

**Example:**

```typescript theme={null}
wsx.onJson('presence', async (message, connection) => {
  wsx.broadcastJson('presence', {
    userId: connection.id,
    status: message.data.status,
  });
});

// Observe every JSON payload
wsx.onJson(async (message) => {
  console.log(message.channel, message.data);
});
```

#### onStream()

Register handlers for binary stream messages. Works with channel-specific or catch-all handlers.

```typescript theme={null}
onStream(channel: string, handler: WSXStreamHandler): WSXServer
onStream(handler: WSXStreamHandler): WSXServer
```

**Parameters:**

* `channel` (optional) - Stream channel name to handle
* `handler` - Function invoked with `WSXStreamMessage` metadata and the binary payload

**Example:**

```typescript theme={null}
wsx.onStream('audio', async (message, data) => {
  console.log(`Received ${data.byteLength} bytes on`, message.channel);
});

wsx.onStream(async (message) => {
  console.log('Stream message on', message.channel);
});
```

#### broadcast()

Send a message to all connected clients.

```typescript theme={null}
broadcast(target: string, html: string, swap?: string): void
```

**Parameters:**

* `target` - CSS selector for the target element
* `html` - HTML content to insert
* `swap` (optional) - Swap method (default: 'innerHTML')

**Example:**

```javascript theme={null}
wsx.broadcast("#status", "<div>Server updated</div>", "innerHTML");
```

#### broadcastJson()

Publish a JSON payload to every connected client.

```typescript theme={null}
broadcastJson(channel: string, data: any, options?: WSXJSONSendOptions): string
```

**Parameters:**

* `channel` - Logical channel name
* `data` - JSON-serializable payload
* `options` (optional) - Additional metadata or explicit identifier

**Returns:** Unique message identifier sent to clients

**Example:**

```typescript theme={null}
wsx.broadcastJson('presence', { userId: 'conn_5', status: 'online' });
```

#### broadcastStream()

Send a binary payload to every connected client.

```typescript theme={null}
broadcastStream(channel: string, payload: WSXBinaryData, options?: WSXStreamSendOptions): string
```

**Parameters:**

* `channel` - Stream channel name
* `payload` - Binary data (`ArrayBuffer` or typed array)
* `options` (optional) - Metadata or explicit stream identifier

**Returns:** Generated stream identifier

**Example:**

```typescript theme={null}
wsx.broadcastStream('audio', audioChunk, { metadata: { mimeType: 'audio/webm' } });
```

#### sendToConnection()

Send a message to a specific connection.

```typescript theme={null}
sendToConnection(connectionId: string, target: string, html: string, swap?: string): void
```

**Parameters:**

* `connectionId` - ID of the target connection
* `target` - CSS selector for the target element
* `html` - HTML content to insert
* `swap` (optional) - Swap method (default: 'innerHTML')

**Example:**

```javascript theme={null}
wsx.sendToConnection(
  "conn_123",
  "#notification",
  "<div>Personal message</div>"
);
```

#### sendJsonToConnection()

Send a JSON message to a specific connection.

```typescript theme={null}
sendJsonToConnection(connectionId: string, channel: string, data: any, options?: WSXJSONSendOptions): string | undefined
```

**Parameters:**

* `connectionId` - Target connection ID
* `channel` - JSON channel name
* `data` - JSON-serializable payload
* `options` (optional) - Metadata or explicit message identifier

**Returns:** Message identifier, or `undefined` if the connection is not found

**Example:**

```typescript theme={null}
wsx.sendJsonToConnection(connection.id, 'presence', { status: 'typing' });
```

#### sendStreamToConnection()

Send a binary stream frame to a specific connection.

```typescript theme={null}
sendStreamToConnection(connectionId: string, channel: string, payload: WSXBinaryData, options?: WSXStreamSendOptions): string | undefined
```

**Parameters:**

* `connectionId` - Target connection ID
* `channel` - Stream channel name
* `payload` - Binary payload (`ArrayBuffer` or typed array)
* `options` (optional) - Metadata or explicit identifier

**Returns:** Stream identifier, or `undefined` if the connection is missing

**Example:**

```typescript theme={null}
wsx.sendStreamToConnection(connection.id, 'audio', audioChunk, { metadata: { sequence: 5 } });
```

#### getConnections()

Get all active connections.

```typescript theme={null}
getConnections(): WSXConnection[]
```

**Returns:** Array of active WSXConnection objects

**Example:**

```javascript theme={null}
const connections = wsx.getConnections();
console.log(`Active connections: ${connections.length}`);
```

#### getConnectionCount()

Get the number of active connections.

```typescript theme={null}
getConnectionCount(): number
```

**Returns:** Number of active connections

**Example:**

```javascript theme={null}
const count = wsx.getConnectionCount();
console.log(`${count} clients connected`);
```

#### removeConnection()

Remove a connection from the server.

```typescript theme={null}
removeConnection(connectionId: string): void
```

**Parameters:**

* `connectionId` - ID of the connection to remove

**Example:**

```javascript theme={null}
wsx.removeConnection("conn_123");
```

#### getApp()

Get the underlying framework app instance.

```typescript theme={null}
getApp(): any
```

**Returns:** The framework-specific app instance (Express app, Hono app, etc.)

**Example:**

```javascript theme={null}
const app = wsx.getApp();
app.get("/health", (req, res) => res.json({ status: "ok" }));
```

## WSXRequest

Interface representing an incoming WebSocket request.

```typescript theme={null}
interface WSXRequest {
  id: string; // Unique request ID
  handler: string; // Handler name from wx-send
  target: string; // CSS selector from wx-target
  trigger: string; // Event trigger name
  data?: Record<string, any>; // Form data or wx-data
  swap?: string; // Swap specification
}
```

**Properties:**

* `id` - Unique identifier for the request
* `handler` - Handler name specified in `wx-send` attribute
* `target` - CSS selector from `wx-target` attribute
* `trigger` - Event that triggered the request
* `data` - Form data or data from `wx-data` attribute
* `swap` - Swap specification from `wx-swap` attribute

## WSXResponse

Interface representing a response to send back to the client.

```typescript theme={null}
interface WSXResponse {
  id: string; // Request ID to match
  target: string; // CSS selector for target element
  html: string; // HTML content to insert
  swap?: string; // Swap method
  oob?: WSXOOBUpdate[]; // Out-of-band updates
}
```

**Properties:**

* `id` - Must match the request ID
* `target` - CSS selector for the element to update
* `html` - HTML content to insert
* `swap` - How to insert the content (innerHTML, outerHTML, etc.)
* `oob` - Array of out-of-band updates for other elements

## WSXOOBUpdate

Interface for out-of-band updates.

```typescript theme={null}
interface WSXOOBUpdate {
  target: string; // CSS selector
  html: string; // HTML content
  swap?: string; // Swap method
}
```

**Properties:**

* `target` - CSS selector for the element to update
* `html` - HTML content to insert
* `swap` - How to insert the content

## WSXConnection

Interface representing a WebSocket connection.

```typescript theme={null}
interface WSXConnection {
  id: string; // Unique connection ID
  sessionData?: Record<string, any>; // Session data
  send(data: string): void; // Send data to client
  close(): void; // Close connection
}
```

**Properties:**

* `id` - Unique identifier for the connection
* `sessionData` - Object for storing session-specific data
* `send()` - Method to send data to the client
* `close()` - Method to close the connection

## WSXHandler

Type definition for handler functions.

```typescript theme={null}
type WSXHandler = (
  request: WSXRequest,
  connection: WSXConnection
) => Promise<WSXResponse | WSXResponse[] | void>;
```

**Parameters:**

* `request` - The incoming request
* `connection` - The connection that sent the request

**Returns:** Promise that resolves to:

* `WSXResponse` - Single response
* `WSXResponse[]` - Array of responses
* `void` - No response (useful for side effects only)

## WSXBinaryData

Union type representing allowed binary payloads.

```typescript theme={null}
type WSXBinaryData = ArrayBuffer | ArrayBufferView;
```

## WSXJSONMessage

Structure passed to JSON handlers and received on the client.

```typescript theme={null}
interface WSXJSONMessage {
  id: string;
  channel: string;
  data: any;
  metadata?: Record<string, any>;
}
```

## WSXJSONHandler

Type definition for JSON message handlers.

```typescript theme={null}
type WSXJSONHandler = (
  message: WSXJSONMessage,
  connection: WSXConnection
) => Promise<void> | void;
```

## WSXJSONSendOptions

Optional options when sending JSON messages.

```typescript theme={null}
interface WSXJSONSendOptions {
  id?: string;
  metadata?: Record<string, any>;
}
```

## WSXStreamMessage

Metadata describing a binary stream frame.

```typescript theme={null}
interface WSXStreamMessage {
  id: string;
  channel: string;
  metadata?: Record<string, any>;
}
```

## WSXStreamHandler

Type definition for stream handlers.

```typescript theme={null}
type WSXStreamHandler = (
  message: WSXStreamMessage,
  data: Uint8Array,
  connection: WSXConnection
) => Promise<void> | void;
```

## WSXStreamSendOptions

Optional options when sending binary stream frames.

```typescript theme={null}
interface WSXStreamSendOptions {
  id?: string;
  metadata?: Record<string, any>;
}
```

## WSXServerAdapter

Interface that framework adapters must implement.

```typescript theme={null}
interface WSXServerAdapter {
  setupWebSocket(
    path: string,
    onMessage: (data: string, connection: WSXConnection) => void
  ): void;
  onConnection?(connection: WSXConnection): void;
  onDisconnection?(connection: WSXConnection): void;
  getApp(): any;
}
```

**Methods:**

* `setupWebSocket()` - Set up WebSocket handling
* `onConnection()` - Optional connection handler
* `onDisconnection()` - Optional disconnection handler
* `getApp()` - Return the framework app instance

## Error Handling

WSX provides built-in error handling, but you can customize it:

```javascript theme={null}
wsx.on("error-prone-handler", async (request, connection) => {
  try {
    // Your logic here
    return {
      id: request.id,
      target: request.target,
      html: "<div>Success</div>",
    };
  } catch (error) {
    console.error("Handler error:", error);
    return {
      id: request.id,
      target: request.target,
      html: '<div class="error">Something went wrong</div>',
    };
  }
});
```

## Best Practices

### Handler Organization

```javascript theme={null}
// Group related handlers
const userHandlers = {
  async updateUser(request, connection) {
    // Update user logic
  },

  async deleteUser(request, connection) {
    // Delete user logic
  },
};

// Register handlers
Object.entries(userHandlers).forEach(([name, handler]) => {
  wsx.on(name, handler);
});
```

### Connection Management

```javascript theme={null}
// Track user sessions
const userSessions = new Map();

wsx.on("login", async (request, connection) => {
  const userId = request.data.userId;
  userSessions.set(connection.id, userId);
  connection.sessionData = { userId };

  return {
    id: request.id,
    target: request.target,
    html: "<div>Logged in successfully</div>",
  };
});
```

### Broadcasting Patterns

```javascript theme={null}
// Broadcast to specific users
function broadcastToUser(userId, target, html) {
  const connections = wsx.getConnections();
  connections
    .filter((conn) => conn.sessionData?.userId === userId)
    .forEach((conn) => {
      wsx.sendToConnection(conn.id, target, html);
    });
}

// Broadcast to all except sender
function broadcastExcept(senderId, target, html) {
  const connections = wsx.getConnections();
  connections
    .filter((conn) => conn.id !== senderId)
    .forEach((conn) => {
      wsx.sendToConnection(conn.id, target, html);
    });
}
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Client API" icon="browser" href="/api-reference/client">
    Learn about the client-side API
  </Card>

  <Card title="Type Definitions" icon="code" href="/api-reference/types">
    Complete TypeScript type definitions
  </Card>

  <Card title="Examples" icon="lightbulb" href="/examples/chat">
    See real-world usage examples
  </Card>

  <Card title="Advanced Usage" icon="cog" href="/advanced/performance">
    Advanced patterns and optimization
  </Card>
</CardGroup>
