JS SDK V3

Background

The V3 JS SDK is the newest iteration of the JS SDK. By hosting it on CloudFlare Workers, the V3 SDK offers the same functionality as the previous JS SDK at a significantly higher speed.

Documentation for the previous version of the sdk can be found here.

Installation

The V3 JS SDK can be installed as a synchronous loading script. We recommend installing it as high as possible in your <head> tag, ideally before any other analytics tools or other scripts are loaded.

To install the Taplytics JS SDK synchronously, use the following script tag. Replace {JS_SDK_KEY} in the src url with your own JS SDK Key from the Taplytics web dashboard:

<script type="text/javascript" src="https://js.taplytics.com/jssdk/{JS_SDK_KEY}.min.js" referrerpolicy="no-referrer-when-downgrade"></script>

By default, this will trigger Taplytics.page(), called with no parameters. This can be disabled by using the auto_page_view query parameter and setting it to false. More info in the Start Options section. Including referrerpolicy is highly recommended for Visual Web Editor users but can be omitted if necessary.

Example:
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <!-- Add other meta information -->
        <!-- Add stylesheets -->
        <script type="text/javascript" src="https://js.taplytics.com/jssdk/{JS_SDK_Key}.min.js" referrerpolicy="no-referrer-when-downgrade"></script>
        <!-- Add other scripts and content -->
    </head>
    <body>
    ...
    </body>
</html>

Onload Event

Taplytics emits a taplytics:loaded event when the V3 SDK has finished loading. Use this to guarantee that other code runs after Taplytics has initialized.

Example:
<script type="text/javascript">
	document.addEventListener('taplytics:loaded', function () {
		console.log('do something cool');
	});
</script>
<script type="text/javascript" src="https://js.taplytics.com/jssdk/{JS_SDK_KEY}.min.js" referrerpolicy="no-referrer-when-downgrade"></script>

Start Options

The following start options are available when installing the SDK script tag:

OptionTypeDescriptionDefault Value
spa_modeBooleanEnables automatic page tracking of route based navigation within single page applications (ie, react router, ng-router)false
auto_page_viewBooleanCalls Taplytics.page() with no arguments as soon as the SDK is loadedtrue

Example:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <!-- Add other meta information -->
        <!-- Add stylesheets -->
        <script type="text/javascript" src="https://js.taplytics.com/jssdk/{JS_SDK_Key}.min.js?spa_mode=true&auto_page_view=true" referrerpolicy="no-referrer-when-downgrade"></script>
        <!-- Add other scripts and content -->
    </head>
    <body>
    ...
    </body>
</html>

User Attributes on First Launch

User Attributes added to the V3 initialization script url will be available for segmentation on the first launch of the site. Any attributes added via identify will be used for segmentation on the next available initialization call or session.

All attribute data must be added as a query string and can be added as it's own parameter.

<script type="text/javascript" src="https://js.taplytics.com/jssdk/{JS_SDK_Key}.min.js?auto_page_view=false&user_id=user123&isEmployee=yes" referrerpolicy="no-referrer-when-downgrade"></script>

Custom Domain Proxy

Implement a Custom Domain Proxy to bypass 3rd party cookie blockers that block requests to the Taplytics SDKs and APIs. The Custom Domain Proxy allows all Taplytics requests to be sent through your recognized domain. A CNAME hostname and certificate will need to be created in order to leverage this feature and both options can be customized if needed.

  1. Identifying a Hostname and Certificate Owner
    The first step involves identifying a hostname to use as the CNAME to Taplytics’ service as well as deciding whether you'd like Taplytics to manage a new certificate or manage the certificate yourselves.
  • If there is more than one service in use, each one will need a unique CNAME.
  • If you'd like to create a custom hostname, you'll need to provide us with the hostname. Otherwise, Taplytics will create one for you.
  • If you need to manage the certificate instead of having Taplytics manage the renewal, you'll need to provide both the Certificate and Private Key for the certificate(s) that you've created.
  1. Setup Hostname and Certificate
    Taplytics will begin the setup with the certificate and hostname. We can start this process immediately if you do not need to customize your hostname or certificate.

  2. DNS Validation
    Once the setup is complete, two DNS record will be provided by Taplytics and you will need to add those records to your DNS provider (TXT validation records).

  3. Additional Setup Step
    Once validation is complete, there may be an extra step involved here with Taplytics depending on your SDK configuration. Taplytics will let you know if this is needed.

  4. Creating a CNAME
    Once all steps are complete, Taplytics will send the details for the DNS CNAME. Once added, the service will be immediately available at the given hostname. You can use this hostname for all requests to Taplytics instead.

  5. Self-Managed Certificates
    If you are managing your own certificate, please provide Taplytics with any new certificates if they expire in the future. Failure to do so will result in an invalid certificate error.

If you have any questions regarding this process, please reach out to your CSM or to our support team.

Usage

Here are the APIs that the V3 JS SDK exposes:

FunctionDescription
identifyIdentify User
trackTrack event
pageTrack page views
resetReset User
runningExperimentsGet running experiments
featureFlagEnabledGet feature flag enabled
variableGet dynamic variable
codeBlockRun code block

identify

Identifies the user that's currently on the page. This helps you track your users and allows you to add custom attributes that can be used for segmentation. If running on cross-platform, it also helps link their activity on the web with their activity on other platforms (iOS, Android).

You should call this function as soon as a user signs up or has logged in.

Method Signature

Taplytics.identify(user_attributes)

Arguments
  • user_attributes (Object): User Attributes object, containing the following fields:
    • user_id (string/integer): User's ID (optional).
    • email (string): User's Email (optional).
    • gender (string): User's Gender, one of male or female (optional).
    • age (integer): User's age as a number (optional).
    • firstName (integer): User's first name (optional).
    • lastName (integer): User's last name (optional).
    • ... (string/integer/object): Any extra custom attributes (optional).
Returns

(Promise): Returns a promise containing the result of the call to the worker.

Example
// With just a few named user attributes
Taplytics.identify({
    user_id: "user123",
    email: "[email protected]",
    age: 23,
    gender: "male",
    firstName: "Nemo",
    lastName: "Dory"
})
// Return: Promise {<pending>}

// With non-named custom attributes
Taplytics.identify({
    loyalty_group: "very_loyal",
    purchases_count: 15,
    friends_count: 800
})
// Return: Promise {<pending>}

track

Tracks the occurrence of an event for the current visitor (anonymous or identified).

Note that value is identified as revenue. If you want to send extra information about the event itself, send it through event_attributes.

Method Signature

Taplytics.track(eventName, value, event_attributes)

Arguments
  • eventName (string): Event name.
  • value (integer/double): Value of the event.
  • event_attributes (Object): Event attributes to be sent with the event.
Returns

(Promise): Returns a promise containing the result of the call to the worker.

Example
// Simple event
Taplytics.track("Clicked Button")
// Return: Promise {<pending>}

// Event with value (revenue)
Taplytics.track("Purchased", 180.50)
// Return: Promise {<pending>}

// Event with value (revenue) and extra attributes
Taplytics.track("Purchased", 180.50, {
    product_id: 100,
    product_name: "Shirt"
})
// Return: Promise {<pending>}

// Event with just attributes and no value
Taplytics.track("Finished Tutorial", null, {
    time_on_tutorial: 100
})
// Return: Promise {<pending>}

page

Tracks a new page and time spent on previous page if this is not the first page tracked.

You can call it manually yourself to structure the page view events, as well as when you have a single page Javascript application that does its own routing.

Currently, we do not listen on window.History state change events to do this automatically.

Method Signature

Taplytics.page(category, name, page_attributes)

Arguments
  • category (string): The category of the page.
  • name (string): The name of the page.
  • page_attributes (Object): Custom defined attributes for the page.
Returns

(Promise): Returns a promise containing the result of the call to the worker.

Example
// Track a page view with no attributes
Taplytics.page()
// Return: Promise {<pending>}

// Track it by setting a name
Taplytics.page(null, "Page Name")
// Return: Promise {<pending>}

// Track a page view with a category and a name
Taplytics.page("Product Listings", "Shirts")
// Return: Promise {<pending>}

// Track a page view with a name and attributes
Taplytics.page(null, "Shirts Page", {
	products_count: 150
})
// Return: Promise {<pending>}

// Track a page view with a name, a category, and attributes
Taplytics.page("Product Listings", "Shirts", {
	products_count: 150
})
// Return: Promise {<pending>}

reset

Resets the user object and assumes the visitor is now anonymous. This can be used to detach the visitor from the user that you had used identify on earlier in the session. Calling this method also refetches the sdk with new config for the anonymous visitor.

Method Signature

Taplytics.reset()

Arguments

None.

Returns

(Promise): Returns a promise containing the result of the call to the worker.

Example
Taplytics.reset()
// Return: Promise {<pending>}

runningExperiments

Returns the running experiments and corresponding variation that the current user is bucketed in synchronously.

Method Signature

Taplytics.runningExperiments()

Arguments

None.

Returns

(Object): A map of experiment names to the variation name that the current user is bucketed in.

Example
Taplytics.runningExperiments()
// Return: { "Experiment 1": "baseline", "Experiment 2": "Variation 1" }

featureFlagEnabled

Returns whether a feature flag is enabled for the current user.

Method Signature

Taplytics.featureFlagEnabled(name, [defaultValue=false])

Arguments
  • name (string): The name of the feature flag.
  • defaultValue (boolean): The default value of the feature flag if it does not exist. Defaults to false.
Returns

(boolean): Whether the feature flag corresponding to name is enabled for the current user. Enabled means that the feature flag exists, is turned on in the Taplytics dashboard, and the current user satisfies the conditions of the feature flag.

Example
Taplytics.featureFlagEnabled("enabledFeatureFlag")
// Return: True

Taplytics.featureFlagEnabled("disabledFeatureFlag")
// Return: False

Taplytics.featureFlagEnabled("featureFlag", true)
// Default set to True

getAllVariables

Returns an array of Taplytics dynamic variable objects that are being served to the user and controlled by your running experiments.

🚧

Warning - Debug Use Only

This method is for debugging purposes only. Please do not use this method as a means to retrieve variable values for use.

Method Signature

Taplytics.getAllVariables()

Arguments

None.

Returns

(Array): An array of variable objects currently being served to the user.

Example

Taplytics.getAllVariables()
// Return: [{name: 'stringVar', variableType: 'String', value: 'test', _id: '123456789'}, ...]

variable

Returns a Taplytics Dynamic Variable value that is controlled by your running experiments and configured through the Taplytics dashboard.

Method Signature

Taplytics.variable(name, defaultValue)

Arguments
  • name (string): The name of the variable to retrieve.
  • defaultValue (string/number/boolean): Default return value if the variable does not exist.
Returns

(string/number/boolean): The value of the dynamic variable by name if it exists, otherwise returns defaultValue.

Example
Taplytics.variable("existingVarName", "default")
// Return: "existingVarValue"

Taplytics.variable("nonExistingVarName", "default")
// Return: "default"

codeBlock

Creates a Taplytics Code Block that will be run if enabled for the running experiment/variation through the Taplytics dashboard.

Method Signature

Taplytics.codeBlock(name, codeBlock)

Arguments
  • name (string): The name of the code block.
  • codeBlock (function): The code block to be called if enabled for the experiment's variation.
Returns

None.

Example
Taplytics.codeBlock("enabledCodeBlock", function() {
    console.log("This code block is enabled for my experiment and variation!");
    // run extra code here
})
// Logs: "This code block is enabled for my experiment and variation!"
// Return: undefined

Taplytics.codeBlock("nonEnabledCodeBlock", function() {
    console.log("This code block is either not enabled or does not exist!");
    // run extra code here
})
// Return: undefined