A package for recording analytics from a front-end application
Features
- Record user interactions and events
- Track user selections and stage transitions
- Capture cart additions and purchase/quote events
- Log custom events for enhanced tracking
Installation
Install the package via your favorite package manager:
npm install @threekit/analytics
In addition to the analytics package, you will also need to install the REST API package. This is needed for some additional dependencies.
Initialization
The first step will be to import the necessary types and objects.
import { getSession, Session } from "@threekit/analytics";
import { Configuration, OptionsType, OptionInteractionType, ARStage, ShareType } from "@threekit/rest-api";
Next we need to initialize the Session object.
const orgId = '...'; // the UUID for your org
const publicToken = '...'; // a public token for your org (do not use a private token in front-end app)
const host = 'admin-fts.threekit.com'; // the host for your org
export const getCurrentSession = () => {
const session = getSession({
auth: { orgId, publicToken, host }
});
Session.log = false;
return session;
};
Recording Events
The analytics events fall into several major categories:
- UI Stage events
- Stage transition where the user has progressed from one configuration step to another in a multi-step configuration scenario.
- Interaction events
- General user interaction events with the UI in terms of seeing the options available for an attribute, selecting options, filling out forms and queries, uploading images, etc.
- Cart Interaction
- In this case we focus on capturing the steps where the users have made a decision and they add items to the cart or proceed with a purchase.
- Error Logging
- Logging front-end errors that the users may have encountered in order to get some statistics on the number and types of errors.
- Custom Events
- You can also create your own custom events to cover for any situation that you'd like to focus on specifically, such as perhaps when the user selects and moves certain components within a modular configurator.
Stage Transition
In a multi-step configuration, each step is referred to as a stage. For example, in the first step the UI provides the user with a choice of product, and once the product choice is made, the UI proceeds to the second step where the user must choose a material.
Use this event to record the start of each stage:
getCurrentSession().stage({ stageName: 'Confirm Selections' });
Options Show
This event should be fired when the user clicks on a dropdown or opens a page where the options for a specific attribute are being shown. The event is meant to record the set of options that were presented to the user for that specific attribute, prior to the user interacting with those options and making a selection.
For the options on a product attribute it is important to log the
assetId
of the product, so that parsing the analytics data can make it easier to tie the interaction events to that specific product.
Within the Classic Catalog there are two major types of attributes:
- Item based - Asset or PartReference attributes which reference Items as options
- Non Item based - All other types such as String, Number, Color, Boolean, or Image Upload.
Item Based Attributes
getCurrentSession().optionsShow({
assetId: assetId, //optional, but highly recommended, assetId of the parent product
optionsSetId: attributeName, //The parent attribute for these options
options: values.map((value) => ({
optionId: attributeOptionAssetId, // The assetId of the Item representing each option, for Asset or PartReference attributes
optionName: attributeOptionAssetName // optional, but highly recommended, the name of the Item representing the option for Asset or PartReference attributes
})),
optionsType: OptionsType.Asset
});
Non Item Based Attributes
getCurrentSession().optionsShow({
assetId: assetId, // optional, but highly recommended, assetId of the parent product
optionsSetId: optionSetName, // a unique string, can be anything but it will be the "name" of the option set in the UI
options: values.map((value) => ({
optionId: value, // any unique string is acceptable here.
optionName: value // optional, but recommended, display name if you have one.
})),
optionsType: OptionsType.Value
});
Options Interaction
Record this event when the user selects an option that was shown to them.
It is currently important to tie every option interaction event to an
optionId
that was logged through anoptionsShow
event. These IDs must match exactly.
Do not use this event for parametric configuration attributes. Instead, use the Parametric Value event.
getCurrentSession().optionInteraction({
optionsSetId: attributeName, // the same optionsSetId used in the ```optionsShow``` event
interactionType: OptionInteractionType.Select,
optionId: value // either the assetID or the string optionId specified for this option in the ```optionsShow``` event.
});
Queries
If the user makes a query you can record it using this event, you can record both its text-based search and its structured query using this event, which takes a dictionary of strings:
getCurrentSession().query({ queryName: "product-search", query: { text: "stylish leggings", size: "12", color: "Blue" } );
Chat Prompts and Responses
If the user makes a query (such as with the AI Discovery feature) you can record it using this event, you can record both its text-based search and its structured query using this event, which takes a dictionary of strings:
getCurrentSession().chatPrompt({
promptId: 'introduction',
promptText:
'Introduce the selected product to the user in a professional manner, the selected product is ...'
});
// ...submit prompt to LLM and get a response...
getCurrentSession().chatResponse({
promptId: 'introduction',
promptResponseText:
'Hello and Welcome to eShop! This electronic yak shaver you have selected is the perfect wedding gift...'
});
Augmented Reality
When the user requests a augmented reality experience, two events can be sent. The first is to request an AR experience and then a second once that AR experience ia launched.
getCurrentSession().ar({
arStage: ARStage.Offered,
arHandoffId: userId
});
Personalize Text
When the user is personalizing an item with custom text, use this event:
getCurrentSession().personalizeText({
personalizeId: 'Label Text',
personalizedText: labelText
});
Parametric Value
When the user sets parametric values on an item, record those changes with this event:
getCurrentSession().parametricValue({
parametricId: 'Table Width',
parametricValue: tableWidth
});
Image Upload
When you allow a user to upload custom images, record those uploads with this event:
getCurrentSession().imageUpload({
imageUploadId: 'Front Image',
imageUploadFileId: fileID
});
Share
When the user generates a URL to share the configuration with another user, record the event using:
getCurrentSession().share({
shareLink: configurationUrl,
shareType: ShareType.Share
});
Custom Events
For events in the user experience that don’t fit any predefined category, use a custom event:
getCurrentSession().custom({ customName: 'View Product List' });
Errors
You can record any errors on the frontend to analytics, just pass in the error object (which must be derived from the JavaScript Error class):
const error = new Error('bad data encountered');
getCurrentSession().error(error);
Add To Cart
For each item a user adds to the cart, record it with this event:
getCurrentSession().addToCart({
assetId: itemId,
configuration: simplifiedConfiguration as Configuration,
itemCustomId: itemConfiguration['SKU'] as string | undefined,
itemName: itemConfiguration['Description'] as string | undefined,
itemPrice: itemConfiguration['Price'] as number | undefined,
itemCount: itemConfiguration['skuQty'] as number | undefined
});
This event is intended to only record the addition of a unique SKU to the cart, whether it is a quantity of 1 or multiples. If the user adds multiple different SKUs to the cart in a single click, such as with modular configurators, then you should fire a separate Add to Cart event for each unique SKU.
Quote or Purchase (Buy Button)
When the user makes an order or a purchase, record the event as follows:
const orderPrice = orderData.reduce(
(previous, current) => previous + current.unitPrice * current.quantity,
0
);
const cartItems = orderData.map((item) => {
return {
itemName: item.description,
itemCustomId: item.name,
itemPrice: item.unitPrice,
itemCount: item.quantity
};
});
getCurrentSession().quote({
orderPrice,
cart: cartItems
});
Best Practices for Analytics Integration
To effectively leverage analytics, it's crucial to capture key user decisions during their interactions with your application. While each project may have unique requirements, the following guidelines can help ensure comprehensive tracking:
Capture Key Decision Points
Multi-Choice Options
- Record when users are presented with multiple choices and when they make a selection.
- Capture details such as:
- The available options (SKUs, asset IDs, prices, etc.).
- Prices associated with each option.
- The option the user ultimately selected.
Stage Transitions
- Track when users advance to the next stage in a multi-step process, such as progressing through a configuration experience.
- Record when users move forward or go back to a previous stage.
- Ensure consistent naming for stages to maintain clarity.
Adding Products to Cart
- Capture details when items are added to the cart, including:
- SKUs or asset IDs of the products.
- Product names and prices.
Requesting Quotes or Purchases
- Record quote requests by capturing:
- The total amount of the quote.
- Item Ids and names and prices
- Customer ID and order ID for reference.
Creating Share Links
- Track when a shareable link is generated by recording:
- The URL of the shared configuration.
Ensure Consistency and Accuracy
Consistent Naming Conventions:
- Use standardized names for stages, options, and events across your application. This consistency simplifies data analysis and reporting.
Comprehensive Event Tracking:
- Avoid overlooking significant events. Think about the user journey and identify all critical interactions that should be recorded.
Testing and Validation:
- Before deploying, thoroughly test your analytics implementation to ensure all events are captured accurately. Validate that the data recorded aligns with user actions. This validation can currently be performed only by Threekit employees.