•3 months ago
In this tutorial, learn how to build a Stream chat widget that connects to the HubSpot CRM to automatically create a new contact when a customer initiates a chat. This widget, backed by the Stream chat API, can be easily embedded to your site as a chat widget for sales, support, lead capture, or a landing page. You can take this knowledge to build powerful sales tools that seamlessly integrate with the HubSpot API.
The application utilizes a React
frontend and an Express
backend. The tutorial explains how to use some basic features of the powerful Stream Library, which handles most of the chat widget UX.
The code required for this tutorial is available in GitHub. If you'd like to build the app from scratch, use
npm express generator --no-view for the backend, and
create-react-app for the frontend. Be sure to use the
package.json file from this repository to get the required dependencies loaded in your version. Otherwise, you can clone the repo from GitHub and follow along.
This tutorial is written to work with a wide range of skillsets. It requires basic knowledge of React Hooks, Express, and Node.js. The code is built and run with the Node Package Manager and is made to run locally. We also use dotenv.
- We'll create a Stream Client and register a user with a chat channel, but we won't specifically describe how to set up support/sales user experience. We'll focus primarily on the customer's experience.
- We won't explore notifying a customer representative when a chat is initiated.
- Styling and CSS: this app uses the out-of-the-box styling of Stream. Check out Stream's free UI Kit to make your chat app shine ✨.
- Encryption or Authentication. To add some more security to your app, check out this post, which shows how to authenticate users and encrypt messages.
What We'll Do
- Set up a free HubSpot account and activate a key.
- Set up a free Stream account and activate a key.
- Create a React form to capture the customer's first name, last name, and email.
- Use an Express backend to:
- Join and load the specified Chat in the frontend using Stream's built-in UI Components.
Let's Get Down To Business
First, we need to set up your unique API keys from HubSpot and Stream. These authenticate your app and are to be stored in a secure
.env file. The Git Repo includes a
.env.example file you can use as a template. Add your unique keys to this file, then remove '.example' from the file name.
Set-up your HubSpot
Create your account at HubSpot and complete the registration form.
Once you are logged into the
HubSpot Dashboard,go to Settings in the upper-right corner
- Navigate to Integrations > API Key, and create a key. If you're a robot, stop here. You've gone too far...
- Copy the HubSpot API key and paste it in the
.envfile located in the
backendfolder. HubSpot's API is authenticated via this key.
Set-up your Stream Account
Sign up for a Stream Trial.
To generate a Stream API Key and API Secret, navigate to your Stream.io Dashboard.
- Then click on "Create App", and complete the form like in the following screenshot.
Give your app a name, select "Development" and click "Submit".
Stream will generate a Key and Secret for your app. You need to copy these into your
.envfile as well.
Spin up the app
If you haven't already, run
npm installon both the
Once your packages are installed, run either
nodemonon both the
When opening this app in the browser, the user will see this login form:
The following snippet shows how the registration form is created. We'll ignore the chat app code for now, as indicated with
The simple form above sets up three
useStates to update and store the user input fields. The form's
register(), will post the user credentials to the backend.
Registering User with Backend
Let's take a look at the first half of the frontend's
register() function. The second half of this function handles the response from the backend, which we will cover next. We use an asynchronous await function to give the backend time to do its work before we continue rendering in the frontend, and wrap the work in a try block for error handling.
Configure the Backend
A brief explanation of backend routing
Let's take a peek at how we handle the backend routing.
npm express generatorsets up this routing for us, but let's run through it in case it's new to you. To start our server we run
npm start. The command
npm startis a script included in
backend/package.json. This script tells node to run the file
backend/bin/www, which in turn tells Express to start a server on port 8080 (the port number can be changed in the
.envfile). Any communications from the frontend are directed to this port. The
wwwfile also configures the
api.jsfile to handle those requests. Next,
api.jstells Express to
backend/routes/index.jswhich is mounted under the root path (
'/'). In other words: our request from the front end will get routed to
index.js. (To learn more about how this works, take a peek at this tutorial).
Before we dive into handling our routes, let's configure
The Stream Chat library is Stream's Chat App library that does all the heavy lifting of creating the chat app itself. HubSpot offers an excellent library we will utilize as well.
By requiring and configuring
dotenv, we're able to access the private variables we set up in
.env. Call these variables using
hubspot library will make connecting to their API a breeze.
Backend Registration Endpoint Process Flow
When a user registers to start a chat, the handler function, configured via
router.post('/registrations'), takes over. This handler is our primary backend function, and will call a few handy methods to set up our chat session. Let's review the router function, then step through it to understand it.
createHubspotContact()to create a HubSpot contact
createUsers()to create our
- Register our app as a Stream
- Register (or update) users with our Stream client using
- Create a private chat
- Create a
customerTokenfor the frontend to join said channel
- Respond to the frontend with all required data to start the client in a browser
Creating Custom Contact Properties in HubSpot
This application will update a customized contact property in the HubSpot CRM.
To use a custom property follow these steps in your HubSpot Dashboard:
- Navigate to your contacts:
- Click the 'Actions' drop down menu, then 'Edit Properties':
- Click the 'Create Property' button and add whatever type of custom fields you'd like to use.
Connecting to the HubSpot API
The backend router first creates the HubSpot contact with the
contactObj is the argument to HubSpot's
.create() method. Any HubSpot contact property can be used in
contactObj. Check out their full list of properties here. Note how we used
your_custom_property as a key. The code will throw an error if you don't have a matching property in your HubSpot CRM.
Customer Stream Registration
To keep a chat secure, we can specify which users can use our client. Let's create a
customer object for our frontend user, and a
supporter object to represent a sales rep or support rep on the other end of the chat.
Note the keys included for the users above. Stream supports a myriad of properties you can add to your users, but for this example, we'll simply add an
Back in our primary backend function, the
upsertUsers() method registers both our
customer and our
supporter admin so they can use our app.
Create a Stream channel
Back to the
router.post function. Now that we have our client configured with the proper credentials, and our users registered with that client, we can open a channel for the two to chat. Stream's
channel() method first accepts a channel type;
'messaging' is the best type for this app.
Each channel on your client should have a unique name. For simplicity, we use the customer's email address, so that if the user is disconnected from their chat, they can return to it by entering the same credentials into the registration form. In your production application, you should create secure id's that can't be guessed.
members argument specifies which users can join this channel. This is not required for the channel, but by specifying the members, we add a layer of security by preventing other users from joining the channel. If
members is not included with the arguments, the channel will be public by default.
Stream provides a quick and easy token generator:
createToken(). This will be used in the frontend to verify the user. The final response to the frontend includes all information required to load the client in the browser and join the channel specified.
Customer Joins Chat in Frontend
Once the backend is finished, the frontend needs to:
- Decompose the response
- Join the Stream client using the
- Establish the browser's user using the
- Join the specific channel using the
- Render the Stream Chat
The snippet below uses
//... to indicate code we already covered in the first section.
The responses from the backend are used in the same manner for the frontend:
- Establish the client using the Stream
- Set the frontend user, supplying the
- Join the channel we already created
channel states determine what to render on the page. After a successful response from the backend, these objects are present, and the Stream Chat components will be rendered.
To create a fully functional chat component from scratch would be a monumental task. Using the Stream's components gets you going quickly. Keep in mind that the Stream Chat Components used here are the most basic, but Stream offers deeper customization.
That's a Wrap
So, there you have it: a customizable shat widget that easily pushes user inputs to your HubSpot CRM for lead capturing purposes. Stay tuned for more posts on how to connect HubSpot with agile Stream apps!