This guide will walk through how to use a personal chat backend and Amazon Connect public APIs to build a chat application, using the v3 JavaScript AWS SDK.
🚨 We recommend using ChatJS, a JavaScript library with light wrapper around the AWS-SDK. This has built in logic to handle WebSocket connections and retry logic. Please refer to "Building a Chat application for Amazon Connect with ChatJS "
- Initiate a chat: make request to your personal chat backend, which calls the StartChatContact SigV4 API
- Connect to a chat session: make a CreateParticipantConnection request with AWS SDK
- Subscribe to websocket: use the ConnectionToken and WebSocket URL provided
- Send chat events: make requests to Amazon Connect Participant Service APIs with AWS SDK
-
Create an Amazon Connect Instance [guide]
-
Create an Amazon Connect Contact Flow, ready to receive chat contacts. [guide]
-
Deploy a custom Amazon Connect Chat backend. [sample CloudFormation stack]
Install the v3 JavaScript AWS SDK library. This allows full customization, but requires your own logic to handle WebSocket connections.
$ npm install @aws-sdk/client-connectparticipant@^3
// AWS SDK v3 (JavaScript) example
import { ConnectParticipantClient, CreateParticipantConnectionCommand } from "@aws-sdk/client-connectparticipant"; // v3.x.x
// Create a ConnectParticipantClient instance
const client = new ConnectParticipantClient({ region: REGION });
Since StartChatContact is a SigV4 API, your application will first make a call to your personal chat backend. If you deploy the sample startChatContactAPI CloudFormation stack, make a request to the API Gateway endpoint. This will return the ParticipantToken used for the rest of the chat session.
// Your chat application
// Example code making request to personal chat backend
const ENDPOINT_URL = "<url-to-personal-chat-backend>";
const startChatRequestBody = {
ContactFlowId: "<REPLACE_ME>",
InstanceId: "<REPLACE_ME>",
ParticipantDetails: {
DisplayName: "John Doe"
}
};
fetch(ENDPOINT_URL, {
"POST",
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(startChatRequestBody),
})
.then(response => response.json())
.then(data => {
console.log('Lambda response:', data); // { "ContactId": "string", "ContinuedFromContactId": "string", "ParticipantId": "string", "ParticipantToken": "string" }
})
.catch(error => {
console.error('API error:', error);
});
Your personal chat backend can use the AWS SDK to make the StartChatContact request, and return the response to your chat application. Here is an example lambda function for this use case:
// AWS SDK v3 (JavaScript) example
// Lambda code to make StartChatContact request
const { ConnectClient, StartChatContactCommand } = require("@aws-sdk/client-connect");
const client = new ConnectClient({ region: process.env.REGION });
exports.handler = (event, context, callback) => {
const body = JSON.parse(event["body"]);
const startChatRequest = {
"InstanceId": body["InstanceId"],
"ContactFlowId": body["ContactFlowId"],
"ParticipantDetails": {
"DisplayName": body["ParticipantDetails"]["DisplayName"]
},
};
const command = new StartChatContactCommand(startChatRequest);
try {
const response = await client.send(command);
console.log("Start chat succeeded with the response: " + JSON.stringify(response.data));
callback({ 200, body: JSON.stringify(response.data) }) // `{ "`[ContactId](https://docs.aws.amazon.com/connect/latest/APIReference/API_StartChatContact.html#connect-StartChatContact-response-ContactId)`": "`***string***`", "`[ContinuedFromContactId](https://docs.aws.amazon.com/connect/latest/APIReference/API_StartChatContact.html#connect-StartChatContact-response-ContinuedFromContactId)`": "`***string***`", "`[ParticipantId](https://docs.aws.amazon.com/connect/latest/APIReference/API_StartChatContact.html#connect-StartChatContact-response-ParticipantId)`": "`***string***`", "`[ParticipantToken](https://docs.aws.amazon.com/connect/latest/APIReference/API_StartChatContact.html#connect-StartChatContact-response-ParticipantToken)`": "`***string***`" }`
} catch (error) {
console.error("Error starting chat contact:", error);
}
};
// AWS SDK v2 (JavaScript) example
// Lambda code to make StartChatContact request
var AWS = require('aws-sdk');
AWS.config.update({region: process.env.REGION});
var client = new AWS.Connect();
exports.handler = (event, context, callback) => {
const body = JSON.parse(event["body"]);
const startChatRequest = {
"InstanceId": body["ContactFlowId"],
"ContactFlowId": body["InstanceId"],
"ParticipantDetails": {
"DisplayName": body["ParticipantDetails"]["DisplayName"]
},
};
client.startChatContact(startChatRequest, function(err, data) {
if (err) {
console.log("Error starting the chat.", err);
} else {
console.log("Start chat succeeded with the response: " + JSON.stringify(data));
callback(null, { 200, body: JSON.stringify(data) });
}
});
};
Connect to the ongoing chat session using the CreateParticipantConnection public API, and pass in the values of the StartChatContact response. This returns ConnectionToken and WebSocket URL
// AWS SDK v3 (JavaScript) example
import { ConnectParticipantClient, CreateParticipantConnectionCommand } from "@aws-sdk/client-connectparticipant";// v3.x.x
const client = new ConnectParticipantClient(config);
const input = { // CreateParticipantConnectionRequest
Type: [ // ConnectionTypeList
"WEBSOCKET" || "CONNECTION_CREDENTIALS",
],
ParticipantToken: "STRING_VALUE", // required
ConnectParticipant: true || false,
};
const command = new CreateParticipantConnectionCommand(input);
const response = await client.send(command);
// { // CreateParticipantConnectionResponse
// Websocket: { // Websocket
// Url: "STRING_VALUE",
// ConnectionExpiry: "STRING_VALUE",
// },
// ConnectionCredentials: { // ConnectionCredentials
// ConnectionToken: "STRING_VALUE",
// Expiry: "STRING_VALUE",
// },
// };
// TODO - add logic for websocket connection
Make calls to the Amazon Connect Participant Service APIs for the ongoing chat, using the ConnectionToken.
Send a message using the SendMessage API
// AWS SDK v3 (JavaScript) example
import { ConnectParticipantClient, SendMessageCommand } from "@aws-sdk/client-connectparticipant"; //v3.x.x
const client = new ConnectParticipantClient(config);
const input = { // SendMessageRequest
ContentType: "text/plain", // Documentation: https://docs.aws.amazon.com/connect-participant/latest/APIReference/API_SendMessage.html#connectparticipant-SendMessage-request-ContentType
Content: "Hello World!", // required
ClientToken: "STRING_VALUE",
ConnectionToken: "STRING_VALUE", // required
};
const command = new SendMessageCommand(input);
const response = await client.send(command);
// { // SendMessageResponse
// Id: "STRING_VALUE",
// AbsoluteTime: "STRING_VALUE",
// };
Send more chat events using the SendEvent API
// AWS SDK v3 (JavaScript) example
import { ConnectParticipantClient, SendEventCommand } from "@aws-sdk/client-connectparticipant"; //v3.x.x
const client = new ConnectParticipantClient(config);
const input = { // SendEventRequest
ContentType: "STRING_VALUE", // required - Documentation: https://docs.aws.amazon.com/connect-participant/latest/APIReference/API_SendEvent.html#connectparticipant-SendEvent-request-ContentType
Content: "STRING_VALUE",
ClientToken: "STRING_VALUE",
ConnectionToken: "STRING_VALUE", // required
};
const command = new SendEventCommand(input);
const response = await client.send(command);
// { // SendEventResponse
// Id: "STRING_VALUE",
// AbsoluteTime: "STRING_VALUE",
// };
Fetch the chat transcript using the GetTranscript API (uses ConnectionToken)
// AWS SDK v3 (JavaScript) example
import { ConnectParticipantClient, GetTranscriptCommand } from "@aws-sdk/client-connectparticipant"; // ES Modules import
const client = new ConnectParticipantClient(config);
const input = { // GetTranscriptRequest
ContactId: "STRING_VALUE",
MaxResults: Number("int"),
NextToken: "STRING_VALUE",
ScanDirection: "FORWARD" || "BACKWARD",
SortOrder: "DESCENDING" || "ASCENDING",
StartPosition: { // StartPosition
Id: "STRING_VALUE",
AbsoluteTime: "STRING_VALUE",
MostRecent: Number("int"),
},
ConnectionToken: "STRING_VALUE", // required
};
const command = new GetTranscriptCommand(input);
const response = await client.send(command);
// { // GetTranscriptResponse
// InitialContactId: "STRING_VALUE",
// Transcript: [ // Transcript
// { // Item
// AbsoluteTime: "STRING_VALUE",
// Content: "STRING_VALUE",
// ContentType: "STRING_VALUE",
// Id: "STRING_VALUE",
// Type: "TYPING" || "PARTICIPANT_JOINED" || "PARTICIPANT_LEFT" || "CHAT_ENDED" || "TRANSFER_SUCCEEDED" || "TRANSFER_FAILED" || "MESSAGE" || "EVENT" || "ATTACHMENT" || "CONNECTION_ACK" || "MESSAGE_DELIVERED" || "MESSAGE_READ",
// ParticipantId: "STRING_VALUE",
// DisplayName: "STRING_VALUE",
// ParticipantRole: "AGENT" || "CUSTOMER" || "SYSTEM" || "CUSTOM_BOT",
// Attachments: [ // Attachments
// { // AttachmentItem
// ContentType: "STRING_VALUE",
// AttachmentId: "STRING_VALUE",
// AttachmentName: "STRING_VALUE",
// Status: "APPROVED" || "REJECTED" || "IN_PROGRESS",
// },
// ],
// MessageMetadata: { // MessageMetadata
// MessageId: "STRING_VALUE",
// Receipts: [ // Receipts
// { // Receipt
// DeliveredTimestamp: "STRING_VALUE",
// ReadTimestamp: "STRING_VALUE",
// RecipientParticipantId: "STRING_VALUE",
// },
// ],
// },
// RelatedContactId: "STRING_VALUE",
// ContactId: "STRING_VALUE",
// },
// ],
// NextToken: "STRING_VALUE",
// };
End the ongoing chat session with the DisconnectParticipant API
// AWS SDK v3 (JavaScript) example
import { ConnectParticipantClient, DisconnectParticipantCommand } from "@aws-sdk/client-connectparticipant"; //v3.x.x
const client = new ConnectParticipantClient(config);
const input = { // DisconnectParticipantRequest
ClientToken: "STRING_VALUE",
ConnectionToken: "STRING_VALUE", // required
};
const command = new DisconnectParticipantCommand(input);
const response = await client.send(command);
// {};