JavaScript SDK Quickstart

TD JavaScript SDK (TD JS SDK) allows Treasure Data to store first-party cookies on your domain’s website and to track your website’s users across the other platforms and collect information. By using the TD JS SDK, you don’t have to install anything server-side to track website activities.

SDK V3.x

If you are using the td-js-sdk v2.x please upgrade today to using v3.x

Pre-Requisites

  • Treasure Data Write-Only API Key
  • Database and table created on your TD account.

Setup

You can host a custom built version of the JavaScript SDK on your website or your preferred CDN. For the purpose of this quickstart we will be using a pre-built publically hosted version.

Install

Add the JavaScript SDK to your website.

JS Scriptnpm
Copy
Copied
<script type="text/javascript">
!function(t,e){if(void 0===e[t]){e[t]=function(){e[t].clients.push(this),this._init=[Array.prototype.slice.call(arguments)]},e[t].clients=[];for(var r=["addRecord","blockEvents","fetchServerCookie","fetchGlobalID","fetchUserSegments","resetUUID","ready","setSignedMode","setAnonymousMode","set","trackEvent","trackPageview","trackClicks","unblockEvents"],s=0;s<r.length;s++){var c=r[s];e[t].prototype[c]=function(t){return function(){return this["_"+t]=this["_"+t]||[],this["_"+t].push(Array.prototype.slice.call(arguments)),this}}(c)}var n=document.createElement("script");n.type="text/javascript",n.async=!0,n.src=("https:"===document.location.protocol?"https:":"http:")+"//cdn.treasuredata.com/sdk/3.0/td.min.js";var o=document.getElementsByTagName("script")[0];o.parentNode.insertBefore(n,o)}}("Treasure",this);
</script>
Copy
Copied
// Does not work with NoseJS. Browser only.
$ npm install --save td-js-sdk

// Exports Treasure class using CommonJS. The entry point is lib/treasure.js. 
// Usable with a build tool such as Browserify or Webpack.
var Treasure = require('td-js-sdk')

Initialize

The JS SDK library works by creating an instance per database, and sending data into tables.

Initializing the SDK is as simple as:

Copy
Copied
  var foo = new Treasure({
    database: 'database_name',
    writeKey: 'your_write_only_api_key'
  });
Write-Only API Key

It is strongly reccomended to use a write-only API Key.

Click here to see how to get a write-only API Key.

1) Login to Treasure Data Console and go to the API Key page.

2) If you dont already have a write-only API Key then create one by clicking on the Top Right, click on Actions -> Create API Key.

3) Name the new API Key and make sure to select Write-Only as the type.

4) Copy / Paste your new Write-Only API Key into the project.

If you're an administrator, databases will automatically be created for you. Otherwise you'll need to ask an administrator to create the database and grant you import only or full access on it, otherwise you will be unable to send events.

Basic Use

Now that we have an object initialized we can send events to Treasure Data. For a fully customized event record use the addRecord function. Later we will discuss how to use the trackEvent and trackPageviews functions to log standard metrics.

Record an Event

Copy
Copied
// Configure an instance for your database
var company = new Treasure({...});

// Create a data object with the properties you want to send
var sale = {
  itemId: 101,
  saleId: 10,
  userId: 1
};

// Send it to the 'sales' table
company.addRecord('sales', sale);

Send as many events as you like. Each event will fire off asynchronously.

Track events + standard info

The TD JavaScript SDK provides a way to track page impressions and events, as well as standard client information.

Client ID and Storage

Each client requires a uuid. It may be set explicitly by setting clientId on the configuration object. Otherwise the JS SDK will search the cookies for a previously set uuid. If unable to find one, a uuid will be generated.

A cookie is set in order to track the client across sessions.

Page impressions

Tracking page view impressions is as easy as:

Copy
Copied
/* insert javascript snippet */
var td = new Treasure({...});
td.trackPageview('pageviews');

This will send all the tracked information to the pageviews table.

Event tracking

In addition to tracking pageviews, you can track events. The syntax is similar to addRecord, with the difference being that trackEvent will include all the tracked information listed in the next section.

Copy
Copied
var td = new Treasure({});

var buttonEvent1 = function () {
  td.trackEvent('button', {
    number: 1
  });

  // doButtonEvent(1);
};

var buttonEvent2 = function () {
  td.trackEvent('button', {
    number: 2
  });

  // doButtonEvent(2);
};

Tracked information

Every time a track functions is called, the following information is sent:

Event Name Description
td_version td-js-sdk's version
td_client_id client's uuid*
td_charset character set
td_description description meta tag
td_language browser language
td_color screen color depth
td_screen screen resolution
td_viewport viewport size
td_title document title
td_url document url
td_user_agent browser user agent
td_platform browser platform
td_host document host
td_path document pathname
td_referrer document referrer
td_ip request IP (server)*
td_browser client browser (server)
td_browser_version client browser version (server)
td_os client operating system (server)
td_os_version client operating system version (server)

Certain values cannot be obtained from the browser. For these values, we send matching keys and values, and the server replaces the values upon receipt. For examples: {"td_ip": "td_ip"} is sent by the browser, and the server will update it to something like {"td_ip": "1.2.3.4"}

All server values except td_ip are found by parsing the user-agent string. This is done server-side to ensure that it can be kept up to date.

* This is a personally identifiable column, and will be affected by whether or not the user is in Signed or Anonymous Mode.

Advanced Use

Default values

Set default values on a table by using Treasure.set(). Set default values on all tables by passing $global as the table name.

Using Treasure.get() you can view all global properties by passing the table name $global.

When a record is sent, an empty record object is created and properties are applied to it in the following order:

  1. $global properties are applied to record object
  2. Table properties are applied to record object, overwriting $global properties
  3. Record properties passed to addRecord function are applied to record object, overwriting table properties

Data Privacy

Treasure Data's SDK enables compliance with many common requirements of the EU's GDPR laws. Several methods have been enabled to help you comply with newer and more stringent data privacy policies:

  • blockEvents / unblockEvents - non-argument methods to shut down or re-enable all sending of events to Treasure Data. No messages will be sent, no calls will be cached. Default is for events to be unblocked. See documentation around these methods: blockEvents, unblockEvents, areEventsBlocked
  • setSignedMode - non-argument method to enter "Signed Mode", where some PII may be collected automatically by the SDK. The data sent to Treasure Data will include td_ip, td_client_id, and td_global_id, if specified. See documentation around this method: setSignedMode
  • setAnonymousMode - non-argument method to enter "Anonymous Mode", where PII will not be collected automatically by the SDK. These data will specifically omit td_ip, td_client_id, and td_global_id, if specified. This is the default behavior. See documentation around this method: setAnonymousMode
  • resetUUID - method to reset the td_client_id value. This will overwrite the original value stored on the user's cookie, and will likely appear in your data as a brand-new user. It's possible to specify a client ID while resetting, as well as custom expiration times by passing in appropriate values. See documentation around this method: resetUUID

A new configuration property has also been added: config.startInSignedMode. This configuration option tells the SDK that, if no express decision has been made on whether the user wants to be in Signed or Anonymous modes, it should default into Signed Mode. The default behavior is to default the user into Anonymous Mode.

Examples

Suppose a user first accesses your site, and you need to know if they have agreed to tracking for marketing purposes. You contract with a Consent Management Vendor to maintain this information, and want to set appropriate values once you know their consent information.

Copy
Copied
var foo = new Treasure({
  database: 'foo',
  writeKey: 'your_write_only_key'
});
td.trackClicks()

var successConsentCallback = function (consented) {
  if (consented) {
    td.setSignedMode()
  } else {
    td.setAnonymousMode()
  }
}

var failureConsentCallback = function () {
  // error occurred, consent unknown
  td.setAnonymousMode()
}

ConsentManagementVendor.getConsent(userId, successConsentCallback, failureConsentCallback)

In this scenario, the Consent Management Vendor returns a true or false value in the callback based on whether or not the user associated with the userId has consented to their PII being used for marketing purposes. Non-PII data may still be collected.

Now suppose your Consent Management Vendor provides strings based on the consent level: MARKETING, NON-MARKETING, REFUSED, for "Consented to PII being used for marketing purposes", "Consented to data being collected for non-marketing purposes", and "Refused all data collection". There's only a minor change to make in the successConsentCallback:

Copy
Copied
var successConsentCallback = function (consented) {
  if (consented === 'MARKETING') {
    td.unblockEvents()
    td.setSignedMode()
  } else if (consented === 'NON-MARKETING') {
    td.unblockEvents()
    td.setAnonymousMode()
  } else if (consented === 'REFUSED') {
    td.blockEvents()
  }
}

This way, when emerging from Signed or Anonymous mode, you can be sure you'll actually be collecting data in Treasure Data. If the customer has refused all tracking, their events are blocked, and this status will be persisted across page refreshes.

SameSite cookies

warning

If you see the warnings about SameSite cookies in Chrome or Firefox, please upgrade the TreasureData JS SDK to version of at least 2.4.2

In recent releases of Chrome and Firefox, they begin enforcing a new secure-by-default cookie classification system, treating cookies that have no declared SameSite value as SameSite=Lax cookies. Only cookies set as SameSite=None; Secure will be available in third-party contexts, provided they are being accessed from secure connections.

This affects the td_client_id and td_global_id cookies in previous versions of TreasureData JS SDK (< 2.4.2) as they are not set as secured cookies.

Starting from version 2.4.2, TreasureData JS SDK uses SameSite=None; Secure cookies as default to adapt the new cookie enforcement.

For more information see the following:

Further Reading

Now that you have the JavaScript SDK integrated into your website or application here are some more resources to keep going.

Support
Copyright © 2021 Treasure Data, Inc. (or its affiliates). All rights reserved.