

# Working with third-party applications in the Amazon Connect Agent Workspace
Working with 3P apps

With Amazon Connect agent workspace, you have the option to use first-party applications, such as Customer Profiles, Cases, Wisdom, and features such as step-by-step guides. With support for third-party applications (3P apps), you can unite your contact center software, built by yourself or by partners in one place. For example, you can integrate your proprietary reservation system or a vendor-provided metrics dashboard, into the Amazon Connect agent workspace.

The following topics describe key concepts and procedures for developing applications for the Amazon Connect agent workspace.

**Topics**
+ [Prerequisites for 3P apps](getting-started-prerequisites.md)
+ [Create your application](getting-started-create-application.md)
+ [Test your application locally](getting-started-testing.md)
+ [Test with a deployed version of your application](getting-started-test-with-deployed-app.md)
+ [Error handling](integrating-with-agent-workspace-error-handling.md)
+ [Troubleshooting](integrating-with-agent-workspace-troubleshooting.md)

# Prerequisites for developing third-party applications for Amazon Connect Agent Workspace
Prerequisites for 3P apps

To develop and test an application for use in Amazon Connect agent workspace, you must have the following:
+ An Amazon Connect instance
+ An IAM user that has the proper permissions for creating an application and associating it with the instance. For more information on the required user permissions, see the [IAM role required for creating applications in Amazon Connect Agent Workspace](appendix-role-required.md)
+ An Amazon Connect user in that instance that has permissions to update security profiles

**Topics**
+ [IAM role required](appendix-role-required.md)

# IAM role required for creating applications in Amazon Connect Agent Workspace
IAM role required

On top of the `AmazonConnect_FullAccess` IAM policy, users need the following IAM permissions for creating an app and associating it with an Amazon Connect instance.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Action": [
                "app-integrations:CreateApplication",
                "app-integrations:GetApplication",
                "iam:GetRolePolicy",
                "iam:PutRolePolicy",
                "iam:DeleteRolePolicy"
            ],
            "Resource": "arn:aws:app-integrations:us-east-1:111122223333:application/*",
            "Effect": "Allow"
        }
    ]
}
```

------

# Create your application for Amazon Connect Agent Workspace
Create your application

An application is a website that can be loaded from an HTTPS URL into an iframe in the Amazon Connect agent workspace. It can be built using any frontend framework and hosted anywhere as long as it can be loaded by the user’s browser and supports being embedded. In addition to being accessible by the user, the application must integrate the [Amazon Connect SDK](https://github.com/amazon-connect/AmazonConnectSDK) to establish secure communication between the application and the agent workspace allowing the application to receive events and data from the workspace.

**Topics**
+ [Install the Amazon Connect SDK](getting-started-install-sdk.md)
+ [Using Connect SDK without package manager](sdk-without-package-manager.md)
+ [Initialize the Amazon Connect SDK in your application](getting-started-initialize-sdk.md)
+ [Events and requests](getting-started-events-and-requests.md)
+ [Application authentication](getting-started-authentication.md)
+ [Integrate with agent data](integrate-with-agent-data.md)
+ [Integrate with contact data](integrate-with-contact-data.md)
+ [Lifecycle events](integrating-with-agent-workspace-lifecycle-events.md)
+ [Apply a theme](integrating-with-agent-workspace-theme.md)

# Install the Amazon Connect SDK for developing applications for Amazon Connect Agent Workspace
Install the Amazon Connect SDK

To develop applications for the Amazon Connect agent workspace you must first install the Amazon Connect SDK. 

The [https://github.com/amazon-connect/AmazonConnectSDK](https://github.com/amazon-connect/AmazonConnectSDK) can be installed from NPM. The Aamzon Connect SDK is made up of a set of modules that can be installed as separate packages, meaning that you should only pull in the packages that you need.

The *app* package provides core application features like logging, error handling, secure messaging, and lifecycle events, and must be installed by all applications at a minimum to integrate into the workspace.

 **Install from NPM** 

Install the app package from NPM by installing ** @amazon-connect/app**.

```
% npm install --save @amazon-connect/app
```

**Note**  
 If you do not use NPM, refer to [Using Amazon Connect SDK without pacakage manager](https://docs.aws.amazon.com/agentworkspace/latest/devguide/sdk-without-package-manager.html) 

# Using the Amazon Connect SDK without a package manager
Using Connect SDK without package manager

This guide is intended for developers building Amazon Connect integrations who do not use npm, webpack, or other JavaScript package managers and bundlers in their web applications. This includes developers building custom StreamsJS-based contact center interfaces or third-party applications that run within the Amazon Connect Agent Workspace.

Amazon Connect recommends using a package manager such as npm and a bundler such as webpack or Vite for SDK integration. These tools provide dependency management, automatic updates, tree-shaking, and a streamlined development workflow. If you choose not to use these tools, this guide describes an alternative approach.

The Amazon Connect SDK is distributed as npm packages. These packages use Node.js-style module resolution and cannot be loaded directly in a browser using a `<script>` tag. If your development environment does not include a package manager or bundler, you must create a prebuilt script file that bundles the SDK packages into a browser-compatible format.

## Your responsibility
Your responsibility

When working without a package manager, it becomes your responsibility to:

1. Set up a one-time build environment to create the bundle

1. Select the specific SDK packages your application requires

1. Build and maintain the bundled script file

1. Update the bundle when SDK versions change

## Why a bundle is required
Why a bundle is required

SDK packages use ES module imports like `import { ContactClient } from "@amazon-connect/contact"`. Browsers cannot resolve these package specifiers directly. A bundler resolves these imports, combines the code, and produces a single file the browser can execute.

## Exposing the SDK as a global
Exposing the SDK as a global

When using `<script>` tags, there is no module system to share code between files. The bundle must attach the SDK to a global variable (such as ` window.AmazonConnectSDK`) so your application scripts can access it. This is different from npm-based projects where you import directly from packages.

## Available packages
Available packages

The SDK consists of multiple packages. Select only the packages your application needs. Examples include:


| Package | Purpose | 
| --- | --- | 
|  @amazon-connect/core  | Core SDK functionality and provider types | 
|  @amazon-connect/contact  | ContactClient for contact operations | 
|  @amazon-connect/email  | EmailClient for email channel operations | 
|  @amazon-connect/app  | App initialization for third-party applications | 
|  @amazon-connect/app-manager  | Plugin for hosting Connect first-party apps (Cases, Step-by-Step Guides) | 
|  @amazon-connect/voice  | VoiceClient for voice channel operations | 

See the [Amazon Connect SDK repository](https://github.com/amazon-connect/AmazonConnectSDK) for the complete list of available packages.

# Building the script file
Building the script file

This section provides step-by-step instructions for creating a browser-consumable bundle from the SDK npm packages.

## Prerequisites
Prerequisites

The following prerequisites are required:
+ Node.js 18 or later installed
+ npm (comes with Node.js)
+ A text editor

## Step 1: Create the build project directory
Step 1: Create directory

Create a new directory to hold your build configuration. This directory will contain npm tooling but the output bundle will be usable without npm.

```
mkdir connect-sdk-bundle
cd connect-sdk-bundle
```

## Step 2: Initialize the npm project
Step 2: Initialize npm

```
npm init -y
```

## Step 3: Install the SDK packages you need
Step 3: Install packages

For an email-based solution using EmailClient and ContactClient:

```
npm install @amazon-connect/core @amazon-connect/contact @amazon-connect/email
```

If you are building a third-party app (not embedded in StreamsJS), also install:

```
npm install @amazon-connect/app
```

If you are integrating with StreamsJS and want to host Connect first-party apps (such as Cases or Step-by-Step Guides), also install:

```
npm install @amazon-connect/app-manager
```

## Step 4: Install the bundler
Step 4: Install bundler

Install esbuild, a fast JavaScript bundler:

```
npm install --save-dev esbuild
```

## Step 5: Create the entry file
Step 5: Create entry file

Create a file that imports the SDK modules you need and exposes them as a global:

```
mkdir src
```

 **For StreamsJS integration** (` src/entry-streams.js`):

```
// Entry file for StreamsJS integration
import { ContactClient } from "@amazon-connect/contact";
import { EmailClient } from "@amazon-connect/email";

// Expose the SDK on the window object
window.AmazonConnectSDK = {
  ContactClient,
  EmailClient,
};
```

 **For StreamsJS with first-party apps** (` src/entry-streams-with-apps.js`):

If you want to host Connect first-party apps like Cases or Step-by-Step Guides alongside the CCP, include the app-manager plugin:

```
// Entry file for StreamsJS integration with 1P app support
import { ContactClient } from "@amazon-connect/contact";
import { EmailClient } from "@amazon-connect/email";
import { AppManagerPlugin } from "@amazon-connect/app-manager";

// Expose the SDK on the window object
window.AmazonConnectSDK = {
  AppManagerPlugin,
  ContactClient,
  EmailClient,
};
```

 **For third-party app** (`src/entry-app.js` ):

```
// Entry file for third-party app integration
import { AmazonConnectApp } from "@amazon-connect/app";
import { ContactClient } from "@amazon-connect/contact";
import { EmailClient } from "@amazon-connect/email";

// Expose the SDK on the window object
window.AmazonConnectSDK = {
  AmazonConnectApp,
  ContactClient,
  EmailClient,
};
```

## Step 6: Add build scripts to package.json
Step 6: Add build scripts

Edit `package.json` to add build scripts:

```
{
  "name": "connect-sdk-bundle",
  "version": "1.0.0",
  "scripts": {
    "build:streams": "esbuild src/entry-streams.js --bundle --minify --sourcemap --format=iife --target=es2020 --outfile=dist/connect-sdk-streams.bundle.js",
    "build:app": "esbuild src/entry-app.js --bundle --minify --sourcemap --format=iife --target=es2020 --outfile=dist/connect-sdk-app.bundle.js",
    "build": "npm run build:streams && npm run build:app"
  }
}
```

## Step 7: Build the bundle
Step 7: Build bundle

```
npm run build
```

This creates the following files in the `dist/` directory:
+ `connect-sdk-streams.bundle.js` - Bundle for StreamsJS integration
+ `connect-sdk-streams.bundle.js.map` - Source map for debugging
+ `connect-sdk-app.bundle.js` - Bundle for third-party apps
+ `connect-sdk-app.bundle.js.map` - Source map for debugging

## Step 8: Copy the bundle to your project
Step 8: Copy bundle

Copy the appropriate `.js` file (and optionally the `.map` file for debugging) to your static website's assets folder:

```
cp dist/connect-sdk-streams.bundle.js /path/to/your/website/assets/vendor/
# or
cp dist/connect-sdk-app.bundle.js /path/to/your/website/assets/vendor/
```

## Complete build project structure
Project structure

After completing all steps, your build project should look like this:

```
connect-sdk-bundle/
├── package.json
├── package-lock.json
├── node_modules/
├── src/
│   ├── entry-streams.js
│   └── entry-app.js
└── dist/
    ├── connect-sdk-streams.bundle.js
    ├── connect-sdk-streams.bundle.js.map
    ├── connect-sdk-app.bundle.js
    └── connect-sdk-app.bundle.js.map
```

# Using the SDK with StreamsJS
Using with StreamsJS

This section explains how to use the prebuilt bundle in a solution that uses Amazon Connect Streams (StreamsJS).

## Prerequisites
Prerequisites

The following prerequisites are required:
+ The Amazon Connect Streams library loaded on your page
+ The `connect-sdk-streams.bundle.js` file from the building section

## HTML setup
HTML setup

```
<!DOCTYPE html>
<html>
  <head>
    <title>Connect StreamsJS with SDK</title>
  </head>
  <body>
    <div id="ccp-container" style="width: 400px; height: 600px;"></div>

    <!-- Load Amazon Connect Streams first -->
    <script src="https://your-domain.com/amazon-connect-streams.min.js"></script>

    <!-- Load the SDK bundle -->
    <script src="/assets/vendor/connect-sdk-streams.bundle.js"></script>

    <!-- Your application code -->
    <script src="/app.js"></script>
  </body>
</html>
```

## JavaScript implementation
JavaScript implementation

In your `app.js` file:

```
// Initialize the CCP
var ccpContainer = document.getElementById("ccp-container");

connect.core.initCCP(ccpContainer, {
  ccpUrl: "https://your-instance.my.connect.aws/ccp-v2/",
  loginPopup: true,
  loginPopupAutoClose: true,
});

// Get the SDK provider from Streams after CCP initializes
connect.core.onInitialized(function () {
  // Retrieve the provider from the Streams SDK client config
  var sdkConfig = connect.core.getSDKClientConfig();
  var provider = sdkConfig.provider;

  // Create the SDK clients using the provider
  var contactClient = new AmazonConnectSDK.ContactClient(provider);
  var emailClient = new AmazonConnectSDK.EmailClient(provider);

  // Example: Subscribe to contact lifecycle events
  contactClient.onIncoming(function (event) {
    console.log("Incoming contact:", event.contactId);
  });

  contactClient.onConnected(function (event) {
    console.log("Contact connected:", event.contactId);
  });

  contactClient.onCleared(function (event) {
    console.log("Contact cleared:", event.contactId);
  });
});
```

## Hosting Connect first-party apps (optional)
Hosting first-party apps

If you want to host Connect first-party apps like Cases or Step-by-Step Guides alongside your CCP, include the `@amazon-connect/app-manager` package in your bundle and apply the plugin during CCP initialization:

```
connect.core.initCCP(ccpContainer, {
  ccpUrl: "https://your-instance.my.connect.aws/ccp-v2/",
  loginPopup: true,
  loginPopupAutoClose: true,
  // Apply the plugin to enable 1P app hosting
  plugins: AmazonConnectSDK.AppManagerPlugin,
});
```

## Key points for StreamsJS integration
Key points

1. Load the Streams library before the SDK bundle

1. Retrieve the provider using ` connect.core.getSDKClientConfig().provider` after CCP initializes

1. Instantiate SDK clients with `new AmazonConnectSDK.ContactClient(provider)`

1. The `AppManagerPlugin` is only required if hosting Connect first-party apps

# Using the SDK in a 3P app
Using in 3P app

This section explains how to use the prebuilt bundle in a third-party application that runs within the Amazon Connect Agent Workspace.

## Prerequisites
Prerequisites

The following prerequisites are required:
+ Your application is registered as a third-party app in Amazon Connect
+ The `connect-sdk-app.bundle.js` file from the building section

## HTML setup
HTML setup

```
<!DOCTYPE html>
<html>
  <head>
    <title>Connect Third-Party App</title>
  </head>
  <body>
    <div id="app-container"></div>

    <!-- Load the SDK bundle -->
    <script src="/assets/vendor/connect-sdk-app.bundle.js"></script>

    <!-- Your application code -->
    <script src="/app.js"></script>
  </body>
</html>
```

## JavaScript implementation
JavaScript implementation

In your `app.js` file:

```
// Initialize the third-party app - this must be called first
var initResult = AmazonConnectSDK.AmazonConnectApp.init({
  // Optional lifecycle callbacks
  onCreate: function (event) {
    console.log("App created");
  },
  onDestroy: function (event) {
    console.log("App destroyed");
  },
});

// Get the provider from the init result
var provider = initResult.provider;

// Create the SDK clients using the provider
var contactClient = new AmazonConnectSDK.ContactClient(provider);
var emailClient = new AmazonConnectSDK.EmailClient(provider);

// Example: Subscribe to contact lifecycle events
contactClient.onIncoming(function (event) {
  console.log("Incoming contact:", event.contactId);
});

contactClient.onConnected(function (event) {
  console.log("Contact connected:", event.contactId);
});

contactClient.onCleared(function (event) {
  console.log("Contact cleared:", event.contactId);
});
```

## Key points for third-party apps
Key points

1. Call `AmazonConnectSDK.AmazonConnectApp.init()` before using any SDK functionality

1. The `init()` function returns an object containing the ` provider`

1. Instantiate SDK clients with `new AmazonConnectSDK.ContactClient(provider)`

1. Lifecycle callbacks (`onCreate`, `onDestroy`) are optional but useful for managing app state

# Updating the bundle
Updating the bundle

When a new version of the SDK is released:

1. Navigate to your build project directory

1. Update the SDK packages:

   ```
   npm update @amazon-connect/core @amazon-connect/contact @amazon-connect/email
   ```

1. Rebuild the bundle:

   ```
   npm run build
   ```

1. Copy the new bundle to your website

1. Test your application to verify compatibility

# Troubleshooting
Troubleshooting

This section describes common issues and resolutions when using the SDK without a package manager.

## Bundle is too large
Bundle is too large

If the bundle size is a concern, ensure you only import the packages you need. Each additional package increases bundle size.

## "AmazonConnectSDK is not defined" error
SDK not defined error

Verify that the bundle script tag appears before your application script in the HTML, and that the path to the bundle file is correct.

## Provider is undefined
Provider is undefined

 **For StreamsJS:** Ensure you are accessing the provider after `connect.core.onInitialized()` fires.

 **For third-party apps:** Ensure you call ` AmazonConnectSDK.AmazonConnectApp.init()` and capture its return value.

## SDK methods not working
SDK methods not working

Verify you passed the provider when creating the clients. The provider establishes the communication channel between your code and Amazon Connect.

# Initialize the Amazon Connect SDK in your application for Amazon Connect Agent Workspace
Initialize the Amazon Connect SDK in your application

Initializing the [Amazon Connect SDK](https://github.com/amazon-connect/AmazonConnectSDK) in your app for the Amazon Connect agent workspace requires calling `init` on the AmazonConnectApp module. This takes an `onCreate` and `onDestroy` callback, which will be invoked once the app has successfully initialized in the agent workspace and then when the agent workspace is going to destroy the iframe the app is running in. These are two of the lifecycle events that your app can integrate with. See [Application lifecycle events in Amazon Connect Agent Workspace](integrating-with-agent-workspace-lifecycle-events.md) for details on the other app lifecycle events that your app can hook into.

```
import { AmazonConnectApp } from "@amazon-connect/app";

const { provider } = AmazonConnectApp.init({
  onCreate: (event) => {
    const { appInstanceId } = event.context;
    console.log('App initialized: ', appInstanceId);
  },
  onDestroy: (event) => {
    console.log('App being destroyed');
  },
});
```

**Note**  
Keep the reference to `{ provider }` which is required to create clients to interact with events and requests. 

Doing a quick test locally by loading your app directly will produce an error message in the browser dev tools console that the app was unable to establish a connection to the workspace. This will happen when your app is correctly calling ` init` when run outside of the workspace.

```
> App failed to connect to agent workspace in the allotted time   
```

# Events and requests in Amazon Connect Agent Workspace
Events and requests

App developers can easily create applications that seamlessly integrate into the agent workspace experience in the Amazon Connect agent workspace with the event and request functionality natively supported by [Amazon Connect SDK](https://github.com/amazon-connect/AmazonConnectSDK). You can build an app by leveraging the [Amazon Connect SDK](https://github.com/amazon-connect/AmazonConnectSDK) to subscribe to agent/contact events (invoking a particular handler when the event occurs) and make requests to quickly retrieve agent/contact data.

This is the main module needed to integrate your app into the agent workspace and get exposure to its agent/contact data and make your app responsive throughout the contact-handling lifecycle.
+  **Event** 

  Refers to an asynchronous subscription-publication model, where the [Amazon Connect SDK's](https://github.com/amazon-connect/AmazonConnectSDK) client allows the 3P app to subscribe a callback to-be-invoked when a specific event occurs, such as an agent changing their state from * Available* to *Offline*. It then performs an application-defined action using the event context when said event fires. If and when an event fires is dependent on the event type. For more information, see the [API Reference](api-reference-3P-apps-events-and-requests.md).
+  **Request** 

  Refers to a request-reply model, where the [Amazon Connect SDK's](https://github.com/amazon-connect/AmazonConnectSDK) client allows the 3P app to make requests on demand to retrieve data about the current contact or the logged-in agent.

 **Install from NPM** 

Install the contact package from NPM by installing ** @amazon-connect/contact**.

```
% npm install --save @amazon-connect/contact  
```

# Authentication for applications in Amazon Connect Agent Workspace
Application authentication

Apps in the Amazon Connect agent workspace must provide their own authentication to their users. It is recommended that apps use the same identity provider that the Amazon Connect instance has been configured to use when it was created. This will make it so users only need to log in once for both the agent workspace and their applications, since they both use the same single sign on provider.

**Note**  
On Jul 22, 2024, Google announced that they no longer plan to deprecate third-party cookies **[1]**. With this announcement, there will be no impact to third-party applications embedded within Amazon Connect’s agent workspace, unless third-party application users explicitly opt-in for deprecation. We advise third-party application developers to adopt the third-party cookie deprecation impact prevention solutions below as a forward-looking preventative measure.  
If you have any questions or concerns, please contact AWS Support **[2]**.  
 **[1] ** [ https://privacysandbox.com/news/privacy-sandbox-update/](https://privacysandbox.com/news/privacy-sandbox-update/)   
 **[2] ** [https://aws.amazon.com/support](https://aws.amazon.com/support)   
For more information, see the [3P admin guide](https://docs.aws.amazon.com/connect/latest/adminguide/3P-apps-agent-workspace.html).  
 **Third-party cookie deprecation**   
We are aware of the **Google Chrome** Third-Party Cookies Deprecation (3PCD) that may impact the third-party applications experience. If your application is embedded within the Amazon Connect’s agent workspace in an iframe and uses cookie based Authentication/Authorization, then your application is likely to be impacted by Third-Party Cookie Deprecation. You can test if your user experience will be impacted by 3PCD by using the following [Test for Breakage](https://developers.google.com/privacy-sandbox/3Pcd/prepare/test-for-breakage) guidance.  
Here are the recommendations to ensure customers continue to have good experiences when accessing your application within the Amazon Connect agent workspace with Google Chrome.  
**Temporary solution**: Allow 3P cookie access [here](https://support.google.com/chrome/a/answer/14439269?hl=en) .
**Permanent solution**: Refer to the [guidance](https://developers.google.com/privacy-sandbox/3Pcd) from Chrome to choose the best option suitable for your application.

# Integrate application with Amazon Connect Agent Workspace agent data
Integrate with agent data

To integrate your application with agent data from the Amazon Connect agent workspace, instantiate the agent client as follows:

```
import { AgentClient } from "@amazon-connect/contact";

const agentClient = new AgentClient({ provider });
```

**Note**  
You must first instantiate the [ AmazonConnectApp](getting-started-initialize-sdk.md) which initializes the default AmazonConnectProvider and returns ` { provider } `. This is the recommended option.

Alternatively, see the [API reference](api-reference-3P-apps-agent-client.md) to customize your client’s configuration.

Once the agent client is instantiated, you can use it to subscribe to events and make requests.

## Example agent event


The code sample below subscribes a callback to the state change event topic. Whenever the agent’s state is modified, the agent workspace will invoke your provided callback, passing in the event data payload for your function to operate on. In this example, it logs the event data to the console.

```
import { AgentStateChanged } from "@amazon-connect/contact";

// A simple callback that just console logs the state change event data 
// returned by the agent workspace whenever the logged-in agent's state changes
const handler = async (data: AgentStateChanged) => {
    console.log(data);
};

// Subscribe to the state change topic using the above handler
agentClient.onStateChanged(handler);
```

## Example agent request


The following code sample submits a `getARN` request and then logs the returned data to the console.

```
const arn = await agentClient.getARN();

console.log(`Got the arn value: ${arn}`);
```

The above agent event and request are non-exhaustive. For a full list of available agent events and requests, see the [API Reference](api-reference-3P-apps-events-and-requests.md).

# Integrate application with Amazon Connect Agent Workspace contact data
Integrate with contact data

To integrate your application with contact data from the Amazon Connect agent workspace, instantiate the contact client as follows:

```
import { ContactClient } from "@amazon-connect/contact";

const contactClient = new ContactClient({ provider });
```

**Note**  
You must first instantiate the [ AmazonConnectApp](getting-started-initialize-sdk.md) which initializes the default AmazonConnectProvider and returns ` { provider } `. This is the recommended option.

Alternatively, see the [API reference](api-reference-3P-apps-contact-client.md) to customize your client’s configuration.

Once the contact client is instantiated, you can use it to subscribe to events and make requests.

## Contact scope


All ContactClient methods include an optional `contactId` parameter. If no value is provided, the client automatically defaults to the contact context from which the app was launched. Note that this requires the app to be opened within a contact's context.
+  **Applications configured with Per Contact scope** 

  For Per Contact scoped applications, the `contactId` of the current contact is provided in the `AppCreateEvent` which is supplied in the `onCreate` callback. 

  ```
  const provider =  AmazonConnectApp.init({
  
      onCreate: async (event: AppCreateEvent) => {
          // Check if scope is defined and has contactId before accessing it
          if (event.context.scope && "contactId" in event.context.scope) {
              let contactId = event.context.scope.contactId;
              console.log("App launched for the contactId", contactId);
          }
      },
  
      onDestroy: async (event: AppDestroyEvent) => {
          console.log("App destroyed:", event);
      },
  
  });
  ```
+  **Applications configured with Cross Contact scope** 

  Cross Contact scoped applications can retrieve the `contactId` by subscribing to any of the contact events like `onConnected` or `onIncomming` 

  ```
  const handler: ContactIncomingHandler = async (data: ContactIncoming) => {
      console.log("Contact incoming occurred! " + data);
      let contactId = data.contactId;
  };
  
  contactClient.onIncoming(handler);
  ```

## Example contact event


The following code sample subscribes a callback to the connected event topic. Whenever a contact is connected to the agent, the agent workspace will invoke your provided callback, passing in the event data payload for your function to operate on. In this example, it logs the event data to the console.

```
import { 
    ContactClient,
    ContactConnected, 
    ContactConnectedHandler
} from "@amazon-connect/contact";

// A simple callback that just console logs the contact connected event data 
// returned by the workspace whenever the current contact is connected
const handler: ContactConnectedHandler = async (data: ContactConnected) => {
    console.log(data);
};

// Subscribe to the contact connected topic using the above handler
contactClient.onConnected(handler, contactId);
```

## Example contact request


The following code sample submits a `getQueue` request and then logs the returned data to the console.

```
import { ContactClient } from "@amazon-connect/contact";

const queue = await contact.getQueue(contactId);

console.log(`Got the queue: ${queue}`);
```

The above contact event and request are non-exhaustive. For a full list of available contact events and requests, see the [API Reference](api-reference-3P-apps-events-and-requests.md).

# Application lifecycle events in Amazon Connect Agent Workspace
Lifecycle events

There are lifecycle states that an app can move between from when the app is initially opened to when it is closed in the Amazon Connect agent workspace. This includes the initialization handshake that the app goes through with the agent workspace after it has loaded to establish the communication channel between the two. There is another handshake between the agent workspace and the application when the app will be shutdown. An application can hook into `onCreate` and ` onDestroy` when calling `AmazonConnectApp.init()`.

The following section describe the create and destroy events in the Amazon Connect agent workspace.

**Topics**
+ [Create event](integrating-with-agent-workspace-lifecycle-events-create.md)
+ [Destroy event](integrating-with-agent-workspace-lifecycle-events-destroy.md)

# The create event in Amazon Connect Agent Workspace
Create event

The create event in the Amazon Connect agent workspace results in the ` onCreate` handler passed into the `AmazonConnectApp.init()` to be invoked. ` Init` should be called in an application once it has successfully loaded and is ready to start handling events from the workspace. The create event provides the *appInstanceId* and the * appConfig* .
+ **appInstanceId**: The ID for this instance of the app provided by the workspace.
+ **appConfig**: The application configuration being used by the instance for this app.
+ **contactScope**: Provides the current ` contactId` if the app is opened during an active contact.

# The destroy event in Amazon Connect Agent Workspace
Destroy event

The destroy event in the Amazon Connect agent workspace will trigger the ` onDestroy` callback configured during `AmazonConnectApp.init()`. The application should use this event to clean up resources and persist data. The agent workspace will wait for the application to respond that it has completed clean up for a period of time.

# Apply a theme to your application in Amazon Connect Agent Workspace
Apply a theme

The theme package defines and applies the Amazon Connect theme when developing with [Cloudscape](https://cloudscape.design) for the Amazon Connect agent workspace.

 **Install from NPM** 

Install the theme package and Cloudscape global-styles from NPM by installing ** @amazon-connect/theme** and ** @cloudscape-design/global-styles**.

```
% npm install -P @amazon-connect/theme  
% npm install -P @cloudscape-design/global-styles
```

 **Usage** 

The theme package must be imported once at the entry point of the application. 

```
import { applyConnectTheme } from "@amazon-connect/theme"; 

await applyConnectTheme(provider);
```

**Note**  
You must first instantiate the [ AmazonConnectApp](getting-started-initialize-sdk.md) which initializes the default AmazonConnectProvider and returns ` { provider } `. 

From then on Cloudscape components and design tokens can be used directly from Cloudscape.

```
// src/app.ts

import * as React from "react";
import Button from "@cloudscape-design/components/button";

export default () => {
  return <Button variant="primary">Button</Button>;
}
```

# Test your application for Amazon Connect Agent Workspace locally
Test your application locally

Once you have a minimal version of the app that you want to use in the Amazon Connect agent workspace with the Amazon Connect SDK that you want to test in the agent workspace, run your app locally and create an application in the AWS console with an * AccessUrl* using the localhost endpoint, like `http://localhost:3000` .

## Creating an application and associating to your instance


**Note**  
Detailed steps for creating and managing applications can be found in the admin guide under [Third-party applications (3P apps) in the agent workspace (Preview)](https://docs.aws.amazon.com/connect/latest/adminguide/3P-apps.html).

1. Open the Amazon Connect [console](https://console.aws.amazon.com/connect/) (https://console.aws.amazon.com/connect/).

1. Navigate to **Third-party applications** in the left hand panel.

1. Choose **Add application**.

1. Fill out the necessary required information:

   1. **Name**: The name of the application is what will show up to agents in the app launcher in the agent workspace.

   1. **Namespace**: Namespace must be unique per application and, in the future, allow for applications to support custom events. Once an app is created, its namespace cannot be updated.

   1. **AccessUrl**: Set to the localhost url for your application.

   1. **Permissions**: A list of allowed functions that grants your application the ability to subscribe to agent/contact events that occur in the agent workspace or make requests for agent/contact data.

1. Select the Amazon Connect instance you are testing with to associate the app with that instance.

1. Choose **Add application** to finish creating your app.

1. Log into your test instance as an admin user.

1. Navigate to **Security profiles** and select the ` Admin` security profile.

1. Under **Agent applications** find your application and make sure the `View` permission is selected.

   1. Open the agent application `/agent-app-v2`

1. Open your app by choosing the app launcher and selecting your application. Your app will be opened in a new application tab.

After following these steps you will have your app loaded from your local machine into the workspace. This will only work when loading the agent workspace on your local machine that has the app running on it. If you want to be able to load your app from any browser / computer, then you must deploy your app somewhere that is internet accessible.

Assuming the logging was included from the code snippet above, you should see the following in the console log of your browser’s dev tools when you open your app in the workspace.

```
App initialized:  00420d405e    
```

When your app is closed, for example, by closing the tab in the agent workspace, you should see the following series of logs entries.

```
> App destroyed: begin
> App being destroyed
> App destroyed
> App destroyed: end
```

If you see these, then your app correctly integrates with the *Amazon Connect Amazon Connect SDK* and the [The create event in Amazon Connect Agent Workspace](integrating-with-agent-workspace-lifecycle-events-create.md) / [The destroy event in Amazon Connect Agent Workspace](integrating-with-agent-workspace-lifecycle-events-destroy.md)destroy lifecycle events.

# Test a deployed version of your application for Amazon Connect Agent Workspace
Test with a deployed version of your application

When ready, deploy the app that you created for the Amazon Connect agent workspace to a place that is internet accessible. Update your application configuration (or configure a new application) to point to the deployed version of your application. A simple way to deploy your app assuming it only has static assets is to [host them on S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/WebsiteHosting.html) and (optionally) [use CloudFront](https://aws.amazon.com/blogs/networking-and-content-delivery/amazon-s3-amazon-cloudfront-a-match-made-in-the-cloud/).

# Handle application errors in Amazon Connect Agent Workspace
Error handling

Applications can communicate errors back to the Amazon Connect agent workspace by either calling ` sendError` or `sendFatalError` on the `AmazonConnectApp` object. The agent workspace will shutdown an app if it sends a fatal error meaning that the app has reached an unrecoverable state and isn’t functional. When an app sends a fatal error the agent workspace won’t attempt to go through the destroy lifecycle handshake and will immediately remove the iframe from the DOM. Apps should do any clean up required prior to sending fatal errors.

# Troubleshoot application setup in Amazon Connect Agent Workspace
Troubleshooting

You can use the [Amazon Connect SDK's](https://github.com/amazon-connect/AmazonConnectSDK) ` AppConfig` object to retrieve data about your applications’s setup in the Amazon Connect agent workspace, including its permissions. This will allow you to inspect its state and determine which permissions were assigned to your app. Accessing its ` permissions` property will return a list of strings, each representing a permissions that grants access to a set of events and requests. Performing an action, whether subscribing to an event or making a request, will fail if your app does not have the corresponding permission that grants the action. You may have to ask your account admin to assign the permissions required for your app to function. To review the full list of permissions assignable to apps, please see the admin guide.

## Events


If your app uses the [Amazon Connect SDK](https://github.com/amazon-connect/AmazonConnectSDK) to subscribe to an event that it does not have permission for, the agent workspace will throw an error with a message formatted like below.

```
App attempted to subscribe to topic without permission - Topic {"key":
<event_name>,"namespace":"aws.connect.contact"}`
```

## Requests


If your app uses the [Amazon Connect SDK](https://github.com/amazon-connect/AmazonConnectSDK) to make a request that it does not have permission for, the agent workspace will throw an error with a message formatted like below.

```
App does not have permission for this request             
```