Tracking Code API Overview

This page has been updated for working with new custom behavioral events.

For legacy custom events, please see the legacy documentation.

In addition to tracking page views, the HubSpot tracking code allows you to identify visitors, track events, and manually track page views (without reloading the page). The Tracking Code API allows you to dynamically create events and track event data in HubSpot.

Function calls are pushed into the_hsq array:

var _hsq = window._hsq = window._hsq || [];
_hsq.push(["method", "arg1"]);

Anything already in the _hsq array is processed when the tracking code is loaded, so you can push an identify call to the array before the code loads to have the identity information pushed with the initial trackPageView call.

Note: trackPageView is automatically called when the tracking code loads, so you should not push any trackPageView calls to _hsq before the page loads.

How do identities work?

The HubSpot analytics tool identifies unique records using two pieces of data, the usertoken (stored in the visitors browser in the hubspotutk cookie) and the email address. When the HubSpot tracking code tracks an action (such as a page view) for a visitor, it automatically associates that action with the usertoken. When you use the Tracking Code API to identify a visitor by email address, the analytics system will tie that email to the usertoken, allowing HubSpot to update an existing contact record or create a new one. HubSpot will validate the email address used for any process that would create or update a contact record. Analytics data (page views, original source, etc.) associated with the  usertoken will show up on the contact record.

With this in mind, you should only use the identify method when you know the identity (i.e. the email address) of the person viewing the page. Using a placeholder email for unknown visitors will create a contact record with that placeholder email, and the visitor's usertoken cookie will be associated with that record, meaning that all unknown visitors would be associated with that single placeholder contact.

Keep in mind that the identify function only sets the identities in the tracker. The identities do not get passed to HubSpot until you make a separate trackPageView or trackEvent call.

Please note that the HTTP API cannot be used to associate analytics data with a contact record, though you can still use the email= parameter in the URL to associate the event with the contact with that email address (or create a new contact if the email address does not belong to an existing record).


Tracking events

Note:Custom behavioral events will only be processed for accounts with Marketing Hub Enterprise.

The trackCustomBehavioralEvent function is used to track custom behavioral events in your HubSpot reports. Custom behavioral events are used to track that an action occurred, and can be tied to a contact record so that you can see if/when a contact triggered that event. In addition, HubSpot can track metadata about the event in the form of properties. HubSpot includes a set of standard properties that can capture certain metadata when it is present at the time of completion, including UTM parameters or device and operating system metadata. While you can set up simple events in HubSpot, you can use the Events API to track more complicated processes on your website or track events that occur offline.

Which one of the two Event APIs should I use?

There are two APIs that work with Events, the trackCustomBehavioralEvent function in the Tracking Code API and the HTTP API.

The trackCustomBehavioralEvent function requires that the HubSpot tracking code be installed on the page.  Since this function works alongside HubSpot's analytics tracking, any events triggered through the JavaScript API will automatically be associated with the visitor's hubspotutk cookie (often called the usertoken), so the event would automatically be tied to the contact associated with that usertoken (see the section about identities below for more information).

The details of the HTTP API can be found here.

Event IDs and names:

Events can be triggered using an Event ID (or an Internal Name). If you're creating events in HubSpot (Reports > Analytics Tools > Custom Behavioral Events), they'll automatically be assigned an Event ID, which will be used to trigger that specific event. You can get this Internal Name from the event created inside HubSpot. See this page for more details about creating events.



Triggering custom behavioral events with the Tracking Code API

If your website has the HubSpot tracking code installed, there are three ways to trigger a custom behavioral event using the Tracking Code API. You can learn more in this help article.

See the details below for manually triggering custom events using the HubSpot tracking code, and see this documentation for details on triggering events using the HTTP API.

Tracking in single-page applications:

The HubSpot tracking code will automatically record a page view when the code is first loaded, but you can also manually track page views in a single-page application without reloading the tracking code. You can use the setPath and trackPageView functions to update and track the current page:

<!-- Set up the path for the initial page view -->
  var _hsq = window._hsq = window._hsq || [];
  _hsq.push(['setPath', '/home']);

<!-- Load the HubSpot tracking code -->
<!-- Start of HubSpot Embed Code -->
  <script type="text/javascript" id="hs-script-loader" async defer src="//{hubId}.js">
<!-- End of HubSpot Embed Code -->

<!-- Tracking subsequent page views -->
  var _hsq = window._hsq = window._hsq || [];
  _hsq.push(['setPath', '/about-us']);

See the documentation for setPath and trackPageView for more details on those functions.

Checking consent banner status

If your site uses the privacy consent banner, you can use the addPrivacyConsentListener function to check the consent status of the visitor. See the documentation for the addPrivacyConsentListener function for more details.

Removing consent banner cookies

If you need to remove the consent banner cookies for a visitor, such as in the case of a GDPR related deletion request, you can use the revokeCookieConsent function. See the documentation for the revokeCookieConsent function for more details.

Place do not track cookie

In the event where you need to prevent all tracking by the HubSpot tracking code, you can place the do not track cookie into a visitor's browser. See the documentation for the doNotTrack function for more details.

Set Page Path: hsq.push(['setPath', { path string }])


Required Parameters How to use Description
Path 'setPath', { path string } The path of the current page. The set path will be treated as relative to the current domain being viewed. The path should always start with a preceding slash. If your URL also contains parameters, these will need to be included in the path as well. See the examples for more details.
Update the path of the current page.  This function should be used by single-page applications to update the current page whenever a page is loaded.  After using this function to update the path, you will need to call the trackPageView function to track the view of the current page.
  • This function call only updates the path stored in the tracker. You'll need to call the trackPageView function to actually track the updated page.
  • Single-page applications should push a setPath call into _hsq before the tracking code loads to set the URL that gets tracked for the first page view (the trackPageView function is called automatically when the tracking code is loaded). See the Tracking Code overview for an example of this.
  • This function can only update the path of the URL.  The domain is set automatically based on the URL of the page on load, and the path that is set using this function is always treated as relative to that detected domain.


Example usage:

// These examples assume that the domain of the site is

// Set the path to '/' and track the page
var _hsq = window._hsq = window._hsq || [];
_hsq.push(['setPath', '/']);
// This will result in a view being recorded for

// Set the path to '/contact-us' and track the page
var _hsq = window._hsq = window._hsq || [];
_hsq.push(['setPath', '/contact-us']);
// This will result in a view being recorded for

// Set the path to '/blog/post?utm_campaign=my-campaign' and track the page
var _hsq = window._hsq = window._hsq || [];
_hsq.push(['setPath', '/blog/post?utm_campaign=my-campaign']);
// This will result in a view being recorded for

// Set the path to '/#/about-us' and track the page
var _hsq = window._hsq = window._hsq || [];
_hsq.push(['setPath', '/#/about-us']);
// This will result in a view being recorded for

Track Page View: _hsq.push(['trackPageView']); 

Track a page view. This function is called when the tracking code is loaded on a page, but you can manually call this function to track subsequent views in a single page application.

This function does not support any arguments.
The title tracked will be the current value of document.title

The URL tracked is based on one of either:

  • the path set using the setPath function.  If you're site is built as a single-page application, this function is the preferred method of setting the tracked path.
  • If setPath has never been called, the tracked URL will be the Referer HTTP header in the request being made by the visitor's browser to HubSpot's tracking servers (modifying the browser history state would update the value used for that header).
    • Relying on the Referer header will not support URL fragments (anything after the # in the URL), as fragments are not included in the Referer header. 
    • Any path set using the setPath function will override the data in the Referer header, so if you call setPath once, you will need to use setPath to update the path for each view you want to track.
Example usage:

// Track a new page using setPath:
// Update the path stored in the tracker:
var _hsq = window._hsq = window._hsq || [];
_hsq.push(['setPath', '/#/new-page']);
// Track the page view for the new page

// Track a new page by updating the browser state:
// Update the browser state, showing "updated.html" in the browser address bar
var stateObj = { foo: 'updated' };
history.pushState(stateObj, "updated page", "updated.html");
//Track the page view for the new page, '/updated.html'
var _hsq = window._hsq = window._hsq || [];
Note - There are a few things to keep in mind when using this function:
  • As mentioned above, this function is automatically called when the tracking code loads, and there is not a way to prevent that initial call. Calling this function manually before or during the initial page load could lead to duplicate views being tracked.
  • While that call cannot be prevented, you can control the URL recorded for the page by pushing a setPath call into _hsq before the tracking code is loaded. See the Tracking Code overview for an example of this.
  • We recommend against including a <link rel="canonical"> tag in your page if your site is a single-page application. If your page uses <link rel="canonical"> tags, you'll need to use the setPath function to update the path of your new pages, as the canonical URL set from the link tag will override any detected URL if you're only updating the browser history state.

Identify a visitor: _hsq.push(["identify", { {identity details} }]);


This endpoint 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.

If your account was created before September 8, 2021 and is set up to allow contact properties to be updated through the tracking code, you can also include other contact properties to be updated with this function. 

When using this function, keep in mind the following:

  • This function call stores the data in the tracker, but the data is not actually passed to HubSpot with this call. The data will only be passed when tracking a pageview or an event (with either the trackPageView or trackEvent functions).
  • You must include an email address to tie the data to a contact. 
  • This function will not restore previously deleted contacts. These contacts must be restored in HubSpot.

This example grabs the value of a 
query string parameter '?email='
and uses that to identify the visitor

function getParameterByName(name) {
    var match = RegExp('[?&]' + name + '=([^&]*)').exec(;
    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));

var _hsq = window._hsq = window._hsq || [];
    email: getParameterByName("email")

This example sets the email,
as well as a custom property favorite_color
var _hsq = window._hsq = window._hsq || [];
    email: getParameterByName("email"),
    favorite_color: 'orange'

This example sets the email,
as well as a custom external id for the visitor.
This assumes that your site includes a variable named 
'user' that includes that user's id in an 'id' 
property, and their email in an 'email' property.
var _hsq = window._hsq = window._hsq || [];

In addition to identifying a record by email address, you can also use a custom external ID to identify a visitor, by simply using 'id' as the identifier.  As with email, identifying a record using 'id will associate analytics data for the visitor with that ID.  However, unlike with an email address, including an 'id' by itself will not create a contact. Also, this 'id' is treated as a completely external identity, so while analytics data can be associated with a specific contact record by the ID (if, for example, you've previously identified a record by ID and by email, or the record was previously identified by ID and the visitor also has a form submission), the contact record cannot be looked up by this ID.

Note: This external ID can only be used with the HubSpot tracking code. This ID cannot be used to retrieve or update any records through any other HubSpot tools or APIs. 

Events JavaScript API: _hsq.push(["trackCustomBehavioralEvent", { {event details} }]);

Please note: Events will only be processed for accounts with Marketing Hub Enterprise.

Use this function to track an event using JavaScript and HubSpot's tracking code. You can use events to track specific activities completed by visitors on your site. Tracked events can show up in contacts' timelines.

Use case for this function: Events can capture actions like logging in, downloading files, or another action on your website. You can use data from this endpoint to segment users and target them with a re-engagement campaign.

Example code to fire a custom behavioral event using the name "clicked Buy Now button" when a visitor clicks an element with the 'buyNow' id.

document.getElementById("buyNow").onclick = function() {_hsq.push(["trackCustomBehavioralEvent", {
   name: "pe123456_course_registration",
   properties: {
       course_id: "Math101"
Arguments How to use Description
Name name: "Internal_Name"

The EVENT_ID or Internal Name of the event that you created in HubSpot.

Properties property_name: "Property Value"

You can only update 

Properties is a list of key-value pairs. Each key-value pair denotes a property.

Property name is the name of the property you’ve created for the event. Property value will take what you put for that property. An example for a property named My_Button with a value would look like {“My_Button” : “Buy Now”}. Note you can also track non-defined properties and go back to create them after event tracking.

Note: See this documentation for triggering events using the HTTP API.

Remove cookies: _hsp.push(['revokeCookieConsent']);


Remove the cookies created by the HubSpot tracking code that are included in the consent banner under GDPR. This would include the cookies related to tracking the visitor.

As a result of the cookies being removed, the visitor would see the cookie consent banner on their next page load, as they would appear as a new visitor.

You can find the specific list of cookies that will be removed  in this Knowledge Base article.

Example code to remove the consent banner cookies
when a visitor clicks an element with the 'removeCookies' id.

var _hsp = window._hsp = window._hsp || [];
document.getElementById("removeCookies").onclick = function() {

Get privacy consent status:_hsp.push(['addPrivacyConsentListener',callbackFunction]);


This content was moved to its own dedicated page specific to the cookie consent banner.

Place do not track cookie: _hsq.push(['doNotTrack']);


Places the __hs_do_not_track cookie in the visitors browser, which will prevent the HubSpot tracking code from sending any information for the visitor.

You can remove the cookie by calling the function again and including the {track: true} argument:
_hsq.push(['doNotTrack', {track: true}]);

Note: This will prevent all information from being collected by the tracking code, including anonymized traffic and custom event data.

Example code to place the __hs_do_not_track cookie for
the visitor when they click an element with the 'doNotTrack' id.

document.getElementById("doNotTrack").onclick = function() {

Get cross-domain linking parameters: _hsq.push(['addIdentityListener', function(hstc, hssc, hsfp) {}]) 

Allows you to get the parameters needed to create cross-domain links. This will allow you to build links that support cross-domain tracking for links added after the page loads, or links that function using JavaScript instead of standard anchor tags. 

The HubSpot tracking code can be used across multiple sites with separate domains. This function will allow you to get the query parameters required to create create links that will allow you to track your visitors across those separate domains. These query parameters are used by the HubSpot tracking code to identify a visitor across domains by ensuring that the separate cookies for the separate domains are merged to a single tracked visitor.


// Get the cross-domain query parameters and store them in a string,
//so that they can be appended to links as needed.
_hsq.push(['addIdentityListener', function(hstc, hssc, hsfp) {
    // Add these query parameters to any links that point to a separate tracked domain
    crossDomainTrackingParams = '&__hstc' + hstc + '&__hssc=' + hssc + '&__hsfp=' + hsfp;

Note: Cross-domain links are only needed when linking to a distinct domain (e.g., and that is also being tracked for a single HubSpot account. HubSpot tracking cookies are set at the domain level (, so visits between subdomains ( and should not need the cross-domain link parameters.

Note: Cross-domain links are automatically set up by the HubSpot tracking code on load, so you should only need to update links that are dynamically added to the page after the tracking code is loaded.

Reapply analytics event handlers: _hsq.push(['refreshPageHandlers'])


Reapplies any analytics event handlers that are set up in the analytics settings for the HubSpot account.

This would include reapplying any clicked element events that have been set up.

 You can use this function to automatically reapply click handlers when content on the page is updated, such as updating a section of content or displaying a modal window on the page.

Note: This functionality is automatically triggered as part of the setPath function, so you'll only need to use this function when updating the content without updating the tracked page URL.

// Reapply event handlers after updating the page content

Custom JavaScript to send a custom behavioral event

This guide assumes that you’ve created a custom behavioral event in the UI.

  1. Go to the custom behavioral events definition manager and copy the “Internal Name” of the event that you would like to track.
  2. In the definition manager, click into any properties that you would like to track in javascript. Drill into getting extra information for that property by clicking the </> symbol. Record the “internal name” of each of these properties.
    new_event_extra information
  3. Navigate to the Settings > Analytics & Tracking and click the “Customize javascript” link in the Tracking Code tab.
  4. Click the “Add custom JavaScript” button.
  5. In the script editor view,enter any custom javascript. This will be executed after the tracking code loads for a page. To track a behavioral event, use the “trackCustomBehavioralEvent” API. This API has the following form:


_hsq.push([“trackCustomBehavioralEvent”, { name: “((behavioral_event_internal_name))”, properties: { internal_property_name: property_value} }]);

In this example, a configuration to track a course registration event when a button with the HTML id register_for_econ101 is clicked. The configuration would look like the following:


Was this page helpful? *
This form is for feedback on our developer docs. If you have feedback on the HubSpot product, please share it in our Idea Forum instead.