> ## Documentation Index
> Fetch the complete documentation index at: https://koreai-agent-management-platform-dev.mintlify.app/llms.txt
> Use this file to discover all available pages before exploring further.

# Kore.ai Web SDK Tutorial

<Badge icon="arrow-left" color="gray">[Back to App Settings](/ai-for-service/app-settings)</Badge>

This tutorial is an end-to-end walkthrough for setting up and running an instance of the App's Web SDK — a collection of libraries for integrating App with your own web applications.

## Web SDK Tutorial Overview

In this tutorial, you will install a sample app, a test application to host the app, and then a JSON Web Token (JWT) generation web service using your local host server to communicate between the app on your local server and the XO Platform.

The following steps describe the general installation and configuration process:

1. **Build the App to be integrated** - Install the *Travel Planning Sample* App, which uses open APIs to get flight and location information along with weather reports.
2. **Configure Web/Mobile Client channel** - Configure the App for the Web/Mobile Client channel.
3. **Create a new Client App** - Create a client app and select the JWT signing algorithm used to generate authentication tokens.
4. **Publish the App** - Publish the app to send it to the Admin for approval.
5. **Approve and Deploy the App** - In the Admin Console, approve and deploy the published App and tasks.
6. **Download and install Node.js** - Install Node.js to host the JWT token generation web service.
7. **Download and uncompress the test application** - The test application, [SDKApp](https://s3.amazonaws.com/static-kore/downloads/SDKApp.zip) simulates your application hosting the Kore.ai App as a channel on a web page using your computer's local host server.
8. **Download and uncompress the Kore.ai Web SDK** - The Web SDK contains the libraries to communicate and run the App using the Web/Mobile Client channel. Configure settings in the index.html file for your computer.
9. **Start your application and view the App in a web browser** - Start the JWT service in a **Terminal** window, then view the App in a web browser.

***

## Installing and Running the Kore.ai Web SDK

This section provides detailed steps to run a Kore.ai sample app using the Web SDK and a test application on your local host server.

1. Log on to App Builder, click the **down-arrow** next to **+New App**, and select **Install Sample Apps.**
2. Hover over **Travel Planning Sample**, then click **Install**.
3. The Travel Planning Sample installed successfully message is displayed and the sample App is added to your **Apps** left-hand navigation menu.

In the next section, define the Web/Mobile Client channel for the Travel Planning Sample App by creating a new client app and defining channel settings. [See here](/ai-for-service/channels/add-web-mobile-client#adding-the-web-mobile-client-channel) for a detailed explanation.

4. On the App builder top menu, select the **Deploy** tab.

5. From the left menu, click **Integrations > Web/Mobile SDK**.

6. In the **Select App** drop-down list, click **Create App**. The **Create Client App** dialog opens.

7. In the **Name** field, enter a name for your app, for example, My SDK Client App.

8. In the **JWT Signing Algorithms** section, select **HS256** to generate the authentication tokens.

9. Click **Next -> Done**.

10. The **Web/Mobile Client Channel** page displays the following JWT credentials — record all of these:
    1. App Name
    2. App ID
    3. Client ID
    4. Client Secret

11. Click **Save**.

    <Note>By default, the Travel Sample Planning App is configured with **Target Audience** set to **Enterprise Users** on the **Build** tab under **Configurations -> General Settings.** You can optionally define this App for **General Public** use. Once published, the **Target Audience** can't be changed.</Note>

12. On the **Deploy** tab, click **Publish**.

13. On the **Publish** page, select all tasks, then click **Proceed**.

14. Enter a comment and **Confirm** publish.

    After an enterprise developer publishes an app, it must be approved and assigned to users.

15. Complete one of the following app deployments in the Admin Console depending on whether your app **Target Audience** is set to **Enterprise Users** or **General Public**:
    1. In the Admin Console, in the **Bots Management** module, on the **Enterprise Bots** page, click the **Ellipses** icon for the Travel Planning Sample bot you want to deploy, then click **Manage bot tasks**. The **Manage Bot Tasks** dialog opens.
    2. In the **Bot tasks** field, click the **Expand** <img src="https://mintcdn.com/koreai-agent-management-platform-dev/txDBUCK5q7jgVuxe/ai-for-service/app-settings/dev-tools/images/web-mobile-sdk-imgarrow.png?fit=max&auto=format&n=txDBUCK5q7jgVuxe&q=85&s=d8f55d0158e293901f52a424be9c08a9" alt="expand arrow" width="20" height="24" data-path="ai-for-service/app-settings/dev-tools/images/web-mobile-sdk-imgarrow.png" /> icon to display available and deployed tasks, select all tasks for this bot, then click **Confirm**.
    3. In the **Manage bots tasks** dialog, click **Confirm**. The Bot status changed successfully message is displayed.
    4. On the **Enterprise Bots** page, click the **Ellipses** icon for the Travel Planning Sample bot, then click **Bot & task assignments**.
    5. In the **Bot & task assignments** dialog, assign the bot to your users for all tasks, including yourself.

16. To download and install Node.js, go to [https://nodejs.org/en/download/](https://nodejs.org/en/download/) and select your OS (.pkg for Mac, .msi for Windows).

17. In a **Terminal** window, run `node -v` to verify installation and version, for example, `v6.10.2`.

18. Locate the **SDKApp/sdk** folder of your web server where you want to integrate the app. For this tutorial, download the test application and JWT web service from [SDKApp](https://s3.amazonaws.com/static-kore/downloads/SDKApp.zip) and unzip it.

19. To download the Kore.ai Web SDK, go to [https://github.com/Koredotcom/web-kore-sdk](https://github.com/Koredotcom/web-kore-sdk). In the **master** dropdown, select the required **Branch/Tag**, then in the **Code** dropdown, click **Download ZIP**. Extract all files to the `…/SDKApp/sdk` folder. Check release compatibility in the [release notes](/ai-for-service/release-notes/automation-ai).

20. From the App Builder **Web/Mobile Client Channel** page under **Deploy -> Channels**, copy the following (from step 10 above):
    1. clientSecret
    2. clientId
    3. App Name

21. For ver7.2 of the platform, the Web SDK repo structure underwent a major change. Follow the appropriate steps based on which repo you are using:

    **a. For the latest Web SDK downloaded after ver7.2 (after Feb 2020):**

    1. Open `index.html` from the `…/SDKApp/sdk/UI` folder in a text editor. Update the following lines to add the path to the UI folder:

       ```html  theme={null}
       <script src="libs/jquery.js" type="text/javascript"></script>
       <script src="libs/jquery.tmpl.min.js" type="text/javascript"></script>
       <script src="libs/jquery-ui.min.js" type="text/javascript"></script>
       <link href="libs/jquery-ui.min.css" rel="stylesheet"></link>
       <script src="chatWindow.js" type="text/javascript"></script>
       <link href="chatWindow.css" rel="stylesheet"></link>
       ```

    2. Open `kore-config.js` and update the `botOptions` parameters `botInfo`, `clientId`, `clientSecret`, and your email as `userIdentity`:

       ```js  theme={null}
       "clientSecret": "{client secret}"
       $.ajax({
       url: "https://localhost:3000/api/users/getJWT",
           //this is sample url of a localhost.
           //This should include the url where you are hosting the app.
       botOptions.userIdentity = ' ';
           // Provide users email id here
       botOptions.clientId= "{client id} ";
           // secure client-id
       _botOptions.botInfo= {name:"{bot name}","id":"{bot id"};
           // Kore bot name is case sensitive
       })
       ```

       The JWTUrl refers to the location where your app is hosted. For this tutorial, the JWT server from step 19 is used.

    3. Set the audience in `kore-config.js`. Choose one of the following:
       * `"isAnonymous": <**false**>;` if the app is deployed for **enterprise users**, then set `botOptions.userIdentity = '< Your email ID >'`;

         **- or -**

       * `"isAnonymous": <**true**>;` if the app is deployed for **Consumer Use**

    **b. For older Web SDK downloaded before ver7.2 (before Feb 2020):**

    Open `index.html` from the `…/SDKApp/sdk/UI` folder in a text editor:

    1. Update the following lines to add the path to the UI folder:

       ```html  theme={null}
       <script src="libs/jquery.js" type="text/javascript"></script>
       <script src="libs/jquery.tmpl.min.js" type="text/javascript"></script>
       <script src="libs/jquery-ui.min.js" type="text/javascript"></script>
       <link href="libs/jquery-ui.min.css" rel="stylesheet"></link>
       <script src="chatWindow.js" type="text/javascript"></script>
       <link href="chatWindow.css" rel="stylesheet"></link>
       ```

    2. Update the following parameters to run as local host:

       ```js  theme={null}
       "clientSecret": "{client secret}"
       $.ajax({
       url: "https://localhost:3000/api/users/getJWT",
           //this is sample url of a local host.
           //This should include the url where you are hosting the app.
       botOptions.userIdentity = ' ';
           // Provide users email id here
       botOptions.clientId= "{client id} ";
           // secure client-id
       _botOptions.botInfo= {name:"{bot name}","id":"{bot id"};
           // Kore bot name is case sensitive
       })
       ```

       <Note>The URL in the above snippet refers to the location where your app is hosted. For this tutorial, the JWT server from step 15 is used.</Note>

    3. Choose one of the following:
       * `"isAnonymous": <**false**>;` if the app is deployed for **enterprise users**, then set `botOptions.userIdentity = '< Your email ID >'`;

         **- or -**

       * `"isAnonymous": <**true**>;` if the app is deployed for **Consumer Use**

22. Save your changes.

23. Go to the home directory: `cd SDKApp`

24. Install dependencies:

    `npm install`

    <img src="https://mintcdn.com/koreai-agent-management-platform-dev/txDBUCK5q7jgVuxe/ai-for-service/app-settings/dev-tools/images/web-mobile-sdk-img1.png?fit=max&auto=format&n=txDBUCK5q7jgVuxe&q=85&s=a333dfa6443e34cb708b2ad91f7dccbc" alt="Install dependencies" width="668" height="179" data-path="ai-for-service/app-settings/dev-tools/images/web-mobile-sdk-img1.png" />

25. Start SDKApp:

    `node startServer.js`

26. Access the application in any browser at `localhost:3000`.

***

### Passing data via webSDK

Pass additional user information by adding custom data at `botInfo` inside the `index.html` file:

```js  theme={null}
botOptions.botInfo = {name: "Banking Bot",
                      "_id": "<bot_id>",
                      customData: "value"
          };
```

Details like phone number, address, or location are examples of data that can be passed inside `customData`.

`customData` can be accessed from `lastMessage` under the `BotUserSession` of the context object. This data is specific to the user using webSDK and lasts for the user session.

Multiple values can be added to `customData` as key-value pairs:

```js  theme={null}
botOptions.botInfo = {name:"<bot_name>",
                      "_id":"<bot_id",
                      customData:{"name":"John",
                                  "age":30,
                                   "cars": {"car1":"Ford",
                                            "car2":"BMW",
                                            "car3":"Fiat"
                                             }
                                   }
                           };
```

#### Accessing customData in Your App Implementation

The custom data passed through the web SDK is accessible from two paths:

* `context.session.UserContext.customData`
* `session.BotUserSession.channels[0].botInfo.customData`

Both paths provide access to the same `customData` object. This dual access design supports multiple processing purposes and gives developers flexibility in how they retrieve and use this information.

<img src="https://mintcdn.com/koreai-agent-management-platform-dev/txDBUCK5q7jgVuxe/ai-for-service/app-settings/dev-tools/images/web-mobile-sdk-img2.png?fit=max&auto=format&n=txDBUCK5q7jgVuxe&q=85&s=317655d76a5c4e4bb66c5a9d9a0ba0d6" alt="BotUserSession of the context object" width="444" height="492" data-path="ai-for-service/app-settings/dev-tools/images/web-mobile-sdk-img2.png" />

***

### Passing Mapped Identities

The Web/Mobile SDKs support passing mapped identities when users switch from one identity to another during an app interaction. This allows users to continue any ongoing conversation initiated using a previous identity.

For example, a user may start a conversation with an anonymous or randomly generated identity. After exchanging messages, the user becomes authenticated by logging into your website. At that point, the known identity can be passed to the app from the SDK as part of the [JWT Grant API](/ai-for-service/sdk/sdk-security#jwt-flow) call using the parameter `identityToMerge`. The Platform merges the user identities and allows the user to resume an ongoing conversation using the new known identity.

```json  theme={null}
{
 "iat": 161181018xxxx,
 "exp": 1611813xxx.883,
 "aud": "https://idproxy.kore.com/authorize",
 "iss": "cs-d3042d3e-7da4-55da-a94d-78334927xxxx",
 "sub": "john.doe@example.com ",
 "isAnonymous": "false",
 "identityToMerge": "john.doe@example.com"
}
```

The following scenarios describe app behavior when dealing with new and merged identities:

* When both the new and merged identities aren't present in the system, the new identity is created and a new conversation starts using the new identity.
* When the new identity is present but the merged identity isn't, the conversation starts or continues (if active session) using the new identity.
* When the merged identity is present but the new identity is not, the new identity is created and the conversation continues using the new identity. All references to the merged identity are replaced with the new identity, and the merged identity is removed.
* When both identities are present and the new identity has no active session, the conversation continues using the new identity. All references to the merged identity are replaced, and the merged identity is removed.
* When both identities are present and both have an active session, the merged identity's conversation continues using the new identity. All references to the merged identity are replaced, and the merged identity is removed. The active session of the new identity is marked as "Drop-off" and closed.

Due to the above identity behavior, the following changes occur:

* Analytics and Chat History are updated, associating all sessions related to the merged identity with the new identity.
* Sessions data is updated replacing the merged identity with the new identity.
* The Billing Session tracking the merged identity's conversation is marked as the new identity.

***

### Custom Meta Tags via webSDK

From ver8.0 of the platform, you can directly add Custom Meta Tags from all supported internal channels (Web SDK/IVR/IVRVoice/Webhook channels). Define Session, User, and Message level meta-tags. These tags are added to the Conversation Session as soon as it's created.

```js  theme={null}
botOptions.botInfo = {
    name:"<bot_name>", "_id":"<bot_id",
    customData :{"name":"John"},
    "metaTags": {
            "messageLevelTags": [{ "name": "tag1", value: "message"}],
            "sessionLevelTags": [{ "name": "tag2", value: "session"}],
            "userLevelTags": [{ "name": "tag3", value: "user"}]
            }
    };
```

***

### Common Errors

* **404 error**: A wrong URL is given in `index.html`. Double-check the URL. If using Kore's web SDK, the URL is `https://demo.kore.net:3000/users/sts 7`. If hosting on an in-house web SDK, provide the respective URL.

* **missing/Invalid jwt.sub()**: Occurs for enterprise Apps when the user's email ID is not provided in `index.html`. Add the user identity:

  `botOptions.userIdentity = 'john.doe@example.com';// Provide users email id here.`

* **Not found**: Occurs when either a wrong clientID or no clientID is given. Check the correct ClientID from App - API Extensions:

  `botOptions.clientId = "{clientID}"; // secure client-id`

* **error verifying the jwt**: The wrong clientSecret is given in `index.html`. Check the correct clientSecret from App - API Extensions:

  `"clientSecret": "{clientSecret}" //provide clientSecret here`

After testing the Web SDK with the test application and local host server, use the same concept to install and configure the Web SDK in your enterprise application. Reconfigure the file paths and URLs in `index.html` to point to your website and servers, and configure an App for the Web/Mobile Client channel with JWT credentials for your enterprise.

***


Built with [Mintlify](https://mintlify.com).