# Twilio Flex SDK

With the Twilio Flex SDK, you can embed Twilio Flex contact center features into any web application.

This SDK can only be consumed together with Twilio Flex. Visit https://twilio.com/flex and https://www.twilio.com/docs/flex/developer/flex-sdk to find out more.

## Getting started

### Installation

To install the Twilio Flex SDK, run the following command in your terminal:

```bash
npm install @twilio/flex-sdk
```

## API usage

Initializing the SDK

```javascript
import { createClient } from "@twilio/flex-sdk";

// Initialize the client
const client = await createClient("SDK_TOKEN");
```

To initialize the Flex SDK, simply call createClient with your SDK token:

### Providing a Custom Worker and Workspace

If you already have or want to manually manage the Worker and/or Workspace, you can pass them to the SDK during initialization.
However, it’s important to ensure that you import and initialize them correctly to maintain full compatibility with Flex SDK functionalities.

```javascript
import { createClient } from "@twilio/flex-sdk";
import { Worker, Workspace } from "@twilio/flex-sdk/taskrouter";

const TOKEN = "SDK_TOKEN";

// Initialize Worker and Workspace correctly
const worker = new Worker(TOKEN);
const workspace = new Workspace(TOKEN);

// Pass them to the SDK client during initialization
const client = await createClient(TOKEN, { worker, workspace });
```

📌 Note: Incorrect initialization may cause unexpected behavior or compatibility issues with Flex SDK features.

## Using a Custom Voice Device

To customize how voice calls behave, you can make use of the Twilio Voice SDK `@twilio/voice-sdk` package.
Create a custom Device object and pass it as a parameter to any voice actions.

**Prerequisite**

-   The `@twilio/flex-sdk` package automatically pulls in `@twilio/voice-sdk`.
-   If you install `@twilio/voice-sdk` separately, make sure the version exactly matches the one bundled with FlexSDK to avoid conflicts.

```javascript
import { Device } from "@twilio/voice-sdk";
import { AddVoiceEventListener, createClient } from "@twilio/flex-sdk";

async function setVoiceDevice() {
    // Get user permission to access audio devices
    const token = "REPLACE_WITH_ACCESS_TOKEN";
    await navigator.mediaDevices.getUserMedia({ audio: true });

    const device = new Device(token);
    await device.register();
    const inputDevices = Array.from(device.audio?.availableInputDevices.values() || []);
    const myCustomMicrophoneId = inputDevices[1].deviceId;
    await device.audio?.setInputDevice(myCustomMicrophoneId);

    const client = await createClient(token);
    client.execute(
        new AddVoiceEventListener(
            "incoming",
            (call) => {
                console.log("Incoming Call", call);
            },
            { voiceDevice: device }
        )
    );
}
```

## Troubleshooting and debugging

### General issues

#### Errors when making API calls

-   Ensure you’re making the correct API calls by referring to the API documentation.
-   Double-check your API credentials and ensure they are properly configured.
-   Review any error messages for specific error codes or details.

### Debugging the SDK

To debug the SDK, enable logging and monitor the console output. You can configure logging as follows:

```javascript
import { createClient } from "@twilio/flex-sdk";

// Set the desired log level (e.g., TRACE)
const client = await createClient("SDK_TOKEN", {
    logger: { level: "DEBUG" } // Set level (TRACE | DEBUG | INFO | WARN | ERROR)
});
```

| Log Level | Description                                                       | Typical Use‑case        |
| --------- | ----------------------------------------------------------------- | ----------------------- |
| **TRACE** | Verbose, includes every request/response, payloads, stack traces. | _Deep debugging_.       |
| **DEBUG** | Shows SDK internals, error details, and important state changes.  | _General development_   |
| **INFO**  | High‑level operational messages (e.g., connection opened).        | _Monitoring_            |
| **WARN**  | Indicates recoverable problems (e.g., retrying a request).        | _Production alerts_     |
| **ERROR** | Critical failures that halt a feature or request.                 | _Production monitoring_ |

> **Default** – `ERROR` (ensures you only see real problems in production).

### Additional resources

-   [Twilio Flex SDK Documentation](https://www.twilio.com/docs/flex/developer/flex-sdk)
-   [Twilio Flex Developer Documentation](https://www.twilio.com/docs/flex/developer)
