Sending Events (Attribution and Automation)
Any interaction that a user has with your website can be recorded as an event in the Metrix dashboard. Metrix collects these events and provides you with their statistical analysis.
Initialize the SDK before sending any events. When an event should be associated with a specific user, call authorizeUser first.
1. Sending an Event by Slug
Use newEvent to send a custom event based on the event slug defined in the dashboard.
newEvent(slug: string, customAttributes?: { [key: string]: string }, onSuccess?: () => void): void| Name | Type | Description | Required |
|---|---|---|---|
slug | string | The event slug created in the Metrix dashboard for the target event. | Yes |
customAttributes | { [key: string]: string } | An object of custom attributes related to the event. | No |
onSuccess | () => void | Callback function that runs after the event is successfully sent. | No |
For example, to track clicks on a button, first create the related event in the Metrix dashboard (Settings > Manage Events > Create event). Then call newEvent with that event slug:
import { newEvent } from '@metrixorg/websdk';
// Send a simple event
newEvent('BUTTON_CLICKED');
// Send an event with custom attributes
const attributes = {
first_name: 'Ali',
last_name: 'Bagheri',
product_name: 'shirt',
size: 'large',
purchase_date: '2024-11-20T11:24:03Z', // use ISO 8601 to treat this attribute as a date
};
newEvent('PURCHASE_COMPLETED', attributes, () => {
console.log('Purchase event sent successfully!');
});If slug is empty, the following error occurs:
Error: newEvent: slug is required and cannot be empty.
2. Sending an Event by Name
This method behaves like newEvent, except that it identifies the event by its event name instead of its slug.
newEventByName(name: string, customAttributes?: { [key: string]: string }, onSuccess?: () => void): void| Name | Type | Description | Required |
|---|---|---|---|
name | string | The event name created in the Metrix dashboard for the target event. | Yes |
customAttributes | { [key: string]: string } | An object of custom attributes related to the event. | No |
onSuccess | () => void | Callback function that runs after the event is successfully sent. | No |
import { newEventByName } from '@metrixorg/websdk';
newEventByName('Purchase Completed', {
product_name: 'shirt',
size: 'large',
});If name is empty, the following error occurs:
Error: newEventByName: name is required and cannot be empty.
3. Sending Revenue Events
To record a revenue event, first create it in the Metrix dashboard, then use newRevenue.
newRevenue(slug: string, revenue: number, currency?: 'IRR' | 'USD' | 'EUR', onSuccess?: () => void): void| Name | Type | Description | Required |
|---|---|---|---|
slug | string | The revenue event slug created in the Metrix dashboard. | Yes |
revenue | number | Revenue amount. | Yes |
currency | 'IRR' | 'USD' | 'EUR' | Currency unit. Defaults to IRR. | No |
onSuccess | () => void | Callback function that runs after the event is successfully sent. | No |
import { newRevenue } from '@metrixorg/websdk';
newRevenue('ORDER_COMPLETED', 12000, 'IRR');Supported currencies:
IRRfor Iranian RialUSDfor US DollarEURfor Euro
Complete Examples
Basic Event Tracking
import { init, newEvent } from '@metrixorg/websdk';
// Initialize SDK
init('APP_ID', 'API_KEY');
// Track a button click
document.getElementById('purchaseButton').addEventListener('click', () => {
newEvent('BUTTON_CLICKED', {
button_id: 'purchaseButton',
button_label: 'Buy Now',
});
});E-Commerce Events
Product Viewed
import { newEvent } from '@metrixorg/websdk';
const attributes = {
product_id: 'SKU-12345',
product_name: 'Premium Running Shoes',
category: 'footwear',
price: '129.99',
brand: 'Nike',
in_stock: 'true',
};
newEvent('PRODUCT_VIEWED', attributes);Item Added to Cart
import { newEvent } from '@metrixorg/websdk';
const attributes = {
product_id: 'SKU-12345',
product_name: 'Premium Running Shoes',
price: '129.99',
quantity: '1',
cart_total: '129.99',
};
newEvent('ITEM_ADDED_TO_CART', attributes);Checkout Started
import { newEvent } from '@metrixorg/websdk';
const attributes = {
cart_item_count: '3',
cart_total: '399.97',
currency: 'USD',
};
newEvent('CHECKOUT_STARTED', attributes);Purchase Completed
import { newEvent } from '@metrixorg/websdk';
const attributes = {
transaction_id: 'txn_12345678',
transaction_total: '399.97',
currency: 'USD',
item_count: '3',
payment_method: 'credit_card',
shipping_cost: '10.00',
tax_amount: '35.00',
};
newEvent('PURCHASE_COMPLETED', attributes, () => {
console.log('Purchase tracked successfully');
});Revenue Event
import { newRevenue } from '@metrixorg/websdk';
newRevenue('ORDER_COMPLETED', 399.97, 'USD', () => {
console.log('Revenue tracked successfully');
});User Interaction Events
Form Submission
import { newEvent } from '@metrixorg/websdk';
document.getElementById('contactForm').addEventListener('submit', (e) => {
e.preventDefault();
const formData = new FormData(e.target);
newEvent('FORM_SUBMITTED', {
form_id: 'contactForm',
form_name: 'Contact Us',
field_count: String(formData.size),
});
e.target.submit();
});Search Performed
import { newEvent } from '@metrixorg/websdk';
function performSearch(query: string) {
const results = search(query);
newEvent('SEARCH_PERFORMED', {
search_query: query,
result_count: String(results.length),
category_filtered: 'all',
});
return results;
}Page Viewed
import { newEvent } from '@metrixorg/websdk';
newEvent('PAGE_VIEWED', {
page_url: window.location.pathname,
page_title: document.title,
referrer: document.referrer || 'direct',
});Account Events
Account Created
import { newEvent } from '@metrixorg/websdk';
const attributes = {
signup_method: 'email',
account_type: 'free',
referral_source: 'google',
};
newEvent('ACCOUNT_CREATED', attributes);Login Successful
import { newEvent } from '@metrixorg/websdk';
const attributes = {
login_method: 'email',
account_type: 'premium',
};
newEvent('LOGIN_SUCCESSFUL', attributes);Password Reset
import { newEvent } from '@metrixorg/websdk';
newEvent('PASSWORD_RESET_REQUESTED', {
reset_method: 'email',
});Best Practices
Attribute Naming
- Use snake_case for attribute keys:
product_name,order_id,category_type - Keep keys lowercase and descriptive
- Avoid spaces and special characters in keys
// Good
const goodAttributes = {
product_name: 'Winter Jacket',
payment_method: 'credit_card',
order_total: '150.00',
};
// Avoid
const badAttributes = {
'Product Name': 'Winter Jacket', // space in key
paymentMethod: 'credit_card', // camelCase
'order-total': '150.00', // hyphen in key
};
newEvent('PURCHASE_COMPLETED', goodAttributes);Attribute Limits
- Keep custom attributes concise and relevant to the event
- Use 10-15 key-value pairs maximum per event
- Avoid redundant or derived attributes that can be calculated server-side
Data Type Handling
- All attribute values must be strings
- Convert numbers, dates, and booleans to strings:
const attributes = {
quantity: '5', // number as string
price: '99.99', // decimal as string
is_premium: 'true', // boolean as string
signup_date: '2024-01-15T10:30:00Z', // ISO 8601 date
timestamp: String(Date.now()), // Unix timestamp
};
newEvent('PURCHASE_COMPLETED', attributes);Sensitive Data
- Do not include passwords, bank card numbers, or personally identifiable information in event attributes
- Use hashed values for PII when necessary
- Consider your data retention and privacy policies
Event Ordering
- Track events in the order they occur for accurate funnel analysis
- Track events before form submissions or page navigations to ensure delivery
Troubleshooting
Events Not Appearing in Dashboard
- Ensure
init()was called before anynewEvent()call - Confirm your
APP_IDandAPI_KEYare correct - Verify the event slug/name matches exactly what you created in the Metrix dashboard
- Check the browser Network tab to verify the event request was sent successfully
- Check the browser console for errors or validation messages
Custom Attributes Not Showing
- Ensure all attribute values are strings
- Verify attribute keys use snake_case naming
- Check whether the dashboard event configuration limits custom attributes
- Test with a simple attribute first:
{ test: 'value' }
Callback Not Executing
- The
onSuccesscallback fires after the event reaches Metrix servers - Network latency may cause delays
- Check the browser console for any error messages
API Summary
| Method | Description |
|---|---|
newEvent(slug, customAttributes?, onSuccess?) | Sends an event by dashboard slug. |
newEventByName(name, customAttributes?, onSuccess?) | Sends an event by dashboard name. |
newRevenue(slug, revenue, currency?, onSuccess?) | Sends a revenue event by dashboard slug. |