Tag Rocket contains powerful data & event-gathering capabilities. But it does not support every tag in the world out of the box. That is why we developed a way for store owners to use Tag Rocket to enable enhanced tagging for the tags not supported out of the box. This is done via an API we developed.

Existing Tag Rocket API solutions

Please share your solutions so we can add them here:

alpha = little or no real-world testing, beta = developed but needs more real-world testing.

Our GitHub repository also includes other examples.

For the script-only solutions, you need to add the script to the Script Manager and edit any variables at the top of the script, e.g. with your account id. Place the scripts in the head on all pages.

How to add a Tag Rocket API Script

Watch this 2-minute video demonstrating the steps to enable the Tag Rocket API and add one of our script solutions to your store.

Install and Publish Tag Rocket

You must install Tag Rocket and enable the API before using it.

  1. Install the app from the app store
  2. Switch to the Dashboard
  3. Scroll down and select the settings for the Global Tag Values section
  4. Scroll down to find the Tag Rocket API section
  5. Check the “Fire All Events” option.
  6. Finish Editing
  7. Click Publish to add Tag Rocket your store.

Example – Writing Tag Rocket Events to the Console.

It’s probably easiest to go through a simple example of using TRAPI and then go into more detail. This example is also a helpful way to monitor how Tag Rocket fires events and the data it provides with them.

The easiest way to add scripts that use the TRAPI is via Storefront->Script Manager. For this example, script settings like this would work.

Name of scriptTag Rocket Console Logger
DescriptionLog Tag Rocket Events to the Console
Location on pageHead
Select pages where script will be addedAll pages
Script categoryTargeting;Advertising
Script typeScript
Script contents[See Later…]

When you write your scripts, you will customise these settings. Make sure you set the Script category to match the type of tag you will be supporting. Most tags are related to ‘Targeting;Advertising’. This is so BigCommerce can automatically make you compliant with a user’s consent when the cookie banner is enabled.

If you wish to intecept all TRAPI events, set the location to Head. Otherwise some events may be sent before your code is run.

Finally, you need to add the contents of the script. Here are the script contents that will write the Tag Rocket events to the console:

Save the script, then navigate to some pages on your website with the browser’s console open to see when the Tag Rocket events fire.

Dissecting The Script

Most scripts using the TRAPI will follow the same pattern. A wrapper code to let you use Tag Rocket once it is ready.

!function(w,t){
    w[t]=w[t]||{};var T=w[t];T.i=T.i||[];if(!T.init)T.init=function(f){T.i.push(f)};
    
    T.init(function() {
        // YOUR TAG ROCKET CODE HERE
    })
}(window,"TagRocket")

The wrapper code makes it possible to place this code anywhere on your pages. It can be before or after the Tag Rocket scripts. And it sets the T variable to represent the Tag Rocket object.

The script then inserts your code via a function to T.init(). This ensures your code gets run when Tag Rocket has been initialised (or instantly if it already is). The function inside T.init can access Tag Rocket functions and data via the T variable. e.g.

console.log("Consent",T.consent);

Tag Rocket stores user consent data in its consent parameter. Here’s an example output to the console:

Tag Rocket will tell you that all consent options are true if the cookie consent banner is not enabled. You could use this data to restrict what code is run based on the user’s consent options.

This part of the script could be an excellent spot to add the base tags for your solution. Tag Rocket even provides an addScriptTag function to help set things up. See later for more details.

T.addScriptTag('https://tagprovider/tag.js');

The main feature of TRAPI is the ability to listen to the Tag Rocket events. This is done via the T.on() function, which accepts a string for the event(s) you want to listen to (it can be a regex expression) and then a function to run when the event fires. In this case, we use the regex .* that matches all strings and, therefore, all events:

       T.on('.*',function(data, eventName){
            // YOUR EVENT HANDLER
        });

The function receives data about the event and the event’s name (eventName).

Handling Events

A common way to set things up is to create a switch statement on the eventName with case statements to handle each event used by the solution. Here’s an example of some events often used by tracking tags:

T.on('.*',function(data, eventName){
    switch(eventName) {
        case "QuickSearch":
        case "SearchPage":
            // EVENT HANDLER CODE
            break;
        case "CartItemChanged": 
            // EVENT HANDLER CODE
            break;
        case "CheckoutStep1CustomerStarted":
            // EVENT HANDLER CODE
            break;
        case "CheckoutStep5OrderCompleted":
            // EVENT HANDLER CODE FOR PURCHASES
            break;

    }                    
});

There are many events, and the data provided varies. Here’s a list of all the events with some pointers on the available data.

NameDescriptionData Object
LinkClickWhen a specific link is clicked on, like an email, phone number, external link or social link.parameters: tag, href, category, label and value
PromotionsVisibleWhen promotions (banners) become visible to the user. an infos property that is an array of information about each promotion that became visible.
PromotionClickedWhen promotion (banner) is clicked on.a promotion parameter with details about the promotion
ProductsVisibleWhen products become visible to the user.an infos property that is an array of information about each product that became visible. Includes a search parameter with the search term if the products were related to a search.
ProductClickedWhen a product in a list is clicked on. a product parameter with details about the product
ProductPageThe product
AddToWishListWhen a user adds a product to their wishlistThe product
CartItemChangedWhen a product is added or removed from the cart.The product with a change parameter that represents how many were added or removed. The data also includes the related cart.
CartPageWhen a user views the cart pageThe cart
CheckoutPageWhen the checkout page is viewedThe cart
CheckoutStep1CustomerStartedThe cart
CheckoutStep1CustomerCompletedThe cart
CheckoutStep2ShippingStartedThe cart
CheckoutStep2ShippingCompletedThe cart
CheckoutStep3BillingStartedThe cart
CheckoutStep3BillingCompletedThe cart
CheckoutStep4PaymentStartedThe cart
CheckoutStep5OrderCompletedThe cart
UserDataUpdatedT.userData contains user information that is currently known. On the order completion page this gets updated just before the CheckoutStep5OrderCompleted event when this event fires.User data
QuickSearchWhen the quick search feature is triggereda term parameter that contains the search term used.
SearchPageWhen a user visits the search result pagea term parameter that contains the search term used.
ContactFormThe user went to a contact form pageempty
ContactSuccessWhen a user successfully makes contact via the contact forman email parameter
ContactErrorWhen a user’s attempt to make contact failsAn error object
AccountCreatedWhen a user creates an account and lands on the thank you page.method can be set to ‘register’ or ‘order-confirmation’
SiteLoginWhen a user logs in via header linkthe method of login. Set to ‘guest’ if the login was done via the order confirmation page, otherwise ‘site’.
SiteLogoutWhen a user logs out via the header link empty
CheckoutLoginWhen a user logs in via the checkout pageThe cart
CheckoutLogoutWhen a user logs out via the checkout page The cart
SubscribeSuccessWhen a user successfully subscribes to the newsletteran email property
NewPromotionsAddedAs promotions (banners) are detected on the page based on them having the correct data attributes.
NewProductsAddedAs new products are detected on the page based on them having the correct data attributes. This will later trigger ProductDataGathered which will have more information about those products.An elements property containing the elements for each product
ProductDataGatheredWhen Tag Rocket has completed gathering extra information about some productsA reason for gathering the product. An items array containing all the product data gathered. This property can be replaced by a new array with some of the products removed.
CartDataGatheredWhen Tag Rocket has completed gathering extra information on a cart or order. ProductDataGathered on the cart items is fired before CartDataGathered.a cart property that can be modified
GetValueThis is fired when a tag is requesting a value to be calculated. The event handler can overwrite the value property using it’s own logic.destination is the name of the tag making the request (MicrosoftAds, FacebookAds, GoogleAds, GA4, PinterestAds, TwitterAds, YahooAds). type is the value it is requesting (ItemId, ItemGroupId, VariantName, OrderAmount). item or order provides relevant data about the request. And value is initially set to what the admin settings indicate it should be.
JavaScriptErrorWhen an unhandled JavaScript error happensdetails about the error that can include type, message, filename, lineno, colno, error, action and label.
ConsoleErrorWhen a Console error is generateda message property
LoadErrorWhen a resource like an image or javascript file fails to load.details about the error that can include targetUrl, targetPath amongst other information.
JsonLdErrorIf a JSON-LD script had a syntax erroran error (string) and element property (DOM element) indicating where the error was.
StencilUtilsFired when stencilUtils has loadedThe stencilUtils object
WebVitalsPendingFired before the complete event to let code alter the data. Set cancel to true to stop this vital from being recorded. e.g. you could create a mechanism to only record 10% of users.

Also includes a metric property with data including the debugNode related to the LCP or CLS node chosen. debugNode can be changed and will automatically change debugTarget.
WebVitalsCompleteFires when Web Vitals data is acquired. A metric property with data that includes name, status and value. In some cases, there is extra data about the element related to the vital such as debugTarget.
PerformanceMetricsAn experimental event not available yet containing more performance data than the web vitals events. Fires as the page unloads (via two methods) and contains all metrics in the one event.eventType indicates which of the two events triggered this event: pagehide or hidden. One event may be more reliably sent than the other.

fetchStart, requestStart, responseStart, responseEnd, domContentLoadedEventStart, domContentLoadedEventEnd, loadEventStart, loadEventEnd, transferSize, type, redirectCount, fcp, fid, cls, lcp, fp
SendBeaconWhen a beacon is senturl and data parameters
XMLHttpRequestResponseErrorWhen an XMLHttpRequestResponse based requests returns with an errorThe request
FetchResponseErrorWhen a fetch() requests returns with an error The error
GaCommandPendingA Google Analytics ga command is about to be sent. This is used by BigCommerces built-in Google Analytics. At this point, you can modify the command’s arguments, cancel the command, or insert new commands to be sent before it.arguments, cancel
GaCommandSentThe ga command has been sent. You could use this to add more commands after a specific command. e.g. add custom dimensions after the ‘create’ command was sent.arguments
GtagCommandPendingTag Rocket uses gtag for GA4 and Google Ads. This event fires just before gtag commands are sent. At this point, you can modify the command’s arguments, cancel the command, or insert a new command to be sent before it.arguments, cancel
GtagCommandSentThe gtag command has been sent. You could use this to add more commands after a specific command. e.g. add custom settings after the ‘js’ command was sent.arguments
GoogleAnalyticsFourItemPendingGives you the ability to alter an item about to be sent to GA4. e.g. alter the categories it sends.the related ‘product’ and the GA4 ‘item’ to send. The item can be updated.
UetCommandPendingMicrosoft Ads use the UET tag to send commands. This event fires just before UET commands are sent. At this point, you can modify the command’s arguments, cancel the command, or insert a new command to be sent before it.arguments, cancel
UetCommandSentThe UET command has been sent. You could use this to add more commands after a specific command. arguments
FbqCommandPendingFacebook Ads use the fbq tag to send commands. This event fires just before fbq commands are sent. At this point, you can modify the command’s arguments, cancel the command, or insert a new command to be sent before it.arguments, cancel
FbqCommandSentThe fbq command has been sent. You could use this to add more commands after a specific command. arguments
PintrkCommandPendingPinterest Ads use the pintrk tag to send commands. This event fires just before pintrk commands are sent. At this point, you can modify the command’s arguments, cancel the command, or insert a new command to be sent before it.arguments, cancel
PintrkCommandSentThe pintrk command has been sent. You could use this to add more commands after a specific command. arguments
TwqCommandPendingTwitter Ads use the twq tag to send commands. This event fires just before twq commands are sent. At this point, you can modify the command’s arguments, cancel the command, or insert a new command to be sent before it.arguments, cancel
TwqCommandSentThe twq command has been sent. You could use this to add more commands after a specific command. arguments
DotqCommandPendingYahoo Ads use the dotq tag to send commands. This event fires just before dotq commands are sent. At this point, you can modify the command’s arguments, cancel the command, or insert a new command to be sent before it.arguments, cancel
DotqCommandSentThe dotq command has been sent. You could use this to add more commands after a specific command. arguments
TtqTrackCommandPendingTikTok uses the ttq tag to send commands. This event fires just before dotq commands are sent. At this point, you can modify the command’s arguments, cancel the command, or insert a new command to be sent before it.arguments, cancel
TtqTrackCommandSentThe ttq command has been sent. You could use this to add more commands after a specific command. arguments
ConsentChangedFires when Tag Rocket detects that the users consent with BigCommerce has changed. This could happen via the BigCommerce consent banner or by calling TagRocket.updateConsentThe current consent information

For the event data that relates to products, here are some key properties that each product can contain:

PropertyDescription
nameName of the product
priceHow much does it cost
currencyA two-letter code for the currency.
productIdInternal ID for the product
variantIdInternal ID for the variant, if applicable (e.g. cart-related events)
skuThis could be a variant or product SKU depending on the situation.
isVariantIs this item a variant or a top-level product
variantNameIf a variant, this describes what the variant is, like “Size: Large”
productSkuThe product SKU, even if it is a variant
variantSkuThe variant SKU in cases where it is a variant
brandThe products brand
categoryThe primary category for the product. An object that includes ‘path’, a textual representation of the category as a breadcrumb, amongst other details about the category
categoriesAn array of all the category objects that this product is in.
quantityIf in a cart, how many
changeIf in a CartItemChanged event, this is the amount it changed. Negative means removals.
cart If in a CartItemChanged event, this provides the cart data

Here are some of the main properties for events with a cart or order.

PropertyDescription
orderIdNumerical id to identify the order
cartAmount
currency.codeA two-letter code for the currency.
itemsAn array of the products in the cart

Cancelling Events

Some events include parameters that let you cancel some actions

ParameterEffect
cancelBuiltInEventsAvailable on the core events fired by Tag Rocket. If set to true, it will not pass the event on to the built-in tags
cancelDataLayerEventsIf the GTM dataLayer feature is enabled, this parameter can be used to stop an event from being pushed onto the dataLayer.
cancelAvailable on Pending Tag events. If set to true, it will stop the pending event from being sent.

Loading Scripts with T.addScriptTag()

Many tag providers include a base script with cryptic code at the top that loads their tags. The code is typically designed to initialise a basic tag and then let the real tag load in the background so that it does not slow down the page. Here’s the Facebook tag with the script loading part highlighted in red.

<!-- Facebook Pixel Code -->
<script>
  !function(f,b,e,v,n,t,s)
  {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
  n.callMethod.apply(n,arguments):n.queue.push(arguments)};
  if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
  n.queue=[];t=b.createElement(e);t.async=!0;
  t.src=v;s=b.getElementsByTagName(e)[0];
  s.parentNode.insertBefore(t,s)}(window, document,'script',
  'https://connect.facebook.net/en_US/fbevents.js');
  fbq('init', '{your-pixel-id-goes-here}');
  fbq('track', 'PageView');
</script>

With Tag Rocket, we didn’t want to duplicate this loading code every time, so we created a function to handle it for us.

T.addScriptTag('https://tag.com/tag.js');

With this basic usage, it will load the script in the background, just like the Facebook tag does.

Some tags like to do custom things to the script element they add to the page. This function automatically sets async on, but you can also set your own attributed via the next parameter:

T.addScriptTag(‘https://tag.com/tag.js’, {id: ‘mytagid’, importance: ‘high’, crossorigin: ‘anonymous’});

This case sets the id for the script tag, which is a special case. If an element on the page already uses that id, the tag will not get added. A neat way to avoid duplicate tagging.

The final parameter of the function adds a whole lot of power. This can be a function you want to run once the script has loaded.

T.addScriptTag('https://tag.com/tag.js', {id: 'mytagid'}, function() {
  // USE THE SCRIPT NOW IT HAS LOADED
});

This means you can make sure your tag does not slow down the loading of a page while still being able to write code that uses it once it is ready.

Sometimes tags are made quite complex, like with Facebook. It does a bunch of initialisation steps before loading the real tag. We’re happy to help you decipher any tags you are wrangling with.

Pre Connecting to domains for Speed

Another function enables you to add a preconnect tag. This asks the browser to try and set up connections to domains as soon as possible because they will be needed later. This may save time when the first request to a domain is made.

T.addPreconnectTag(‘https://api.tag.com’);

Note that for privacy reasons this feature is disabled if the consent banner is enabled. This is because it can leak IP address information before the user has given consent.

Inserting CSS

The final helper function lets you insert CSS onto the page via a style tag.

T.addStyleTag(‘h1 {font-weight: 700;}’);

Public Parameters

The Tag Rocket object has a few public parameters that you can use. Within the script, these parameters can be accessed via the T variable. Some parameters are only set for specific events.

ParameterDescription
consentDetails about the current user’s consent settings.
logA log of the events fired, grouped by tags
orderAccess to the current order on the order completion page
pageTypeThe current pages type
productsDetails about products on the page.
productDetails about the product for a product page
tagsPipe separated list of the tags that have been enabled

Tag Rocket integrates with the BigCommerce consent system as well as a third-party Consetn Management Platforms (CMP) that support Google Consent Mode. You can see the users current consent state with the following console command:

TagRocket.consent 

The standard BigCommerce consent options are analytics, functional and targetingAdvertising. The consent data also includes some properties used by Tag Rocket to handle things like Consent Modes.

Tag Rocket first waits until it know consent nas been established. For the BigCommerce consent banner this is in the footer code. For CMPs there may be a delay as Tag Rocket waits for them to indicate the corrent consent states. When consent is established it fires a ‘ConsentChanged’ then a ‘ConsentEstablished’ event. After that, if the user changes their consent settings, another ‘ConsentChanged’ event is fired.

Tag Rocket supports CMPs via Google Consent Mode. If the CMP does not suppoort Google Consent Mode you will have to implement it. Setting consent is like this:

gtag("consent", "update", {
   "ad_storage": "granted",
   "ad_user_data": "granted",
   "ad_personalization": "granted",
   "analytics_storage": "granted",
   "functionality_storage": "granted",
   "personalization_storage": "granted",
   "security_storage": "granted"
});

Where each parameter is “granted” or “denied”. Tag Rocket listens for these consent commands and responds to them. e.g. enabling tags and sending events when the appropriate consent is granted. It also uses the BigCommerce API to tell BigCommerce about the new consent settings.

At this time BigCommerce does not support ad_user_data or ad_personalization. Please upvote my idea to add them.

How to set up consent mode with Tag Rocket and BigCommerce.

Getting Product IDs using the Tag Rocket format

The Tag Rocket admin interface provides a way to provide a format text for how a product ID is created. This syntax can also be used to get an ID via a function call:

var id = TagRocket.getProductId(destination, type, product, productFormat, variantFormat);
PropertyDescription
destinationA name for what is going to use this ID. Say the name of the channel you are using it in.
type Can be either ‘ItemId’ (variant) or ‘ItemGroupId’ (product) and relates to what type of ID is required.
productThe product object the ID needs to be extracted from.
productFormatText containing placeholders that are replaced by the products values. Placeholders are:
‘[[psku]]’ = Product SKU if available
‘[[pid]]’ = Product ID
‘[[vsku]]’ = Variant SKU if available
‘[[vid]]’ = Variant ID if available
‘[[vname]]’ = Variant Name if available

‘||’ can be used to supply an alternate format if the first format is not available. If all supplied formats fail then Product ID is used.
variantFormatIf set and it is a variant, an ‘ItemId’ type will use this format instead.

For example, to simply return a product id:

var id = TagRocket.getProductId(‘MyTag’, ‘ItemGroupId’, product, ‘[[pid]]’);

While this will return the product SKU if set, otherwise ‘P’ and the Product ID:

var id = TagRocket.getProductId('MyTag', 'ItemGroupId', product, '[[psku]]||P[[pid]]');

When related to a cart, the item being IDed could be a variant. We may want to get a variant value (say SKU) and the product value:

var itemGroupId = TagRocket.getProductId('MyTag', 'ItemGroupId', product, '[[psku]]||P[[pid]]');
var itemId = TagRocket.getProductId('MyTag', 'ItemId', product, '[[psku]]||P[[pid]]', '[[vsku]]');