@novustech/mtrix
v1.2.1
Published
Analytics, experiments, and monitoring package for web applications
Maintainers
Readme
Mtrix JS SDK
Analytics, experiments, and monitoring package for web applications.
Installation
npm install @novustech/mtrixQuick Start
import mtrix from '@novustech/mtrix';
// Initialize the SDK
mtrix.init({
organizationId: 'your-org-id',
projectId: 'your-project-id',
environment: 'production',
encryptionKey: 'your-encryption-key',
debug: false,
options: {
sessionRecording: {
tracking: true,
sampleRatio: 0.1
},
errorReporting: {
tracking: true
},
performanceReporting: {
tracking: true
}
}
});Features
Track Events
// Basic event tracking
mtrix.trackEvent('button_clicked', {
buttonId: 'checkout-btn',
productId: '12345'
});
// Event with EventData fields and custom properties
mtrix.trackEvent('page_view', {
// These are recognized EventData fields and will be at root level
organizationId: 'org-123', // Optional, defaults to init config
projectId: 'proj-456', // Optional, defaults to init config
pageName: 'product-page',
pageType: 'lander',
productType: 'apparel',
country: 'USA',
city: 'New York',
variantIndices: [
{
experimentId: 583920174826,
selectedVariantId: 0,
selectedVariantName: 'On',
variantAllocation: 50,
returningExperimentVisitor: false
}
],
// These are not in EventData schema, so they go to customProperties
campaign: 'summer-sale',
customField: 'value'
});
// Using explicit customProperties
mtrix.trackEvent('button_clicked', {
buttonId: 'checkout-btn',
customProperties: {
campaign: 'summer-sale',
variant: 'blue-cta',
clickPosition: { x: 150, y: 300 },
userSegment: 'premium'
}
});
// Override the default sessionId if needed
mtrix.trackEvent('button_clicked', {
buttonId: 'checkout-btn',
sessionId: 'custom-session-id-123'
});Get Page Experiment Details
const experiments = await mtrix.getPageDetails({
location: '/product-page',
userId: 'user-123'
});
// Automatically apply experiment variants to the page
if (experiments.success) {
mtrix.applyExperiments(experiments);
}Get Visitor Experiment Details
Fetch the experiment variants that a visitor has seen during their session:
const visitorDetails = await mtrix.getVisitorDetails();
if (visitorDetails.success) {
console.log('Visitor experiments:', visitorDetails.data.experiments);
// Process the experiment data as needed
}Log Purchase Data
Log purchase transactions with comprehensive order details:
const purchaseData = {
// Required fields
purchaseId: 'ORDER-12345',
userId: 'user-123',
sessionId: 'session-abc-123',
email: '[email protected]',
purchase: {
subTotal: 99.99,
shippingTotal: 5.00,
tax: 8.99,
products: [{
productTitle: 'Premium Plan',
price: 99.99,
compareAtPrice: 129.99,
quantity: 1,
isSubscription: true
}]
},
// Optional fields
productName: 'Premium Subscription',
checkoutAmount: 99.99,
upsellAmount: 19.99,
cartCurrency: 'USD',
testPurchase: false,
billingAddress: {
first_name: 'John',
last_name: 'Doe',
address1: '123 Main St',
city: 'New York',
country: 'US'
}
};
const result = await mtrix.logPurchase(purchaseData);Cart Tracking
// Add items by variant ID
await mtrix.addToCart(['variant-123', 'variant-456']);
// Or with explicit quantities
await mtrix.addToCart([
{ variantId: 'variant-123', quantity: 2 }
]);addToCart updates the cart and automatically tracks an AddToCart event with the variant IDs and quantities.
User Identification
mtrix.setUser('user-123');Performance Monitoring
const metrics = mtrix.getPerformance();
console.log('Page load metrics:', metrics);Session Recording
// Force session recording (e.g., after an error)
mtrix.forceRecording();
// Stop session recording
mtrix.stopRecording();Debug Mode
// Enable debug mode for detailed logging
mtrix.enableDebugMode();
// Check if debug mode is enabled
if (mtrix.isDebugMode()) {
console.log('Debug mode is active');
}
// Disable debug mode
mtrix.disableDebugMode();Session Management
// Get the current session ID being used by Mtrix
const currentSessionId = mtrix.getSessionId();
console.log('Current session:', currentSessionId);Critical Events
The following events are automatically sent using fetch with keepalive: true for maximum reliability:
CartAbandonedBeforeUnloadPageUnloadWindowClose
These events will complete even if the user is closing their browser, ensuring critical data isn't lost. The library uses keepalive to maintain the request during page unload.
Example:
// This will automatically use fetch with keepalive for reliability
mtrix.trackEvent('CartAbandoned', {
cartItemCount: 3,
cartValue: 99.99,
customProperties: {
items: cartItems,
abandonReason: 'page_close'
}
});API Reference
mtrix.init(config)
Initialize the SDK with your configuration.
mtrix.trackEvent(eventName, properties)
Track custom events with optional properties.
Property Handling:
- Properties that match fields in the EventData schema are placed at the root level of the event
- EventData fields include:
organizationId,projectId,userId,sessionId,ipAddress,pageName,pageType,funnelName,productType,productName,productId,amount,variantIndices,country,city,referrer,queryParams,gender,browserLocales - Properties not in the EventData schema are automatically placed in the
customPropertiesfield - You can also explicitly pass a
customPropertiesobject, which will be merged with any other unrecognized properties - If you include a
sessionIdin the properties, it will override the default session ID organizationIdandprojectIddefault to values from the init configuration if not provided- Internal fields like
eventId,eventName, andtimestampare generated by the SDK and cannot be overridden
mtrix.getPageDetails(params)
Get experiment details for a specific page and user.
mtrix.getSessionId()
Get the current session ID being used by Mtrix for event tracking.
mtrix.getVisitorDetails()
Get all experiment variants that a visitor has seen in their session. Uses the SDK's internal sessionId — no parameter required.
mtrix.logPurchase(purchaseData)
Log purchase transaction data. Required fields:
purchaseId: Unique purchase identifieruserId: User identifiersessionId: Session identifieremail: Customer emailpurchase.subTotal: Order subtotal amount
mtrix.addToCart(items)
Add items to the cart and track an AddToCart event. items is an array of variant IDs (strings) or { variantId, quantity? } objects.
mtrix.updateCart(items)
Update the cart directly. variantId is required per item; omit quantity to increment by 1, set a positive quantity to set it, or 0 to remove the item.
mtrix.setUser(userId)
Set the current user ID for tracking.
mtrix.applyExperiments(experimentData)
Automatically apply experiment variants to page elements.
mtrix.getPerformance()
Get performance metrics for the current page.
mtrix.forceRecording()
Force session recording to start.
mtrix.stopRecording()
Stop session recording.
License
MIT
