Skip to main content

Javascript Tracker Core

Overview

The Snowplow JavaScript Tracker Core is an node module, available on npm, providing functionality common to both the server-side Snowplow Node.js Tracker and the client-side Snowplow JavaScript Tracker. It supports all the Snowplow event types. Custom contexts and timestamps can be added to all events.

It is automatically included when using the Node.js or JavaScript trackers.

It has two main types of method: setter methods and tracking methods. Setter methods like setUserId store a name-value pair to be added to all future events, while tracking methods like trackPageView track a specific event.

1. Setup

Compatibility

Current release: 3.14.0

The current release of Snowplow Tracker Core is compatible with Node.js versions 10, 12 and 14. Installing it requires npm or yarn.

Installation

Setting up the tracker should be straightforward if you are familiar with npm:

npm install snowplow-tracker-core

or

yarn add snowplow-tracker-core

2. Initialization

Requiring the module

Require the Snowplow Tracker Core module into your code like so:

var trackerCore = require('snowplow-tracker-core');

or if using ES Modules, import like so:

import { trackerCore } from 'snowplow-tracker-core';

Creating a tracker core instance

The tracker core constructor takes two parameters:

  • A boolean value indicating whether unstructured events and custom contexts should be base 64 encoded (which defaults to true)
  • An optional callback to be executed on every payload before it is returned
const t = trackerCore(false, console.log);

The above example would create a tracker core instance which doesn't use base 64 encoding and which logs all payloads it creates to the console.

3. Setter methods

The core instance maintains a dictionary called payloadPairs containing persistent name-value pairs which are added to every payload. You can interact with these through the following methods:

addPayloadPair()

Adds a single name-value pair to payloadPairs.

t.addPayloadPair('myKey', 'myValue');

addPayloadDict()

Adds all the name-value pairs in a dictionary to payloadPairs.

t.addPayloadDict({
key1: 'value1',
key2: 'value2'
});

resetPayloadPairs()

Creates a new dictionary of payload pairs, removing all pre-existing name-value pairs. If no argument is provided, creates an empty dictionary.

t.resetPayloadPairs({
key1: 'value1',
key2: 'value2'
});

Other setter methods

For convenience, other setter methods are provided for certain fields. They all use addPayloadPair.

Method nameKey addedExample
setTrackerVersiontvt.setTrackerVersion('js-3.0.0');
setTrackerNamespacetnat.setTrackerNamespace('cloudfront-1');
setAppIdaidt.setAppId('my-node-application');
setPlatformpt.setPlatform('web');
setUserIduidt.setUserId('user-427')
setScreenResolutionrest.setScreenResolution(800, 600)
setViewportvpt.setViewport(307,250)
setColorDepthcdt.setColorDepth(24)
setTimezonetzt.setTimezone('Europe/London')
setIpAddressipt.setIpAddress('37.347.12.457')

Example usage

Some calls to setter methds, along with comments indicating the current state of the payloadPairs dictionary:

var snowplowTrackerCore = require('snowplow-tracker-core');
var t = snowplowTrackerCore(); // {}
t.addPayloadPair('a', 'one'); // {a: 'one'}
t.addPayloadDict({
b: 'two',
c: 'three'
}); // {a: 'one', b: 'two', c: 'three'}
t.resetPayloadPairs(); // {}
t.setPlatform('srv'); // {p: 'srv'}
t.setPlatform('pc'); // {p: 'pc'}
t.setViewport(600, 400); // {p: 'pc', 'vp': 600x400}
t.resetPayloadPairs({
d: 'four',
e: 'five'
}); // {d: 'four', e: 'five'}

4. Tracking methods

Common features

Any method whose name starts with "track..." is a tracking method which creates a payload for a single Snowplow event. The tracking methods have certain features in common.

Custom contexts

Each tracking method's penultimate argument is an optional array of custom context dictionaries.

Example:

var myContexts = [{
'schema': 'iglu:com.acme/viewed_product/1-0-1',
'data': {
'price': 13,
'name': 'cyan paint'
}
},
{
'schema': 'iglu:com.acme/page_type/1-0-1',
'data': {
'type': 'testPage'
}
}];

t.trackScreenView('title screen', 's-1342', myContexts);

Timestamp argument

Each tracking method's final argument is an optional timestamp. It should be in milliseconds since the Unix epoch - the same format generated by new Date().getTime(). If you don't provide a timestamp for an event, the current time will be used.

Return values

When called, a tracker method will assemble a payload dictionary based on the arguments passed to it and the payloadPairs object, and will add a version 4 UUID. If you provided a callback function when constructing the core instance, that function will be passed the payload. (For example, the callback could be used to convert the payload to a querystring and send it to a Snowplow collector.) The payload will then be returned.

trackScreenView()

ArgumentDescriptionRequired?Type
nameHuman-readable name for this screenNoNon-empty string
idUnique identifier for this screenNoString
contextCustom contextNoArray
tstampWhen the screen was viewedNoPositive integer

name and id are not individually required, but you must provide at least one of them.

Example:

t.trackScreenView("HUD > Save Game", "screen23", null, 1368725287000);

trackPageView()

ArgumentDescriptionRequired?Type
pageUrlThe URL of the pageYesNon-empty string
pageTitleThe title of the pageNoString
referrerThe address which linked to the pageNoString
contextCustom contextNoArray
tstampWhen the screen was viewedNoPositive integer

Example:

t.trackPageView("www.example.com", "example", "www.referrer.com");

trackEcommerceTransaction()

ArgumentDescriptionRequired?Type
orderIdID of the eCommerce transactionYesNon-empty string
affiliationTransaction affiliationNoString
totalValueTotal transaction valueYesNumber
taxValueTransaction tax valueNoNumber
shippingDelivery cost chargedNoNumber
cityDelivery address cityNoString
stateDelivery address stateNoString
countryDelivery address countryNoString
currencyCurrencyNoString
contextCustom contextNoArray
tstampWhen the transaction event occurredNoPositive integer

Example:

t.trackEcommerceTransaction(
"order-456", // order ID
null, // affiliation
142, // total
20, // tax
12.99, // shipping
"London", // city
null, // state
"United Kingdom", // country
"GBP" // currency
);

trackEcommerceTransactionItem()

FieldDescriptionRequired?Type
orderIdID of the eCommerce transactionYesNon-empty string
skuItem SKUYesNon-empty string
nameItem nameNoString
categoryItem categoryNoString
priceItem priceYesNumber
quantityItem quantityYesInt
currencyCurrencyNoString
contextCustom context for the eventNoArray
tstampWhen the transaction event occurredNoPositive integer

Example:

t.trackEcommerceTransactionItem(
"order-456", // order ID
"570634", // SKU
"red hat", // name
"headgear", // category
10, // price
1, // quantity
"GBP" // currency
);

trackStructEvent()

ArgumentDescriptionRequired?Type
categoryThe grouping of structured events which this action belongs toYesNon-empty string
actionDefines the type of user interaction which this event involvesYesNon-empty string
labelA string to provide additional dimensions to the event dataNoString
propertyA string describing the object or the action performed on itNoString
valueA value to provide numerical data about the eventNoNumber
contextCustom context for the eventNoArray
tstampWhen the structured event occurredNoPositive integer

Example:

t.trackStructEvent("shop", "add-to-basket", null, "pcs", 2);

trackUnstructEvent()

ArgumentDescriptionRequired?Type
propertiesThe properties of the eventYesJSON
contextCustom context for the eventNoArray
tstampWhen the unstructured event occurredNoPositive integer

Example:

t.trackUnstructEvent({
"schema": "com.example_company/save-game/jsonschema/1.0.2",
"data": {
"save_id": "4321",
"level": 23,
"difficultyLevel": "HARD",
"dl_content": true
}
})

trackLinkClick()

FieldDescriptionRequired?Type
targetUrlURL of the linkYesNon-empty string
elementIdHTML id of the link elementNoNon-empty string
elementClassesHTML classes of the link elementNoArray
elementTargetHTML target of the link elementNoString
contextCustom context for the eventNoArray
tstampItem priceNoNumber
t.trackLinkClick(
'http://www.example.com', // URL
'first header', // id
['header'], // classes
'_blank' // target
);

trackAdImpression()

NameDescriptionRequired?Type
impressionIdIdentifier for the particular impression instanceNostring
costModelThe cost model for the campaign: 'cpc', 'cpm', or 'cpa'Nostring
costAd costNonumber
targetUrlThe destination URLNostring
bannerIdAdserver identifier for the ad banner (creative) being displayedNostring
zoneIdAdserver identifier for the zone where the ad banner is locatedNostring
advertiserIDAdserver identifier for the advertiser which the campaign belongs toNostring
campaignIdAdserver identifier for the ad campaign which the banner belongs toNostring

Example:

t.trackAdImpression(
'67965967893', // impressionId
'cpm', // costModel - 'cpa', 'cpc', or 'cpm'
5.5, // cost
'http://www.example.com', // targetUrl
'23', // bannerId
'7', // zoneId
'201', // advertiserId
'12' // campaignId
);

trackAdClick()

NameDescriptionRequired?Type
targetUrlThe destination URLYesstring
clickIdIdentifier for the particular click instanceNostring
costModelThe cost model for the campaign: 'cpc', 'cpm', or 'cpa'Nostring
costAd costNonumber
bannerIdAdserver identifier for the ad banner (creative) being displayedNostring
zoneIdAdserver identifier for the zone where the ad banner is locatedNostring
advertiserIDAdserver identifier for the advertiser which the campaign belongs toNostring
campaignIdAdserver identifier for the ad campaign which the banner belongsNotostring

Example:

t.trackAdClick(
'http://www.example.com', // targetUrl
'12243253', // clickId
'cpm', // costModel
2.5, // cost
'23', // bannerId
'7', // zoneId
'67965967893', // impressionId - the same as in trackAdImpression
'201', // advertiserId
'12' // campaignId
);

trackAdConversion()

NameDescriptionRequired?Type
conversionIdIdentifier for the particular conversion instanceNostring
costModelThe cost model for the campaign: 'cpc', 'cpm', or 'cpa'Nostring
costAd costNonumber
categoryConversion categoryNonumber
actionThe type of user interaction, e.g. 'purchase'Nostring
propertyDescribes the object of the conversionNostring
initialValueHow much the conversion is initially worthNonumber
advertiserIDAdserver identifier for the advertiser which the campaign belongs toNostring
campaignIdAdserver identifier for the ad campaign which the banner belongs toNostring

Example:

t.trackAdConversion(
'743560297', // conversionId
10, // cost
'ecommerce', // category
'purchase', // action
'', // property
99, // initialValue - how much the conversion is initially worth
'201', // advertiserId
'cpa', // costModel
'12' // campaignId
);

trackConsentGranted()

NameDescriptionRequired?Type
idIdentifier for the document granting consentYesNumber
versionVersion of the document granting consentYesNumber
nameName of the document granting consentNoString
descriptionDescription of the document granting consentNoString
expiryDate-time string specifying when consent document expiresNoString
contextCustom context for the eventNoArray
tstampWhen the event occurredNoPositive integer

Example:

t.trackConsentGranted(
743560297, // id
10, // version
'consent-document', // name
'a document granting consent', // description
'2020-11-21T08:00:00.000Z' // expiry
);

trackConsentWithdrawn()

NameDescriptionRequired?Type
idIdentifier for the document withdrawing consentYesNumber
versionVersion of the document withdrawing consentYesNumber
nameName of the document withdrawing consentNoString
descriptionDescription of the document withdrawing consentNoString
allSpecifies whether all consent should be withdrawnNoBoolean
contextCustom context for the eventNoArray
tstampWhen the event occurredNoPositive integer

Example:

t.trackConsentWithdrawn(
743560297, // id
10, // version
'consent-document', // name
'a document withdrawing consent', // description
'false' // all
);
Was this page helpful?