# Integrate HubSpot Chatbot into Your React App: A Developer’s Guide

**URL:** <https://community.hubspot.com/t/integrate-hubspot-chatbot-into-your-react-app-a-developer-s-guide/118763>\
**Category:** APIs & Integrations\
**Tags:** chatflows\
**Created:** [October 21, 2024, 5:46am UTC](https://community.hubspot.com/t/integrate-hubspot-chatbot-into-your-react-app-a-developer-s-guide/118763 "2024-10-21T05:46:06Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![NPatel6](https://avatars.discourse-cdn.com/v4/letter/n/9de053/32.png) [@NPatel6](https://community.hubspot.com/u/NPatel6)\
**Post date:** [October 21, 2024, 5:46am UTC](https://community.hubspot.com/t/integrate-hubspot-chatbot-into-your-react-app-a-developer-s-guide/118763/1 "2024-10-21T05:46:06Z")

</div>

This guide will walk you through the entire process step-by-step on integrating the HubSpot chatbot also called tracking code in react. So let’s dive in!

# **Table of Contents**

1. Prerequisites  
2. Step 1: Setting Up HubSpot Tracking Code  
3. Step 2: Adding the Tracking Code to Your React App  
4. Step 3: Installing and Configuring the `react-hubspot-tracking-code-hook` Library  
5. Step 4: Assigning Logged-In User Information  
6. Step 5 (Optional): Revoking User Details on Logout  
7. Wrapping Up

**Prerequisites**

Make sure you have the following before you start:

- **HubSpot Account:** If you haven’t signed up yet, [create](https://www.hubspot.com/products/crm) a free account.  
- **React Application:** A working React project. Create React App is a great option if you’re starting from scratch.  
- **Basic React Knowledge:** Familiarity with React components, hooks, and project structure.  
- **Access to Project Files:** You’ll need to modify your `index.html` and install npm packages, so ensure you have the necessary permissions.

### 

Step 1: Setting Up HubSpot Tracking Code

The HubSpot Tracking Code is like the bridge between your website and HubSpot’s services. It enables the chatbot, tracks user interactions, and integrates with other HubSpot tools.

**a. Log in to Your HubSpot Account**

1. Head over to [HubSpot](https://app.hubspot.com/login) and log in with your credentials. If you’re new, go ahead and [sign up](https://www.hubspot.com/products/crm).

**b. Navigate to Account Settings**

1. Once logged in, click on the **Settings** icon (🔧) located in the main navigation bar at the top-right corner.  
2. In the left sidebar, find and click on **Tracking Code** under the **Accounts Management** section.

 ![Screenshot 2024-10-21 at 10.37.57 AM.png](https://d2qpr2jzcazej7.cloudfront.net/original/3X/6/3/635a9edc725954d54e49056d56cd09603bcc534e.png)

3. You’ll see your unique tracking code snippet. Click **Copy** to grab the code, or use **Email to web developer** if you prefer sending it directly to your team.

**Note** : If you’ve just created the tracking code, give it a few hours to propagate. The chatbot might not appear instantly.

**Step 2: Adding the Tracking Code to Your React App**

Now that you have your tracking code, it’s time to embed it into your React application.

**a. Locate the `index.html` File**

In most React setups (like Create React App), the `index.html` file resides in the `public` directory.

```lia-code-sample
my-react-app/
├── public/
│ └── index.html
├── src/
│ └── ...
├── package.json
└── ...

```

**b. Insert the Tracking Code**

1. Open the

**index.html**

file in your preferred code editor.

2. **Before** the closing

**\</body\>**

tag, paste the tracking script you copied from HubSpot. It should look something like this:

```lia-code-sample
<!DOCTYPE html>
<html lang="en">

<head>
<base href="/" />
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />

<title>My React App with HubSpot Chat</title>
</head>

<body>
<div id="root"></div>

<!-- HubSpot Tracking Code -->
<script type="text/javascript" id="hs-script-loader" async defer src="//js-eu1.hs-scripts.com/<Your-Tracking-Code>.js"></script>
</body>

</html>

```

**Important:** Replace

**\<Your-Tracking-Code\>**

with the actual code HubSpot provided (it’s usually a series of numbers).

**c. Save and Test**

1. Save the changes to **index.html**.

2. Start your React app if it’s not already running:

`npm start`

3. Open your browser and navigate to your app. If the chatbot doesn’t appear immediately, remember it might take a few hours to activate. Refresh the page periodically to check.

\*\*Step 3: Installing and Configuring the

react-hubspot-tracking-code-hook

Library\*\*

To better manage HubSpot’s tracking within your React app, we’ll use the

react-hubspot-tracking-code-hook

library. It provides a handy custom hook to interact with the HubSpot Tracking Code API.

**a. Install the Library**

Open your terminal, navigate to your project directory, and run:

`npm install react-hubspot-tracking-code-hook`

**Or if you’re using Yarn:**

`yarn add react-hubspot-tracking-code-hook`

**b. Understand What This Library Does**

This library offers a React hook that simplifies:

- **Setting the Current Page Path:** Essential for tracking page views in single-page applications (SPAs) like React.  
- **Manually Tracking Page Views:** Ensures each route change is recorded, maintaining accurate analytics.

**c. Implement the Hook in Your App**

Let’s add the hook to your main component, typically **App.js** or **App.tsx**.

1. **Open App.tsx (or App.js):**

```lia-code-sample
import React, { useEffect } from 'react';
import { useTrackingCode } from 'react-hubspot-tracking-code-hook';

function App() {
const { setPathPageView, setTrackPageView } = useTrackingCode();

useEffect(() => {
// Set the initial page path
setPathPageView('/');
// Track the page view
setTrackPageView();
}, [setPathPageView, setTrackPageView]);

return (
<div>
<h1>Welcome to My React App</h1>
{/* Rest of your components */}
</div>
);
}

export default App;

```

This ensures that when the component mounts, it sets and tracks the current page.

**d. Handling Route Changes with React Router**

If your app uses React Router for client-side routing (which most SPAs do), you’ll want to track page views whenever the route changes.

1. Install React Router (if not already installed):

`npm install react-router-dom`

**Or with Yarn:**

`yarn add react-router-dom`

2. Modify **App.tsx** to Include Routing and Tracking:

```lia-code-sample
import React, { useEffect } from 'react';
import { BrowserRouter as Router, Route, Switch, useLocation } from 'react-router-dom';
import { useTrackingCode } from 'react-hubspot-tracking-code-hook';

function App() {
const { setPathPageView, setTrackPageView } = useTrackingCode();

return (
<Router>
<RouteChangeTracker setPathPageView={setPathPageView} setTrackPageView={setTrackPageView} />
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
{/* Add more routes as needed */}
</Switch>
</Router>
);
}

function RouteChangeTracker({ setPathPageView, setTrackPageView }) {
const location = useLocation();

useEffect(() => {
setPathPageView(location.pathname);
setTrackPageView();
}, [location, setPathPageView, setTrackPageView]);

return null;
}

function Home() {
return <h1>Home Page</h1>;
}

function About() {
return <h1>About Page</h1>;
}

export default App;

```

**Step 4: Assigning Logged-In User Information**

Personalizing the chatbot experience by linking it to the current user can make interactions more meaningful. Here’s how to set the logged-in user’s email in HubSpot.

\*\*a.

Implementing User Identification\*\*

Assuming you have an authentication system (like Firebase, Auth0, etc.), you’ll typically have access to the user’s email and a unique ID upon login.

1. **Create an Authentication Handler:**

Let’s say you have a **signIn** function that handles user login.

```lia-code-sample
import { useTrackingCode } from 'react-hubspot-tracking-code-hook'

const { setIdentity } = useTrackingCode()

const signIn = async (email: string, id: string) => {
 setIdentity(email, { id: id })
 }

```

2. Explanation:

This function is used to identify a visitor to your site. The unique identifier is an email address. If there is an existing contact record for that email address, it will be updated. Otherwise, a new contact record will be created. In both cases, the analytics data collected for the visitor will be associated with the contact record.

**Step 5 (Optional): Revoking User Details on Logout**

Switching users or logging out should clean up any user-specific data to maintain privacy and data integrity. Here’s how to revoke user details from HubSpot when a user logs out.

**a. Implement the Revocation**

1. Create a Sign-Out Handler:

Extend your authentication logic to include a `signOut` function.

```lia-code-sample
const signOut = () => {
 revokeIdentity();
};

const revokeIdentity = () => {
 if (window._hsq) {
 window._hsq.push(['revokeCookieConsent']);
 } else {
 window._hsq = window._hsq || [];
 window._hsq.push(['revokeCookieConsent']);
 }
};

```

**Why This Matters:** Revoking user details prevents data from different users from getting mixed up, maintaining the privacy and accuracy of your analytics.

**Wrapping Up**

Congratulations! 🎉 You’ve successfully integrated the HubSpot chatbot into your React application. Here’s a quick recap:

1. **Set Up HubSpot Tracking Code:** Obtained and embedded the tracking script into your `index.html`.  
2. **Installed and Configured the Library:** Used r

eact-hubspot-tracking-code-hook

to manage tracking within React.  
3. **Handled User Identification:** Linked logged-in users to HubSpot for personalized interactions.  
4. **Managed User Data on Logout:** Ensured data privacy by revoking user details upon logout.

---

<div class="post-metadata">

**Author:** ![Jaycee\_Lewis](https://d10pqhm3lwygmk.cloudfront.net/user_avatar/community.hubspot.com/jaycee_lewis/32/61352_2.png) [@Jaycee\_Lewis](https://community.hubspot.com/u/Jaycee_Lewis)\
**Post date:** [October 21, 2024, 8:28pm UTC](https://community.hubspot.com/t/integrate-hubspot-chatbot-into-your-react-app-a-developer-s-guide/118763/2 "2024-10-21T20:28:57Z")

</div>

Thanks for sharing @NPatel6 👋 — Jaycee
