Twilio Webchat React App is an application that demonstrates a website chat widget built for Flex Conversations. It uses Twilio's Conversations JS SDK, Twilio Paste Design library, the Flex WebChats endpoint, and the Create React App.
Run the following command
yarn
We provide a handy bootstrap
script to set up the environment variables required, but you can alternatively copy the .env.sample
file.
yarn bootstrap \
accountSid=YOUR_ACCOUNT_SID \
authToken=YOUR_AUTH_TOKEN \
apiKey=YOUR_API_KEY_SID \
apiSecret=YOUR_API_SECRET \
addressSid=YOUR_ADDRESS_SID \
conversationsServiceSid=YOUR_CONVERSATIONS_SERVICE_SID
You can find your Account Sid and Auth Token on the main Twilio Console page.
For more info on how to create an API key and an API secret, please check the documentation.
You can find your Conversations Service Sid on the services page. Make sure to pick the one linked to your Flex Account — usually it is named Flex Chat Service
and it starts with IS
For the Address Sid, click on the edit button of your address and the edit screen will contain Address Sid. Note this Sid starts with IG
.
The environment variables associated with enabling and configuring customer transcripts can be found in the .env.sample
file and their use will be covered here.
yarn server
Your server will be served at http://localhost:3001/.
yarn start
Your app will be served at http://localhost:3000/.
Twilio Webchat React App is built entirely with Twilio Conversations SDK and provides UI for most of its features:
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.
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.
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.
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.
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.
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
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
.env
file.
EMAIL_TRANSCRIPT_ENABLED=true
.env
file as the values for SENDGRID_API_KEY
and FROM_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.
Twilio Webchat React App is an open source repository that includes:
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.
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 from kebab-case
to camelCase
.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.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.
This first controller, hit by the application when the pre-engagement form is submitted, takes care of a few things:
conversationSid
and a participant identity
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.
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.
In order to use this widget in production you will need to follow these three steps:
It is necessary to create two endpoints on a remote server or as serverless functions, for initWebchat and refreshToken logic.
We highly recommend that you implement as many of the following security controls as possible, in order to have a more secure backend.
To create a bundle file for the whole Webchat React App.
yarn 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.
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>
Next, declare the root element that the webchat widget will be rendered into:
<div id="twilio-webchat-widget-root"></div>
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>
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
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.
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.
Currently there is a known issue with installing dependencies for this project using npm. We are investigating this and will publish a fix as soon as possible. We recommend using yarn
instead.
MIT © Twilio Inc.