---
title: "Reconnect to session"
description: "Reconnect a client to an existing WebSocket session, retrieve its chat history, and keep several clients in sync on one session."
---

# Reconnect to session

> Reconnect a client to an existing WebSocket session, retrieve its chat history, and keep several clients in sync on one session.

## Event `session:reconnect`

The `session:reconnect` event allows you to re-establish a connection to an existing
[session](https://docs.moveo.ai/api/websocket/life-cycle.md), because the client was disconnected, or because you want to share the
same session across **multiple clients**. This is particularly useful for maintaining conversation
continuity when network issues occur or when the client needs to reconnect after a temporary
disconnection.

### Use cases

- Recovering from network interruptions
- Re-establishing connection after client-side issues
- Maintaining session state across page refreshes
- Handling temporary disconnections gracefully
- Preserving conversation history and context
- Sharing the same session across multiple clients

### Payload example

```json
{
  "session_id": "123e4567-e89b-12d3-a456-426614174000",
  "timestamp": 1635789600000,
  "identity_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..."
}
```

### Payload fields

| Field            | Type    | Required | Description                                                                                                                                                                                                                      |
| ---------------- | ------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `session_id`     | String  | Yes      | The unique identifier of the session to reconnect to. The initial `session:created` event returns this ID.                                                                                                                       |
| `timestamp`      | Integer | Yes      | Unix timestamp in milliseconds of the moment the client starts the reconnect.                                                                                                                                                    |
| `identity_token` | String  | No       | Required when the integration [requires an identity token](/docs/integrations/web/web-getting-started#require-an-identity-token) and the session started with a token. A JWT for the same user (`sub`) that started the session. |

:::warning
Until `session:reconnected` arrives on this connection, send no other event for the session. When
`require_identity_token` is on, Moveo ignores these events and sends no error.
:::

### Server responses

#### Success: `session:reconnected`

On successful reconnection, the server responds with a `session:reconnected` event. This event
includes the same payload structure as the `session:created` event, containing all session details:

```json
{
  "session_id": "123e4567-e89b-12d3-a456-426614174000",
  "is_service_desk": false,
  "is_conversation": true,
  "is_handover": false,
  "assignee_agent_id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
  "assignee_brain_id": "550e8400-e29b-41d4-a716-446655440000",
  "assignee_collection_id": "c56a4180-65aa-42ec-a945-5fd21dec0538",
  "source": {
    "integration_id": "d9e7c112-8f11-4c80-9318-b3f98b9728d6",
    "channel": "web",
    "opt_out": false,
    "is_test": false,
    "account_id": "6fa459ea-ee8a-3ca4-894e-db77e160355e",
    "brain_id": "550e8400-e29b-41d4-a716-446655440000",
    "brain_parent_id": "329a91d4-dbfd-4dfc-8c76-ccd5d30e476b",
    "brain_version": 3,
    "desk_id": "1b1cb6bb-9c1e-4afe-b139-ca06fa2fff4f",
    "session_timeout": 3600,
    "brain_inactivity_timeout": 600,
    "keep_alive": 120,
    "account_slug": "acme-corp",
    "department_id": "5f8cc8eb-6ef4-4a77-b8a0-51eb3f11e1b4"
  },
  "context": {
    "user": {
      "display_name": "John Doe",
      "phone": "***",
      "email": "john.doe@example.com"
    }
  }
}
```

:::note
For a detailed explanation of all fields in the response, see the
[session:created](https://docs.moveo.ai/api/websocket/create-session.md#success-sessioncreated) documentation.
:::

#### Error: `session:reconnect:error`

If the reconnection fails because of a server error, the server responds with an error event. If the
session does not exist or has expired, the server sends a `session:expired` event instead.

With `require_identity_token` on, the server also sends
[`session:expired`](https://docs.moveo.ai/api/websocket/server-events.md#event-sessionexpired) when a session started with a token and
the reconnect has no valid token for the same `sub`. The client then starts a new session.

```json
{
  "error_code": "internal-server-error",
  "description": "unable to process reconnection"
}
```

### Retrieve chat history

Once a client has reconnected to a session, it can retrieve the chat history by calling the
`session:history:sync` event. This event requests the chat history from the server, and the server
returns a `session:history:synced` event containing the chat history.

#### `session:history:sync` payload

```json
{
  "session_id": "123e4567-e89b-12d3-a456-426614174000",
  "timestamp": 1635789600000
}
```

#### `session:history:synced` payload

```json
{
  "session_id": "123e4567-e89b-12d3-a456-426614174000",
  "history": [
    [
      "message:send", // First element in the array is the event type
      {
        "session_id": "123e4567-e89b-12d3-a456-426614174000",
        "input": {
          "text": "Hello from Client A"
        },
        "timestamp": 1635789600000
      } // Second element in the array is the payload
    ]
  ],
  "context": {
    "user": {
      "display_name": "John Doe"
    }
  }
}
```

:::note
Not all the events are included in the chat history. Only the events that are relevant to the
conversation content are included, such as `message:send`, `message:received`,
`message:brain_received`, `conversation:member_join`, `conversation:member_leave`, etc.
:::

### Session expiration and reconnection

:::note
For detailed information about session states, transitions, timeout mechanisms, and
expiration behavior, see the [Session lifecycle](https://docs.moveo.ai/api/websocket/life-cycle.md) documentation.
:::

When attempting to reconnect to a session, it's important to understand the following:

1. **Session timeout**: sessions have a configurable timeout period. If the session expired, the
   reconnection fails.
2. **Keep alive**: closed sessions remain accessible for a configurable period before final
   expiration.
3. **Session state**: the session must be in a valid state (active or closed but not expired) for
   reconnection to succeed.

## Multi-client session handling

The `session:reconnect` event can be used to handle a single session from multiple clients
simultaneously. This is useful for scenarios where you want to maintain the same conversation across
different devices or browser tabs.

When multiple clients are connected to the same session:

1. Each client must use the same `session_id` to reconnect
2. All clients receive the same session context and state
3. When any client sends a message using `message:send`, the server:
   - Processes the message normally
   - Sends a `message:send:sync` event to all other connected clients
   - Does not send the sync event to the original sender

This behavior ensures that all clients stay in sync with the conversation state.

### Example: multi-client message exchange

```javascript
// Client A implementation
const socketA = io(URL, socketOptions);

// Reconnect to existing session
socketA.emit("session:reconnect", {
  session_id: "123e4567-e89b-12d3-a456-426614174000",
  timestamp: Date.now(),
});

// Send a message after the server confirms the reconnect
socketA.once("session:reconnected", () => {
  socketA.emit("message:send", {
    input: { text: "Hello from Client A" },
    session_id: "123e4567-e89b-12d3-a456-426614174000",
    timestamp: Date.now(),
  });
});

// Client B implementation
const socketB = io(URL, socketOptions);

// Reconnect to the same session
socketB.emit("session:reconnect", {
  session_id: "123e4567-e89b-12d3-a456-426614174000",
  timestamp: Date.now(),
});

// Listen for sync events from other clients
socketB.on("message:send:sync", (data) => {
  console.log("Received sync from other client:", data);
});
```

### Sync event payload structure

The `message:send:sync` event payload is the same as the
[`message:send`](https://docs.moveo.ai/api/websocket/message-exchange.md#client-sends-message-messagesend) payload that the other client
sent. AI agent and human agent responses reach every connected client as
[`message:brain_received` and `message:received`](https://docs.moveo.ai/api/websocket/message-exchange.md#server-sends-message-messagereceived-or-messagebrain_received)
events.

```json
{
  "session_id": "123e4567-e89b-12d3-a456-426614174000",
  "input": {
    "text": "Hello from Client A"
  },
  "timestamp": 1635789600000
}
```

:::note
The `message:send:sync` event is only sent to other clients connected to the same session.
The client that sent the original message does not receive this sync event.
:::

:::note
For detailed payload structures and field descriptions, see the
[Send and receive messages](https://docs.moveo.ai/api/websocket/message-exchange.md) documentation.
:::

:::tip
When implementing multi-client support, consider:

- Handling message synchronization across all connected clients
- Managing UI state to reflect the current active client
- Implementing proper cleanup when clients disconnect
:::

### Example usage

```javascript
// Initialize socket connection
const socket = io(URL, socketOptions);

// Reconnect payload
const reconnectPayload = {
  session_id: "123e4567-e89b-12d3-a456-426614174000",
  timestamp: Date.now(),
  // For a session that started with a token
  identity_token: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
};

// Send reconnect event
socket.emit("session:reconnect", reconnectPayload);

// Handle success response
socket.on("session:reconnected", (data) => {
  console.log("Successfully reconnected to session:", data.session_id);

  // Sync the message history after the reconnect
  socket.emit("session:history:sync", {
    session_id: data.session_id,
    timestamp: Date.now(),
  });
});

// Handle error response
socket.on("session:reconnect:error", (error) => {
  console.error("Error reconnecting to session:", error.description);
  // Handle the error appropriately (e.g., create a new session)
});

// Handle a refused reconnect: the session is gone, so start a new one
socket.on("session:expired", () => {
  socket.emit("session:create", {
    timestamp: Date.now(),
    // Required when the integration requires an identity token
    identity_token: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
  });
});
```

### Best practices

1. **Error Handling**

   - Implement proper error handling for reconnection failures
   - Consider creating a new session if reconnection fails
   - Log reconnection attempts and failures for debugging

2. **Session Management**

   - Store session IDs securely for future reconnection attempts
   - Implement session validation before attempting reconnection
   - Handle session expiration gracefully

3. **Message Synchronization**

   - After successful reconnection, sync message history
   - Ensure message continuity across reconnections
   - Handle any missed messages appropriately

4. **Network Considerations**
   - Implement exponential backoff for reconnection attempts
   - Handle network interruptions gracefully
   - Consider implementing offline message queuing

:::tip
To maintain session continuity, consider implementing automatic reconnection logic in your
WebSocket client implementation. This can help handle temporary network issues without user
intervention.
:::
