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:

  • Identify users
  • Record custom events
  • Track consents
  • Display experiments and personalization

Installation

Initialize the SDK

Install the SDK by running the npm package.

npm install intempt

To update to the latest version, run

npm install intempt@latest

Import

Use this command to import the whole SDK:

import {SDK} from "intempt/src";

or

const IntemptSdk = require('intempt/src/SDK')

Create instance

SDK constructor parameters description:

const intempt: SDK = new SDK(
    'demo-organization', // organization name
    'demo-project', // project name
    'YOUR_API_KEY', // api key (identifier.secret)
    '616010376811536384', // source id
    100, // batch time in milliseconds (optional)
    20 // max items batch size (optional)
)

🚧

Don't miss out!

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

Tracking methods

Restrictions

SDK has an event title parameter mandatory for almost all tracking methods. All event titles are acceptable except 'Identify' - it's the default event title for user identification.

Identify

Our SDK offers a convenient function to identify users using unique identifiers such as email or phone number. Simply call the functions provided below to utilize this feature effectively.

await intempt.identify(
    '1845348', // user profile identifier
    '[email protected]', // unique user identifier
    'Identify User', // event title (optional)
    {'country': 'USA'} // user attributes (optional)
)

Usage examples

Connect profileId with unique user identifier:

await intempt.identify('1845348', '[email protected]')

Connect profileId with unique user identifier having custom event name:

await intempt.identify('1845348', '[email protected]', 'Identify User')

Connect profileId with unique user identifier including user attributes. User attributes require a provided event title different from 'Identify':

await intempt.identify('1845348', '[email protected]', 'Identify User', {'country': 'USA'})

📘

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.

Group

Our SDK includes a function that helps you identify accounts using unique identifiers such as domain or work email. To leverage this functionality, simply invoke the functions listed below.

await intempt.group(
    '1845348', // user profile identifier
    'intempt.com', // unique account identifier
    'Identify Account', // event title (optional)
    {'country': 'USA'} // account attributes (optional)
)

Usage examples

Connect user profileId with unique account identifier:

await intempt.group('1845348', 'intempt.com')

Connect user profileId with unique account having custom event name:

await intempt.group('1845348', 'intempt.com', 'Identify Account')

Connect user profileId with unique account including account attributes. Account attributes require a provided event title different from 'Identify':

await intempt.group('1845348', 'intempt.com', 'Identify UsAccounter', {'company_country': 'USA'})

Track

The SDK enables you to track custom events, such as 'Purchase' or 'Add to Cart,' by profileId. To monitor these user actions, simply call the method provided below.

await intempt.track(
    '1845348', // user profile identifier
    'Purchase', // event title 
    {'purchase_amount': 50.0, 'product_name': 'Shoes'} // event properties
)

Usage examples

Method call example:

await intempt.track('1845348', 'Purchase', {'price_amount': 50, 'product_name': 'Shoes'})

Alias

The SDK offers a convenient method to merge two separate user profiles, such as one identified by email and another by phone number, into a single user profile. By linking the two different identifiers, the system will consolidate them into one unified user, associating both the email and phone number with a single user record. Refer to the function below to perform this merge.

await intempt.alias(
    '1845348', // user profile identifier
    '[email protected]', // first user identifier
    '555-555-1234' // second user identifier to merge with
)

Usage examples

Method call example:

await intempt.alias('1845348', '[email protected]', '555-555-1234')

Record

The SDK offers a versatile method for configuring tracking with extensive customization options. This method enables you to tailor tracking settings according to your specific requirements without restrictions. It provides flexibility to define and monitor data at a granular level, ensuring you can capture and analyze all necessary information for comprehensive insights. Use the function below to access these advanced configuration capabilities.

await intempt.record(
    '1845348', // user profile identifier
    'Purchase', // event title
    '[email protected]', // unique user identifier (optional)
    'intempt.com', // unique account identifier (optional)
    {'purchase_amount': 50.0, 'product_name': 'Shoes'}, // event properties
    {'country': 'USA'}, // user attributes
    {'company_country': 'USA'} // account attributes
)

Usage examples

Record the item with event properties and user, account identifiers:

await intempt.record('1845348', 'Purchase', '[email protected]', 'intempt.com', {'purchase_amount': 50.0, 'product_name': 'Shoes'})

Record the item with event properties, user identifier, and attributes:

await intempt.record('1845348', 'Purchase', '[email protected]', undefined, {'purchase_amount': 50.0, 'product_name': 'Shoes'}, {'country': 'USA'})

Record the item with event properties account identifier, and attributes:

await intempt.record('1845348', 'Purchase', undefined, 'intempt.com', {'purchase_amount': 50.0, 'product_name': 'Shoes'}, undefined, {'company_country': 'USA'})

OptIn

This method activates the tracking of user data, allowing you to monitor and analyze user interactions and behaviors. By enabling this feature, you can collect valuable data that can provide insights into user preferences, activities, and trends. By default, it's enabled.

await intempt.optIn()

OptOut

This method disables the tracking of user data, ensuring that no further information about user interactions and behaviors is collected. By turning off this feature, you can respect user privacy and comply with data protection regulations. Use this function when you need to halt the monitoring and analysis of user data, whether temporarily or permanently. This method provides control over your data collection practices and can be a crucial part of your privacy and compliance strategy.

await intempt.optOut()

Consents methods

Consents

This method manages all user consents for data tracking. It allows you to handle user preferences regarding the collection and processing of their data. By invoking this function, you can set and update a user's consent status, ensuring that your application adheres to privacy regulations and respects user choices.

await intempt.consents(
    '1845348', // user profile identifier
    'accept', // consent action 'accept' or 'reject' allowed
    '1711705256000', // consents expiration time in ms (optional)
    '[email protected]', // user consents email (optional)
    'consents message' // user consents message (optional)
)

Usage examples

Update all consents:

await intempt.consents('1845348', 'accept')

Update all consents with the user's email and message:

await intempt.consents('1845348', 'accept', undefined, '[email protected]', 'consents message')

Consent

This method in the library allows you to manage the single consent for a specific type of user data tracking. By calling this function, you can enable or disable tracking for a particular data category according to the user's preference.

await intempt.consent(
    '1845348', // user profile identifier
    'accept', // consent action 'accept' or 'reject' allowed
    'GDPR', // consent category
    '1711705256000', // consents expiration time in ms (optional)
    '[email protected]', // user consents email (optional)
    'consents message' // user consents message (optional)
)

Usage examples

Update single consent:

await intempt.consent('1845348', 'accept', 'GDPR')

Update single consent with the user's email and message:

await intempt.consent('1845348', 'accept', 'GDPR', undefined, '[email protected]', 'consents message')

Optimization choose methods

Choose personalizations by groups

The SDK provides a method for selecting personalized experiences based on a list of groups. This allows you to tailor the user's experience according to specific segments or groupings, enhancing their overall interaction with your application. By choosing from a variety of groups, you can deliver customized content and features that align with the user's interests and preferences.

await intempt.choosePersonalizationsByGroups(
    '1845348', // user profile identifier
    ['banner'] // list of groups, if undefined - select all
)

Usage examples

Choose all personalizations:

await intempt.choosePersonalizationsByGroups('1845348')

Choose personalizations by groups:

await intempt.choosePersonalizationsByGroups('1845348', ['banner'])

Choose personalizations by names

The SDK provides a method to select personalized experiences based on a list of names. This approach enables you to customize the user experience by targeting specific individuals or groups identified by their names. By using this method, you can deliver tailored content and features to enhance the user's interaction with your application, ensuring a more engaging and personalized experience.

await intempt.choosePersonalizationsByNames(
    '1845348', // user profile identifier
    ['new year banner'] // list of names, if undefined - select all
)

Usage examples

Choose all personalizations:

await intempt.choosePersonalizationsByNames('1845348')

Choose personalizations by groups:

await intempt.choosePersonalizationsByNames('1845348', ['new year banner'])

Choose experiments by groups

The SDK provides a method to select and manage experiments based on a list of groups. This allows you to efficiently organize and conduct A/B tests or other experimental comparisons within specified groups. By targeting groups directly, you can streamline the process of running experiments and analyzing results, which in turn helps optimize your product or service for better user engagement and performance.

await intempt.chooseExperimentsByGroups(
    '1845348', // user profile identifier
    ['banner'] // list of groups, if undefined - select all
)

Usage examples

Choose all personalizations:

await intempt.chooseExperimentsByGroups('1845348')

Choose personalizations by groups:

await intempt.chooseExperimentsByGroups('1845348', ['banner'])

Choose experiments by names

The SDK provides a method to select and manage experiments based on a list of names. This functionality allows you to precisely target and conduct experiments with specific named experiments. By selecting experiments directly by name, you can easily control and track the performance of various tests, which enables efficient optimization and analysis for better user experiences and product improvements.

await intempt.choosePersonalizationsByNames(
    '1845348', // user profile identifier
    ['new year banner'] // list of names, if undefined - select all
)

Usage examples

Choose all personalizations:

await intempt.chooseExperimentsByNames('1845348')

Choose personalizations by groups:

await intempt.chooseExperimentsByNames('1845348', ['new year banner'])

Optimization choose response structure

[
  {
    "name": "login", // optimization name
    "group": "banner", // optimization choose
    "body": [ // body provided in Intempt application
      {
        "banner": "holiday-banner"
      }
    ]
  }
]

Field Type Validation

  1. When sending custom events, it’s important that each field matches the data type defined in your event schema. If a field’s type changes (e.g., from a string to an object), the event will be rejected. This ensures data consistency and prevents errors.
    Example:
    If the field name is defined as a string in the schema:

const event = { name: “John Doe” }; // ✅ Accepted
const event = { name: { first: “John”, last: “Doe” } }; // ❌ Rejected

What to do?
Always ensure that event fields retain the same type as defined in your schema.

  1. Adding New Fields to Custom Events
    You can now safely add new fields to your custom event schema without impacting existing fields. This allows you to extend your event tracking capabilities while keeping previous fields intact and functional.
    Example:

Original event - After adding a new field

const event = { name: “John Doe” }; // ✅ Accepted
const event = { name: { first: “John”, last: “Doe” } }; // ❌ Rejected

Existing fields will remain usable even after schema updates.

Recommendation

The method allows you to get products from a feed using an ID. Fields and quantity are configurable parameters to select the fields returned in the response and amount of products from the feed. Sending nulls means that all fields will be returned and the product amount will be limited to 5. The product ID is a nullable parameter and it's necessary for feeds with product input, like "Purchased Together".

intempt.recommendation(
  '1845348', // user profile identifier
  111090, // feed identifier
  5, //quantity
  "SKU12345", //product identifier
  ["title", "image_url", "price"] // fields to retrieve
)

This example retrieves five recommended products using the feed with ID 111090, including only the title, image URL, and price in the response.

Declaration

async recommendation(
    profileId: string,
    feedId:string,
    quantity:number,
    fields:string[], 
    productId?:string 
  ):Promise<Product[]>

Parameters

  • profileId (string, required) – User profile identifier
  • feedId (number, required) – The ID of the feed used to generate recommendations.
  • quantity (number, optional) – The number of recommended products to return. Defaults to 5.
  • fields (string[], optional) – A list of product attributes to include in the response (e.g., ["title", "image_url", "price"]).
  • productId (string, optional) - The unique identifier of the product

Returns

  • A Promise that resolves to an array of recommended products.

This method provides full flexibility in fetching and displaying personalized product recommendations based on predefined feed settings.

SDK provides additional methods for product events


Product Add

The productAdd method emits an event when a product is added to the cart.

productAdd(params: {  
    profileId: string,
    productId:string,
    quantity:number
}):  Promise<void>

Parameters

  • profileId (string, required) – User profile identifier
  • productId (string, required) - The unique identifier of the product being added to the cart.
  • quantity (number, optional) – The number of units added to the cart.

Returns

A Promise<void> that resolves once the event is emitted.

Example

intempt.productAdd(
  '1845348', // user profile identifier
  "SKU12345", //product identifier
   5, //quantity
);

This logs the addition of a product to the shopping cart, triggering an "Added to cart" event.

Product Ordered

The productOrdered method emits an event when a list of products is ordered, ensuring all products have valid details.

Declaration

productOrdered(
  profileId: string,
  products:{productId:string, quantity:number}[]
): Promise<void>

Parameters

  • profileId (string, required) – User profile identifier
  • products (array, required) - Array of products.

Returns

A Promise<void> that resolves once the event is emitted.

Example

intempt.productOrdered(
  '1845348', // user profile identifier
  [{ productId: "SKU12345", quantity: 2 },{ productId: "SKU16347", quantity: 4 }]
);

This triggers an order event for multiple products.


Product View

The productView method emits an event when a product is viewed by the user

Declaration

productView(profileId: string, productId:string): Promise<void>

Parameters

  • profileId (string, required) – User profile identifier.
  • productId (string, required) - The unique identifier of the product being viewed.

Returns

A Promise<void> that resolves once the event is emitted.

Example

intempt.productView(
  '1845348', // user profile identifier
  'SKU12345', //product identifier
);

This triggers an event when a product is viewed by the user.