---
title: "Create session"
description: "Create a WebSocket session with the session:create event, and read the session:created response and the errors the server returns."
---

# Create session

> Create a WebSocket session with the session:create event, and read the session:created response and the errors the server returns.

## Event `session:create`

The `session:create` event is used to initialize a new conversation session after establishing a
WebSocket connection. This event registers a new conversation context and prepares the system to
receive and process messages.

```json
{
  "context": {
    "user": {
      "display_name": "John Doe",
      "phone": "+1234567890"
    }
  },
  "identity_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "timestamp": 1635789600000,
  "is_test": false,
  "opt_out": false
}
```

### Payload fields

| Field            | Type    | Required | Description                                                                                                                                                                                                              |
| ---------------- | ------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `context`        | Object  | No       | A [context object](/docs/ai-agents/context) containing information about the user and conversation environment. This context is available throughout the session lifecycle.                                              |
| `identity_token` | String  | No       | JWT token for identity verification. Required when the integration has [`require_identity_token`](/docs/integrations/web/web-getting-started#require-an-identity-token) on.                                              |
| `timestamp`      | Integer | Yes      | Unix timestamp in milliseconds of the moment the client starts the session.                                                                                                                                              |
| `is_test`        | Boolean | No       | Flag indicating if this is a test session. Defaults to `false` if not provided.                                                                                                                                          |
| `opt_out`        | Boolean | No       | When `true`, Moveo does not store analytics data for this session. Defaults to `false`. The session also opts out when the account turns off [**Use data and analytics**](/docs/platform/platform-account#data-privacy). |

### Server responses

#### Success: `session:created`

On successful session creation, the server responds with a `session:created` event containing the
created 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": "+1234567890"
    }
  }
}
```

#### Response fields

| Field                        | Description                                                                     |
| ---------------------------- | ------------------------------------------------------------------------------- |
| `session_id`                 | Unique identifier for the created session, used in all subsequent interactions. |
| `source.brain_inactivity_timeout` | Time in seconds before the session expires due to inactivity when an AI agent is assigned. |
| `is_service_desk`            | Indicates if this session is connected to a service desk.                       |
| `is_conversation`            | Indicates if this session is a conversation type.                               |
| `is_handover`                | Indicates if this session is configured for human handover.                     |
| `assignee_agent_id`          | ID of the human agent assigned to this session (if any).                        |
| `assignee_brain_id`          | ID of the AI agent assigned to this session.                                    |
| `source.keep_alive`          | Time in seconds that a closed conversation stays open for a reopen.             |
| `assignee_collection_id`     | ID of the collection assigned to this session.                                  |
| `source`                     | Object containing metadata about the integration and account.                   |
| `context`                    | Copy of the initial context provided.                                           |

:::warning
Moveo controls certain fields in the context object. As these are likely to be sensitive,
the server obfuscates these fields in the response and shows them as `***`.
:::

#### Error responses

If session creation fails, the server responds with one of the following error events:

| Error event                                   | Description                                                                                                      |
| --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `session:create:error`                        | General error during session creation.                                                                           |
| `session:create:error:invalid_identity_token` | The provided identity token is invalid or expired, or the integration requires a token and the payload has none. |
| `session:create:error:invalid_private_key`    | The private key used for verification is invalid.                                                                |
| `session:create:error:invalid_aes_claims`     | The AES claims in the token are invalid.                                                                         |
| `session:create:error:failed_aes_descryption` | AES decryption of the token failed.                                                                              |

Error responses include the following payload:

```json
{
  "error_code": "identity-token-error",
  "description": "invalid jwt token"
}
```

For a missing token, the description is `identity token is required for this integration`.

## Session lifecycle

After successful creation, the session enters the active state and remains available until
explicitly closed or until it expires. The `session:created` response contains important timeout
values (`source.brain_inactivity_timeout`, `source.keep_alive`, and `source.session_timeout`) that
govern the session's lifespan.

:::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.
:::

## Example usage

The following example demonstrates how to create a session using the WebSocket API:

```javascript
// Initialize socket connection (see connection.md for details)
const socket = io(URL, socketOptions);

// Connection event handling
socket.on("connect", () => {
  console.log("Connected to WebSocket API");

  // Create session payload
  const sessionCreatePayload = {
    context: {
      user: {
        display_name: "Jane Smith",
        email: "jane.smith@example.com",
      },
    },
    timestamp: Date.now(),
    is_test: false,
    opt_out: false,
  };

  // Send session:create event
  socket.emit("session:create", sessionCreatePayload);
});

// Handle success response
socket.on("session:created", (data) => {
  console.log("Session created:", data.session_id);
  // Store session_id for future interactions
  const sessionId = data.session_id;

  // Now you can start sending messages with this session_id
});

// Handle specific error responses
socket.on("session:create:error", (error) => {
  console.error("General error creating session:", error.description);
});

socket.on("session:create:error:invalid_identity_token", (error) => {
  console.error("Invalid identity token:", error.description);
});

// Handle other potential errors
socket.on("session:create:error:invalid_private_key", handleAuthError);
socket.on("session:create:error:invalid_aes_claims", handleAuthError);
socket.on("session:create:error:failed_aes_descryption", handleAuthError);

function handleAuthError(error) {
  console.error("Authentication error:", error.description);
  // Implement retry logic or user notification
}
```

:::tip
To prevent premature session expiration, send regular `session:activity` events during
periods of user inactivity. See [Client events](https://docs.moveo.ai/api/websocket/client-events.md#event-sessionactivity) for
implementation details.
:::
