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

# WebSocket Protocol

> Connecting to the Magne real-time WebSocket API.

# WebSocket Protocol

Magne uses a WebSocket connection for real-time event delivery. All presence updates, messages, typing indicators, and voice states are pushed through this channel.

## Connection

```
wss://api.magne.chat/v1/ws?token=YOUR_ACCESS_TOKEN
```

The access token is passed as a query parameter. The server validates the token and associates the connection with the authenticated user.

## Connection Lifecycle

1. **Connect** — Client opens WSS connection with token
2. **Authenticated** — Server validates token, registers the session
3. **Events flow** — Server pushes events as JSON frames
4. **Heartbeat** — Server tracks connection health
5. **Disconnect** — Client closes connection or token expires

## Message Format

All WebSocket messages are JSON-encoded with a consistent structure:

```json theme={null}
{
  "eventType": "message.created",
  "data": {
    "id": "msg-uuid",
    "channelId": "channel-uuid",
    "authorId": "user-uuid",
    "content": "Hello world",
    "createdAt": "2026-03-03T12:00:00Z"
  }
}
```

## Multi-Session

Users can have **multiple simultaneous WebSocket connections** (e.g., desktop + mobile). The server tracks connection count per user and only triggers cleanup (voice disconnect, presence offline) when **all** connections close.

<Note>
  This prevents false presence flickers during reconnection or when switching
  devices.
</Note>

## Reconnection

If disconnected, clients should implement **exponential backoff**:

1. Wait 1 second, reconnect
2. If failed, wait 2 seconds
3. If failed, wait 4 seconds
4. Cap at 30 seconds between attempts
5. Refresh access token if expired before reconnecting
