Setting Up HubSpotUTK Cookie Tracking

How to set up Hubspot attribution to link contacts captured in Spara to hubspotutk cookie tracking data.

The hubspotutk cookie is set by HubSpot's tracking script and stores a unique visitor token used for contact attribution. By calling HubSpot's identify method from Spara's JavaScript API onUserMessageSent() event, you can associate a visitor's session with their HubSpot contact record.

Prerequisites

Add the identify call

Use Spara's onUserMessageSent() event (see Javascript API) to extract the visitor's email. Then, call identify to merge the visitor to the hubspot cookie data and trackPageView to push the identity to HubSpot.

<script type="text/javascript" src="https://app.spara.co/embed-<app_id>.js"></script>
<script>
  Spara = {
    onUserMessageSent: function (text) {
      // extract email from user message
      function extractEmail(text) {  
        const match = text.match(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/);
        return match ? match[0] : null;
      }

      const email = extractEmail(text);

      if (window._hsq && email) {
        window._hsq.push(["identify", { email }]);
        window._hsq.push(["trackPageView"]);
      }
    },
  }
</script>

Note: identify sets the identity in HubSpot's tracker memory only. A separate trackPageView or trackEvent call is required to actually send the data to HubSpot.

Single-page application (SPA) setup

If your site uses Next.js or React, page navigations don't trigger full reloads, so HubSpot won't automatically track route changes or send identity data.

  1. Follow the identify call instructions above.

  2. Create a HubSpotPageView.tsx component to call trackPageView on every route change:

  1. Add it to your root layout (app/layout.tsx):

Last updated