twilio-flex-webchat-widget
v0.0.8
Published
_Twilio Flex Webchat Widget_ is a package that provides a website chat widget built for Flex Conversations. It uses Twilio's Conversations JS SDK, Twilio Paste Design library and the Flex WebChats endpoint.
Downloads
24
Readme
Twilio Flex Webchat Widget
Twilio Flex Webchat Widget is a package that provides a website chat widget built for Flex Conversations. It uses Twilio's Conversations JS SDK, Twilio Paste Design library and the Flex WebChats endpoint.
It can be included into a React-base web application. A sample application that demonstrates such usage can be found at Twilio Flex Webchat Sample.
Getting Started
Install
Install the package with the following command
npm i twilio-flex-webchat-widget --save
Configuration
If you want to run the Cypress-based UI tests, copy cypress.env.sample.json
to cypress.env.json
in the root folder and populate values for the evironment variables.
Usage
Features
Core Messaging Features
Twilio Webchat React App is built entirely with Twilio Conversations SDK and provides UI for most of its features:
- Typing indicator
- Read receipt
- Attachments
- Unread messages
This app also makes use of the v2 WebChats endpoint which creates a Conversation, an anonymous user, and configures the conversation as per the Address Sid.
Ability to Resume Sessions
Twilio Webchat React App will persist user session, if the user closes and reopens the tab. The customer will achieve it by potentially storing the JWT token in their user's local storage. This JWT token will expire after an amount of time.
Connectivity Notification
Twilio Webchat React App monitors user internet connectivity and will inform them with a notification if their connection has been lost. Once the connection has been re-established, the user again will be informed and the list of messages will be updated with any missed messages during the connectivity loss.
This feature is built using Conversations SDK ConnectionState events and Twilio Paste alert component.
See how to re-use Paste alert component to build custom notifications in our How to guides.
Pre-engagement Form
Twilio Webchat React App comes out-of-the-box with a pre-engagement form. The data gathered on submission will be passed by default to the initWebchat
endpoint of your server.
More info here.
Chat Transcripts
Twilio Webchat React App can provide customers with chat transcripts, if enabled. Chat transcripts can be provided to a customer through a direct download or email, at the end of a chat session. All files attached within the chat will be also be provided if a transcript is requested. This feature is disabled by default, but can be enabled by following the steps below.
Downloading Transcripts
Customers can download chat transcripts as a plain text file. If attachments are present within the chat conversation, a zip file containing the plain text transcript file and the attached files will be downloaded.
Setup
Allowing customers to download transcripts requires no additional setup beyond adding the below entry to the .env
file.
DOWNLOAD_TRANSCRIPT_ENABLED=true
Emailing Transcripts
Customers can email chat transcripts to the email address provided in the pre-engagement form. The transcript will be provided within the body of the email and any associated files will be added as attachments to the email. Emails will be sent using the SendGrid API.
Setup
- Add the following entry to the
.env
file.EMAIL_TRANSCRIPT_ENABLED=true
- Create a SendGrid account with a verified domain or email. This will be used to send the email transcripts to customers.
- Add the SendGrid API key and verified email to the
.env
file as the values forSENDGRID_API_KEY
andFROM_EMAIL
respectively.
The email subject and content can be customised in the configuration object, as described here.
Customisation
The email subject and HTML email content can be customised using the configuration object, as described here.
Project Structure
Twilio Webchat React App is an open source repository that includes:
- A React App
- A local backend server
1. React App
The React app is a newer version of the legacy webchat widget. With this new app, you can clone and customize it to meet your needs.
This App is built in React using Typescript, Twilio Paste and Twilio Conversations SDK.
You can find the source files in the src
folder.
After being initialized, the widget renders a button in the bottom right part of the page that, once clicked, will show a customisable form for your customers to compile.
Once submitted, the App will hit the initWebchat
endpoint of your server with the form data and get back a token with a conversationSid.
At that point, your customer will be able to send messages to your agents.
Configuration
This React app is open-sourced, so you can freely customise every aspect of it to suit your needs. However, to speed up some aspects of the customisations, we are exposing a configuration object on the init function.
Here's an example of how to use this config object in your index.html
template.
window.addEventListener("DOMContentLoaded", () => {
Twilio.initWebchat({
serverUrl: "%YOUR_SERVER_URL%",
theme: {
isLight: true,
overrides: {
backgroundColors: {
colorBackgroundBody: "#faebd7"
// .. other Paste tokens
}
}
},
fileAttachment: {
enabled: true,
maxFileSize: 16777216, // 16 MB
acceptedExtensions: ["jpg", "jpeg", "png", "amr", "mp3", "mp4", "pdf"]
},
transcript: {
emailSubject: (agentNames) => {
let subject = "Transcript of your chat";
if (agentNames.length > 0) {
subject = subject.concat(` with ${agentNames[0]}`);
agentNames.slice(1).forEach((name) => (subject = subject.concat(` and ${name}`)));
}
return subject;
},
emailContent: (customerName, transcript) => {
return `<div><h1 style="text-align:center;">Chat Transcript</h1><p>Hello ${customerName},<br><br>Please see below your transcript, with any associated files attached, as requested.<br><br>${transcript}</p></div>`;
}
}
});
});
serverUrl
represents the base server url that the app will hit to initialise the session or refresh the token.theme
can be used to quickly customise the look and feel of the app.theme.isLight
is a boolean to quickly toggle between the light and dark theme of Paste.theme.overrides
is an object that you can fill with all the theme tokens you want to customise. Here's the full list of tokens. Note remember to change the keys fromkebab-case
tocamelCase
.
fileAttachment
allows you to enable and configure what files your customers can send to your agents.fileAttachment.enabled
describes whether customers can send agents any file at all.fileAttachment.maxSize
describes the max file size that customers can send (in bytes).fileAttachment.acceptedExtensions
is an array describing the file types that customers can send.
transcript
allows you to enable and configure what chat transcripts your customers can received.transcript.emailSubject
configures what email customers receive in the email subject when they request an emailed transcript.transcript.emailContent
configures what email customers receive in the email body when they request an emailed transcript.
2. Local Backend Server
As mentioned before, Twilio Webchat App requires a backend to hit in order to work correctly.
This server — found in the server
folder — exposes two main controllers.
1. InitWebchat
This first controller, hit by the application when the pre-engagement form is submitted, takes care of a few things:
- Contacts Twilio Webchats endpoint to create a conversation and get a
conversationSid
and a participantidentity
- Creates a token with the correct grants for the provided participant identity
- (optional) Programmatically send a message in behalf of the user with their query and then a welcome message
A note about the pre-engagement form data
By default, this endpoint takes the friendlyName
field of the form and uses it to set the customer User's name via the webchat orchestration endpoint.
In addition to that, all the fields (including friendlyName
) will be saved as the conversation attributes
, under the pre_engagement_data
key. You can find additional information on the Conversation object here.
2. RefreshToken
This second controller is in charge of refreshing a token that is about to expire. If the token is invalid or already expired, it will fail.
Working in Production
In order to use this widget in production you will need to follow these three steps:
- Create remote server endpoints.
- Upload compiled and minimised React App code.
- Update your website template.
1. Create Remote Server Endpoints
It is necessary to create two endpoints on a remote server or as serverless functions, for initWebchat and refreshToken logic.
Security Best Practises
We highly recommend that you implement as many of the following security controls as possible, in order to have a more secure backend.
- Create an allow-list on the server side. It is necessary to verify on the server side that all the requests are sent from an allowed domain (by checking the origin header).
- Configure the Access-Control-Allow-Origin header using the allow-list described above. This will prevent browsers from sending requests from malicious websites.
- Create logs to detect and find anomalous behaviors.
- Block requests by IP, by geolocation/country and by URL. Thanks to the logs created, it is possible to detect suspicious behaviours, depending on those behaviours it is possible to block requests for specific IP addresses, domains and even geolocations.
- Include a fingerprint in the token. Generate a fingerprint to try to identify the client and include it in the token. When the token is sent, the fingerprint is generated again and compared with the token's fingerprint.
2. Upload Compiled and Minimised React App Code
To create a bundle file for the whole Webchat React App.
yarn build
# or with npm
npm run build
Make sure to upload and host this file on your server, or on a host service, that is accessible from your website's domain.
3. Update Your Website Template
Once the bundle is uploaded, make sure to have it loaded in your website page, as per example below:
<script src="https://[...]webchat.js"></script>
Finally, add the code to initialize the webchat widget as per following example. It is crucial that you update the serverUrl
with the base URL of your endpoints.
The React App will then target /initWebchat
and /refreshToken
endpoints. If you want to use different endpoint urls, make sure to upload the code in src/sessionDataHandler.ts
.
For more information about the available options, please check the Configuration section.
<script>
window.addEventListener("DOMContentLoaded", () => {
Twilio.initWebchat({
serverUrl: "%SERVER_URL%" // IMPORTANT, UPDATE THIS!!
});
});
</script>
Browser Support
Twilio Webchat React App is built entirely on two main libraries Twilio Paste Design System and Twilio Conversations SDK, and it supports the same set up browsers. For more information please refer to Twilio Conversations SDK browser support and Twilio Paste browser support FAQ
Accessibility
Twilio Webchat React App is built using Twilio Paste Design System and follows accessibility standards. Using Webchat app as a foundation for your website chat widget will make it easier to stay WCAG compliant with your website. Find out more about Twilio UX principles and inclusive design guidelines.
FAQs
As a developer, how do I clear an ongoing chat?
Open your browser console, run localStorage.clear()
and refresh the page to start anew.
Alternatively, you can simply wrap up/complete the corresponding task as an agent from your Flex UI instance.
License
MIT © Twilio Inc.