Singular Website SDK: Native Integration

 

The Singular Website SDK is an enterprise feature. If you're interested in using this feature, reach out to your Customer Success Manager.

The Singular Website SDK allows you to attribute website activities to marketing touchpoints and to track user events within your website. It is also a key component in Singular’s cross-device attribution solution, making it possible to analyze user journeys and calculate cross-platform LTV and ROAS.

To learn more, see our Cross-Device Attribution FAQ and Web Attribution FAQ.

In addition to the native JavaScript version described here, the Singular Website SDK is also available as a Google Tag Manager Template.

Browser Compatibility:

Chrome: 15+ Edge: 15+ Internet Explorer: 10+
Safari: 5.1+ Firefox: 6+ Opera: 15+

Adding the SDK Script to Your Site

Use one of the following methods to set up the SDK on your website or web app.

Linking to the Script on Singular's CDN

In this method, Singular hosts the SDK JavaScript code on Singular's CDN.

Add the following code inside the <head> tag of each page you want to track:

<head>
    <!-- Using the latest SDK version   -->
    <script src="https://web-sdk-cdn.singular.net/singular-sdk/latest/singular-sdk.js">
    </script>
</head>

Note: The code above links to the latest version of the SDK. If you want to use a specific version of the SDK, use the following code instead:

<head>
    <!-- Using a fixed SDK version   -->
    <script src="https://web-sdk-cdn.singular.net/singular-sdk/1.4.1/singular-sdk.js">
    </script>
</head>

Setting Up Using NPM

  1. Run npm i singular-sdk in your project’s root directory, or add "singular-sdk": "^1.4.1" to the dependencies section in your package.json file and then run npm install.
  2. Add the following code in the scripts you want to use the SDK.
import {singularSdk, SingularConfig} from "singular-sdk";

Initializing the SDK

The SDK initialization code should be called every time a page is loaded. It is a prerequisite to all Singular attribution functionality, and it also:

  • Creates a new user session when a user enters the site with new advertising data or when the session timeout has passed.
  • Sends a new "page visit" event to Singular

Page visits events and user sessions are used to calculate user retention and enable re-engagement attribution.

1. Constructing the SingularConfig Object

Before you can initialize the SDK, you have to create a SingularConfig object. This object will contain:

  • SDK Key and SDK Secret: To find these, log into your Singular account and go to "Developer Tools > SDK Integration > SDK Keys".
  • Your Product ID: A name for your website. We recommend using the reverse DNS notation of your main web domain, e.g., “com.example”. This will be used to identify your website throughout the Singular platform. This value must also match the App bundleID on the Apps Page in the Singular platform.
  • Optionally, any SDK preferences you may want to set (read on for details).

To create a basic SingularConfig object use this code:

const config = new SingularConfig(sdkKey, sdkSecret, productId);

However, you will probably want to add settings to enable various capabilities offered by Singular.

To add settings, you will use the SingularConfig object's ".with" methods. For example:

// Configure the SDK to pass the user ID to Singular
const config = new SingularConfig(sdkKey, sdkSecret, productId)
    .withCustomUserId(userId);

SingularConfig Method Reference

Here are all the available ".with" methods.

Method Description Learn More
.withCustomUserId(customId) Send the user ID to Singular Setting the User ID
.withProductName(productName) An optional display name for the product  
.withLogLevel(logLevel) Configure the logging level: 0 - None (Default); 1 - Warn; 2 - Info; 3 - Debug.  
.withSessionTimeoutInMinutes (timeout) Set the session timeout in minutes (default: 30 minutes)

 

.withAutoPersistentSingularDeviceId (domain) Enable automatic cross-subdomain tracking Auto-Persist using Cookies

.withPersistentSingularDeviceId (singularDeviceId)

Enable manual cross-subdomain tracking Set Singular Device ID Manually
.withInitFinishedCallback(callback) Invoke a callback when SDK initialization is complete Invoking a Callback Function when Initialization is Complete

2. Initializing Singular

After creating the SingularConfig object, initialize Singular using the init method, passing the config object.

The init method can be called at any point in the code but must get called before any event is reported. We recommend calling init during the loading of each page you want to track.

init Method
Description Initialize the SDK with configuration options set in the SingularConfig object.
Signature init(config)
Usage Example
function initSingular() {
    const config = new SingularConfig(sdkKey, 
sdkSecret, productId); singularSdk.init(config); }

Important: For Single Page Applications (SPAs), call singularSdk.pageVisit() every time you route to a different page. Do not call singularSdk.pageVisit() on the first page that is loaded since singularSdk.init already reports a page visit.

Invoking a Callback Function when Initialization is Complete

To set a callback function to be invoked once initialization is done, use .withInitFinishedCallback(callback) on the SingularConfig object.

withInitFinishedCallback Method
Description Sets the callback which will be invoked once the initialization process is finished.
Signature withInitFinishedCallback(callback)
Usage Example
function initSingular() {      
  const config = new SingularConfig(sdkKey, sdkSecret, productId)
    .withInitFinishedCallback(initParams=> {
      // This callback will be called when the init method has finished

      // You can get Singular Device id here
      const singularDeviceId = initParams.singularDeviceId;
    });
singularSdk.init(config);
}

Sending the User ID to Singular (Optional)

You may send your internal User ID to Singular using a Singular SDK method.

Note: If you use Singular's Cross-Device solution, you must collect the User ID across all platforms.

  • The User ID can be any identifier and should not expose PII (Personally Identifiable Information). For example, you should not use a User's email address, username, or phone number. Singular recommends using a hashed value unique only to your first-party data.
  • The User ID value passed to Singular should also be the same internal User ID you capture across all platforms (Web/Mobile/PC/Console/Offline).
  • Singular will include the User ID in user-level exports, ETL, and Internal BI postbacks (if configured). The User ID is first-party data, and Singular does not share it with other parties.
  • The User ID value, when set with the Singular SDK Method, will persist until it is unset using the logout() method or until the browser local storage is deleted. Closing or refreshing the website does not unset the User ID.
  • In private/incognito mode, the SDK cannot persist the user ID because the browser automatically deletes the local storage when it is closed.

To set the User ID, use the login() method. To unset it (for example, if the User "logs out" of the account), call logout() method.

Note: If multiple Users use a single device, we recommend implementing a logout flow to set and unset the User ID for each login and logout.

If you already know the user ID when the Singular SDK is initialized on the website, set the User ID in the config object. This way, Singular can have the User ID from the first Session. However, the User ID is typically unavailable until the User registers or performs a login. In that case, call login() after the registration flow is complete.

SingularSDK login() Method
Description Send the user ID to Singular.
Signature login(customUserId)
Usage Example
singularSdk.login("custom_user_id");
SingularSDK logout() Method
Description Unset the user ID that has been sent to Singular.
Signature logout()
Usage Example
singularSdk.logout();

Optional: Custom User ID Device Mapping

Important: This advanced Enterprise feature is only available in exceptional cases. Please consult with one of Singular’s Solution Engineers before implementing it.

Singular can receive additional mobile event tracking data via a server-to-server integration. To utilize this feature, you must map the User ID to Singular’s Mobile Device tracking identifier.

Note: Call this method as soon as possible after initializing the Singular SDK or once you have the User ID.

SingularSDK setDeviceCustomUserId Method
Description Sets the Custom User Id the same as login and maps it to Singular’s tracking identifier.
Signature singularSdk.setDeviceCustomUserId(userId)
Usage Example
singularSdk.setDeviceCustomUserId("customUserId");

Optional: Tracking Events and Revenue

Tracking Events

Singular can collect data about user events within the site to help analyze the performance of your campaigns and measure KPIs. For example, your organization may want to collect data about user logins, registrations, or tutorial completions.

You can send events to Singular using the event method.

Note:

  • We highly recommend passing event names and attributes in English to guarantee compatibility with third-party partners and analytics solutions if you plan to use them.
  • Event names are limited to 32 ASCII characters. Strings in non-ASCII characters have to be under 32 bytes once converted to UTF-8.
  • Attributes and values are limited to 500 ASCII characters.
event Method
Description Report a user event to Singular with or without additional information.
Signature

singularSdk.event(eventName, args)

Note: 'args' is a JavaScript object with key-value pairs. If you don’t want to pass any additional args call the event method with only the event name.

Usage Example
// Send a Registration_Completed event with no arguments
singularSdk.event("Registration_Completed");
// Send an event called "Registration_Completed" with additional properties singularSdk.event("Registration_Completed", {key1: 'value1', key2: 'value2'});

Tracking Revenue

Singular can collect data about revenue gained through the website to help analyze the performance and ROI of your campaigns. Singular will make the data available to you in reports, log exports, and postbacks.

Use the revenue method to report events. Revenue allows you to pass a custom event name, so that you'll be able to view revenue in Singular reports broken down by the different types of revenue events.

Notes: Any revenue reported in a different currency will be auto-converted to your organization's preferred currency, as set in your Singular account.

revenue Method
Description Send a revenue event to Singular with optional additional information.
Signature

singularSdk.revenue(eventName, currency, amount, args)

Note:

  • Pass currency as a three-letter ISO 4217 currency code, such as “USD”, “EUR”, or “INR".
  • The amount value can be passed as a decimal value.
Usage Example
// Send a revenue event to Singular 
singularSdk.revenue("Item_Purchased","USD", 5.50);
// Send a revenue event to Singular with additional args singularSdk.revenue("Item_Purchased","USD", 5.50, {key1: 'value1', key2: 'value2');

Optional: Cross-Subdomain Tracking

By default, the Singular Website SDK generates a Singular Device ID and persists it using browser storage. Since this storage can't be shared between subdomains, the SDK ends up generating a new ID for each subdomain.

If you want to persist the Singular Device ID across subdomains, you can use one of the following options:

Method A: Auto-Persist using Cookies

You can have the Singular SDK persist the Singular Device ID using a custom first-party cookie. Use the following method and set the main domain you want to track.

withAutoPersistentSingularDeviceId Method
Description Initialize the SDK with configuration options including the main domain for auto persisting Singular Device Id.
Signature withAutoPersistentSingularDeviceId(domain)
Usage Example
function initSingular() {
  const config = new SingularConfig(sdkKey, sdkSecret, productId)
    .withAutoPersistentSingularDeviceId(“example.com”);
  singularSdk.init(config);
}

Method B (Advanced): Set Singular Device ID Manually

If you don’t want Singular SDK to persist the Device ID automatically, you can persist the ID manually across domains - for example, using a top-level domain cookie or a server-side cookie. The value should be an ID previously generated by Singular, in valid uuid4 format.

Note: You can read the Singular Device ID using singularSdk.getSingularDeviceId() after calling the init method or using InitFinishedCallback.

withPersistentSingularDeviceId Method

Description

Initialize the SDK with configuration options including the Singular Device Id you want to persist.

Signature withPersistentSingularDeviceId(singularDeviceId)
Usage Example
function initSingular() {
  const config = new SingularConfig(sdkKey, sdkSecret, productId)
    .withPersistentSingularDeviceId(singularDeviceId);
  singularSdk.init(config);
}

Optional: Get Match ID

Important: This is an advanced feature. Consult with one of Singular’s Solution Engineers before implementing it.

Singular can attribute server to server installs from PC & Console platforms based on a deterministic unique Match ID per user. In order to utilize this feature, retrieve the Match ID from Singular's Web SDK after initialization.

getMatchID Method
Description Gets the unique Match ID for this web session
Signature singularSdk.getMatchID()
Usage Example
// Gets the user match ID to be included in the first session of other platforms
singularSdk.getMatchID()