Node.js SDK

Overview

Node.js server-side source allows you to collect server-side data and pull data directly from your servers and databases.

Node.js library will be most useful to you if you need to send data from a Node.js server, or for interacting with Intempt APIs in JavaScript outside of the browser.

This SDK is stateless and will only send the data you populate. In contrast, our web & mobile SDKs will automatically collect web and app, like device information or page/screen visited.

SDK capabilities:

  • Record custom events
  • Identify users
  • Track consents
  • Display experiments
  • Display experiences (personalization campaigns)

Installation

Create a source

Under the "Sources" page, select the "Create source" button and then the "NodeJS" option.

Copy the snippet and use it in the next step - SDK initialization.

Create the API key

Refer to API keys to create unique API keys that you can use in your project to authenticate SDK access.

Initialize the SDK

Install the SDK by running the npm package.

    npm install @intempt/sdk

To update to the latest version, run

    npm install intempt-nodejs-source@latest

Import

Use this command to import the whole SDK:

    const IntemptSdk = require('@intempt/sdk');

Or alternatively:

    import * as IntemptSdk from '@intempt/sdk'

Authorize the SDK

Configure the SDK parameters based on the source snippet you created in the earlier step.

interface ConfigurationParameters {
    basePath?: string; // override base path
    fetchApi?: FetchAPI; // override for fetch implementation
    middleware?: Middleware[]; // middleware to apply before/after fetch requests
    queryParamsStringify?: (params: HTTPQuery) => string; // stringify function for query strings
    username?: string; // parameter for basic security
    password?: string; // parameter for basic security
    apiKey?: string | ((name: string) => string); // parameter for apiKey security
    accessToken?: string | Promise<string> | ((name?: string, scopes?: string[]) => string | Promise<string>); // parameter for oauth2 security
    headers?: HTTPHeaders; //header params we want to use on every request
    credentials?: RequestCredentials; //value for the credentials param we want to use on each request
}

🚧

Don't miss out!

Remember to replace "YOUR_API_KEY" with the API key you generated via API keys section.

Example of authenticating via API key:

const configuration = new IntemptSdk.Configuration({
    username:'d9371778-b7ab-4d1c-8929-d3ee58e216d3',
    password:'081ad6c9-dee9-4e64-9384-4cf0ca41c079'
})

SDK methods

Identify users

Our SDK provides an exported function to track users automatically. To track a user, all you must do is call the functions below. Refer to Users & accounts for an explanation of how to use different identifiers.

	Intempt.profile({profileId: profileId, user_identifier: user_identifier, account_identifier: account_identifier})

πŸ“˜

Important

In your server, it is advisable to use the Id of your users as profileId. That way, it is always unique and you don't need to have a randomizer or generator.

Tracking events

Our server-side API allows the creation of any event type you might desire to be tracked for your page or application.

You can log custom events by calling Intempt's recordEvent function and passing in a set of key-value pairs.

    Intempt.recordEvent('COLLECTION_NAME', event);

The COLLECTION_NAME refers to an event type. For example, if you wanted to track every time your server received a purchase request, you might call the collection "purchase." Then, when a purchase happens, you call track and pass in the "purchase" event properties.

Example

	Intempt.recordEvent("purchase", {
		 "items": [{"item name": "item 1","price": 20}, {"item name": "item 2","price": 15}],
		 "totalprice": 35,
		 "ispaid": true,
		 "timestamp": new Date().getTime(),
		 "fixed.name": "John Smith",
		 "fixed.age": 28,
		 "intempt.visit.trackcharge": 35
	})

In the example above, we have a custom collection with the name purchase, then we have an object of key-value pairs. The Object passed into represents the fields we created while creating the collection.

There are other examples in the samples directory.

Prerequisite

Our platform uses AVRO schema, requiring you to create event collections before sending the data to Intempt. Refer to Collections to create the event schema on the NodeJS source before you start sending the events from the server.

Verify event tracking

There are two ways to verify if your events were tracked successfully.

Check via the browser console's network tab.

Use the browser's inspect tool, select the network tab, and enter "adapter" into the search bar.

This will only show network events that are related to event tracking via Intempt.

If the request is successful (returns 200), it means that the event was tracked successfully. You can verify this by clicking on the "Payload" tab.

Check via your project user list.

You can visit your project user list and check the latest user data.

If under "Event stream," it matches the event performed, it means that the event was tracked successfully.

Display experiments

Experiment methods allow you to display A/B tests on your website via server-side rendering.

Requirements

  1. Create a server-side experiment with at least one variant. Refer to Experiment builder on the creation process.
  2. Add a custom payload/list of changes that will be served on your app if the user meets the experiment conditions.

Define your payload in the editor view - this will be the exact content that the app will receive - ensure that it renders based on your functionality.

Here is an example preview of the served experiment via an example payload.

  1. Copy the Experiment ID from the selected experiment and use it on the following calls to serve the experiment variant to users that match the targeting and traffic conditions configured within the experiment.
  1. Use the following methods to use the configured experiments on your app.

Choose the experiment variant

Select experiment variants using the NodeJS SDK library.

  1. Create experiments API object to choose variants
const experimentsApi = new IntemptSdk.CDPMetadata.ExperimentsApi(configuration);
  1. Build request parameters (sessionId - optional parameter, userIdentifier - value of user identifier, email usually)
  const requestParameters = {
    orgName: "organization-name",
    projectName: "project-name",
    experimentId: "unique-experiment-id",
    chooseVariant: {
      userIdentifier: "user-identifier-value",
      sessionId: "current-session-id"
    }
  };
  1. Call choose the variant request
  const variant = experimentsApi.chooseVariant(requestParameters)

Display experiences

Experiences methods allow you to display different personalization elements and screens on your website or app. The difference between experiments and experiences is that you can display multiple experiences targeted for different users in a single campaign without requiring you to create multiple experiments, create different hypotheses, and ensure you meet the statistical significance requirements.

Requirements

  1. Create a server-side personalization campaign with at least one variant. Refer to Experiment builder on the creation process.
  2. Add a custom payload/list of changes that will be served on your app if the user meets the experience conditions.

Define your payload in the editor view - this will be the exact content that the app will receive - ensure that it renders based on your functionality.

Here is an example preview of the served experiment via an example payload.

  1. Copy the Campaign ID from the selected experiment and use it on the following calls to serve the experiment variant to users that match the targeting and traffic conditions configured within the experiment.
  1. Use the following methods to use the configured experiments on your app.

Choose experience

Select campaign experience using NodeJS SDK library.

  1. Create a Campaign API object to choose experiences
const personalizationApi = new IntemptSdk.CDPMetadata.PersonalizationApi(configuration);
  1. Build request parameters (URL - optional parameter, userId - value of user identifier, email usually)
  const requestParameters = {
    orgName: "organization-name",
    projectName: "project-name",
    campaignId: "unique-campaign-id",
    chooseExperience: {
      userId: "user-identifier-value",
      url: "target-url-to-match"
    }
  };
  1. Call choose experience request
  const experience = personalizationApi.chooseExperience(requestParameters)

Tracking consents

Needs documentation

Configure batching

Our libraries are built to support high-performance environments. That means using our Node library on a web server serving hundreds of requests per second is safe.

Every method you call does not result in an HTTP request but is queued in memory instead. Messages are then flushed in the batch in the background, which allows for much faster operations.

const eventRecorder = IntemptSdk.EventRecorder.WithEventBatcher(
    orgName,
    projectName,
    sourceId,
    new IntemptSdk.PushSource.SourcesApi(configuration),
    { maximum:100, interval: 10 });

Flush functions

flushAt: This has a default value of 10. It determines how many items can be stored in memory at a time. For example, if you have flushAt set at 1, this means we can only have one event at a time in our batch memory.

flushInterval: This has a default value of 10000ms. It determines how long our memory should hold data before flushing to Intempt Servers. For example, if you have flushInterval set at 10000ms, this means we can only store events for as long as 10 seconds in our batch memory.