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

# Chat SDK API reference

> Every Chat SDK method, client option, event, and error code

Reference for `@typewise/chat-sdk`. For a guided introduction, start with
[Getting started](https://docs.typewise.app/guides/channels/chat-sdk/getting-started.md).

## createClient

```typescript theme={null}
import { createClient } from "@typewise/chat-sdk";

const chat = createClient(options);
```

Creates a client for one visitor. It does no network work until you call a
method.

### Options

**clientId** `string` *required*

Your Typewise client ID, from **Behavior → Channels → Chat → Installation**.

**workspaceId** `string` (default: Default workspace)

Workspace to load configuration and the Domain allowlist from.

**language** `string` (default: Runtime locale, then en)

Language short code, such as `de`.

**variables** `object | () =\> object`

Context variables for new conversations. Pass a function to read fresh values
each time a conversation starts. See [Share page
context](https://docs.typewise.app/guides/channels/chat-sdk/page-context.md).

**signedVariables** `string | () =\> string | Promise\<string\>`

A JWT signed by your backend, or a function returning one. The SDK calls the
function each time it authenticates. See [Identify signed-in
users](https://docs.typewise.app/guides/channels/chat-sdk/page-context.md#identify-signed-in-users).

**initialMessages** `string[]` (default: Platform configuration)

Greetings shown before a conversation starts.

**storage** `StorageAdapter` (default: localStorage, otherwise in-memory)

Where the visitor session is kept. Any object with `getItem`, `setItem`, and
`removeItem` works, sync or async, such as React Native's `AsyncStorage`.

**storageKey** `string` (default: tw-client-sdk:\<clientId>)

Storage key for the visitor session.

**baseUrl** `string` (default: [https://platform-api.typewise.app](https://platform-api.typewise.app))

API origin.

**fetch** `function` (default: globalThis.fetch)

Custom `fetch` implementation.

## State

**getState()** `ChatState`

Returns the current [state
snapshot](https://docs.typewise.app/guides/channels/chat-sdk/render-messages.md#the-state-snapshot).

**subscribe(listener)** `() =\> void`

Calls `listener` with the new state after every change. Returns a function
that unsubscribes.

**on(event, listener)** `() =\> void`

Listens to one [event](#events). Returns a function that unsubscribes.

**getConfig()** `Promise\<ChatConfig\>`

Loads and caches the chat configuration, including greetings. `resume()` calls
it for you.

## Conversation

**resume()** `Promise\<Conversation | null\>`

Restores the stored conversation and connects to real-time updates. Resolves
to `null` when there is none.

**sendMessage(input)** `Promise\<Message\>`

Sends a message, starting a conversation first if needed. Messages sent while
it starts are merged into one. Pass a string, or an object:

**input**

**text** `string` *required*

The message text. Can be empty when `attachments` has files.

**attachments** `Attachment[]`

Files returned by
[`uploadFiles`](#attachments-surveys-and-verification).

**startNewConversation()** `Promise\<Conversation\>`

Closes the current conversation and starts a new one.

**close()** `Promise\<void\>`

Closes the conversation. It's removed locally at once, and the request
survives page unloads.

**reopen()** `void`

Lets the visitor keep writing after the conversation was closed on the server.
Check `conversation.canReopen` first.

**setTyping(isTyping)** `Promise\<void\>`

Shows the visitor's typing state to Human Agents.

**setVariables(input)** `Promise\<SetVariablesResult\>`

Updates context on the open conversation, or holds it for the next one.

**input**

**variables** `object`

Unverified values: strings, numbers, or booleans.

**signedVariables** `string`

A JWT signed by your backend.

**result**

**droppedVariableKeys** `string[]`

Names not declared in Context Variables.

**rejectedVariableKeys** `string[]`

Unsigned values that couldn't overwrite a value that arrived verified.

## Attachments, surveys, and verification

See
[Attachments, surveys, and verification](https://docs.typewise.app/guides/channels/chat-sdk/attachments-surveys-verification.md)
for how these fit together.

**uploadFiles(files, options)** `Promise\<UploadResult[]\>`

Uploads `File`s, `Blob`s, or `{ name, type, data }` objects. Resolves to one
result per file: `{ ok: true, name, attachment }` or `{ ok: false, name,
    error }`.

**options**

**onProgress** `(\{ index, name, loaded, total \}) =\> void`

Called as bytes are sent. Needs `XMLHttpRequest` (browsers and React
Native). Elsewhere it fires only when each file completes.

**getAttachmentUrl(message, attachment)** `Promise\<string\>`

Returns a short-lived download URL. Fails for messages that are still sending.

**csat.getConfig()** `Promise\<CsatConfig\>`

Loads the survey prompt (`csatMessage`) and any previous `lastRating` and
`lastComment`.

**csat.submit(\{ rating, comment })** `Promise\<void\>`

Submits a rating from 1 to 5 and an optional comment.

**verification.sendCode(email)** `Promise\<void\>`

Sends a verification code to the email.

**verification.verifyCode(code)** `Promise\<\{ success, reason \}\>`

Checks the code. When `success` is `false`, `reason` is `invalid_code`,
`max_attempts`, or `expired`.

**verification.getStatus()** `Promise\<VerificationStatus\>`

Returns `state` (`none`, `awaiting_email`, `awaiting_code`, or `verified`),
`email`, and `attemptsRemaining`.

**getTranscriptionKey()** `Promise\<string\>`

Returns a short-lived ElevenLabs key for speech-to-text.

## Session

**track(event, properties)** `Promise\<void\>`

Records a product analytics event for this visitor. Does nothing before the
visitor has a session.

**resetSession()** `Promise\<void\>`

Forgets the visitor and disconnects, for example on logout.

**destroy()** `Promise\<void\>`

Disconnects and releases the client. It can't be used afterwards.

## Events

Listen with `chat.on(event, listener)`. For the fields of `Message`,
`Conversation`, and `Activity`, see
[Render messages and activity](https://docs.typewise.app/guides/channels/chat-sdk/render-messages.md#the-state-snapshot).

**message** `Message`

A new message arrived or was sent.

**messageUpdated** `\{ message, previousId \}`

A message changed, for example when the server confirmed a sent message and
its `id` changed from `previousId`.

**conversation** `Conversation | null`

The conversation started, changed status, or closed.

**activity** `Activity`

The typing indicator changed.

**connection** `string`

The real-time connection state changed.

**error** `TypewiseError`

A background task failed, such as a history refresh after a reconnect.

## Errors

Methods reject with a `TypewiseError`. HTTP failures also carry a `status`.
Failures in the background are emitted on `chat.on("error", listener)` instead.

| `code` | Meaning |
| :- | :- |
| `invalid_input` | The call's arguments are invalid, such as an empty message |
| `http` | The API returned an error. Check `status`: `404` means the client or workspace ID doesn't exist |
| `network` | The request didn't reach the API |
| `auth` | The API rejected the visitor's session (HTTP 401 or 403) |
| `realtime` | The real-time connection failed |
| `upload` | A file upload failed |
| `no_conversation` | The method needs an open conversation |
| `destroyed` | The client was destroyed |

```javascript theme={null}
import { TypewiseError } from "@typewise/chat-sdk";

try {
  await chat.sendMessage(text);
} catch (error) {
  if (error instanceof TypewiseError && error.code === "network") {
    showOfflineBanner();
  }
}
```

## Other exports

**createMemoryStorage()** `StorageAdapter`

In-memory storage adapter, for servers and tests.

**TypewiseError** `class`

The error class methods reject with.

**Types** `TypeScript`

`ChatState`, `Message`, `Conversation`, `Activity`, `ChatConfig`,
`TypewiseClient`, and more. Types are bundled with the package.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.