Tracking Code API Overview

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: Events will only be processed for accounts with Marketing Hub Enterprise.

The trackEvent function is used to track events in your HubSpot reports. Events are used to track that some action occurred, and can be tied to a contact record so that you can see if/when a contact triggered that event. 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 trackEvent function in the Tracking Code API (which is the preferred API) and the HTTP API.

The trackEvent 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 HTTP API can be used in cases where the HubSpot tracking code cannot be installed, so it can be used to track offline events (so you could trigger an event based on data processed in a CRM).  While the HTTP API cannot be used to tie analytics data to a contact record, you can identify a contact record by email address, so that offline events can still be tied to contact records.

Event IDs and names:

Events can be triggered using a numerical ID or a string name. If you're creating events in HubSpot (Reports > Analytics Tools > Events), they'll automatically be assigned a numerical ID, which will be used to trigger that specific event. You can get the ID out of the URL when viewing the event in HubSpot. See this page for more details about creating events.

You can also trigger an event using a string name for the event. If you use a name, and there is not an existing event that already has that name, a new event with that name will be dynamically created. If an event with that name was already dynamically, then the new event will count towards that existing one. This allows you to keep dynamically creating new events without doing manual work in HubSpot.

  • Events created in the HubSpot app cannot be triggered by name, only by ID.
  • Events created dynamically by name can only be created once. If you delete an event that was created this way, a new event will not be created if you try to dynamically trigger an event with the same name.

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.

Use case for this endpoint: In addition to creating contacts by email address, this method can also be used to set or update other contact properties. Note: the email address of an existing contact cannot be updated with this method.

Note - There are a few things to keep in mind when using this function:
  • 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. Other contact properties, including custom properties, can be updated with this function, but only an email will associate the data with a contact.
  • This function will not restore previously deleted contacts. These contacts must be restored in-app.


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(["trackEvent", { {event details} }]);

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


Arguments How to use Description
Event ID id: The ID of the event. If you created the event in HubSpot, use the generated ID of the event as a string. Otherwise, you can use a string name for the event to dynamically create an event. See the overview for more details on names and ids.
Value value: The value of the event. This is an optional argument that can be used to track the revenue of an event. This value will be used to increment the hs_analytics_revenue property if the event is associated with a contact record. 

Use this endpoint 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 endpoint: Events can capture actions like logging in. You can use data from this endpoint to segment users how have not logged in in more than seven days and target them with a re-engagement campaign.

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

document.getElementById("buyNow").onclick = function() {
    _hsq.push(["trackEvent", {
        id: "Clicked Buy Now button",
        value: 20.5

Events HTTP API:  GET 


This API is used to trigger a custom HubSpot event using an HTTP GET call. Note: You must have a Marketing Hub Enterprise subscription for access to the events tool.

Use case for this endpoint: You can use this call to trigger any custom events in your HubSpot account. Those events can then be used to create smart lists, score leads, or email contacts.

Response details

If the request is successful, it will have a status code of 200 with no data in the body. The content-type will be image/gif, so it's possible to use HTTP API urls with <img> tags, though we recommend using the JavaScript API on webpages when possible.

  Method Details

HTTP Methods: GET

Response Format: N/A

Requires Authentication?: No

Rate Limited?: No

Headers: User-Agent

Products: Marketing

Required Scope: business-intelligence


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

Required Parameters How to use Description
HubSpot Hub (portal) ID &_a=XXXXXX - Used in the request URL. Your HubSpot Hub ID. See this page for help finding your Hub ID.
Event ID &_n= - Used in the request URL The ID or name of the event you want to trigger.  See here for more details.



Optional Parameters How to use Description
Contact Email Address & - Used in the request URL If you want to tie the event that you're triggering to a contact in HubSpot, use this parameter. If the contact doesn't yet exist in HubSpot, it will be created. If the contact does exist, the event will be attributed to the existing contact.
Contact Revenue &_m=20 - Used in the request URL You can use Events to keep track of the monetary value that a contact is worth to you. Any numerical amount that you provide here will increment the "Revenue" field within the Web Analytics History section this value.
Any Contact Property &{property}={value} - Used in the request URL You can also include any contact property with the Event that you are triggering. This will populate the corresponding contact property for the contact specified by the email parameter. Make sure that the parameter you use here is the same as the property name (not the label) in the Contacts Settings area of HubSpot. For example, if you have a property with the name favorite_color, you can populate that property using &favorite_color=orange
External id &id={value} - Used in the request URL

Ties the event to a record based on your external id. Unlike email, including this id will not automatically create a contact record, so you would need to have some event associating the id with an email (either a previous HTTP Event call with both the id and email, or by using the id with the JavaScript API for a visitor that was associated with an email address) to have the event update a specific contact if you're only including the id parameter. Also note that this id is treated as a completely external id, so there will not be a way to look up a contact record using this id.

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