getu-attribution-sdk
Version:
GetuAI Attribution SDK for client-side tracking
612 lines (441 loc) • 15 kB
Markdown
# GetuAI Attribution SDK
A JavaScript SDK for tracking user attribution and conversion events in web applications.
## Features
- **Automatic UTM Parameter Tracking**: Automatically captures and stores UTM parameters from URLs
- **Cross-Domain UTM Passing**: Automatically adds UTM parameters to external links for seamless attribution tracking
- **Event Queue Management**: Batches events and sends them efficiently to the server
- **Offline Support**: Stores events locally when offline and syncs when connection is restored
- **Auto-tracking**: Automatically tracks page views, form interactions
- **Immediate Event Processing**: Critical events like purchases and logins are sent immediately
- **Session Management**: Tracks user sessions and maintains user identity
- **TypeScript Support**: Full TypeScript support with type definitions
## Installation
### Via CDN (Recommended)
Add the script tag to your HTML:
```html
<script
src="https://unpkg.com/getu-attribution-sdk@0.2.2/dist/getuai-attribution.min.js"
data-api-key="your_api_key_here"
></script>
```
### Via NPM
```bash
npm install getu-attribution-sdk
```
## Configuration
### Script Tag Attributes
| Attribute | Type | Default | Description |
| --------------------------- | ------- | --------------------------------------------- | ----------------------------------------------- |
| `data-api-key` | string | required | Your GetuAI API key |
| `data-api-endpoint` | string | `https://attribution.getu.ai/attribution/api` | API endpoint URL |
| `data-debug` | boolean | `false` | Enable debug logging |
| `data-auto-track` | boolean | `false` | Enable automatic event tracking |
| `data-auto-track-page-view` | boolean | `false` | Automatically track page view on initialization |
| `data-batch-size` | number | `100` | Number of events to batch |
| `data-batch-interval` | number | `5000` | Batch interval in milliseconds |
| `data-auto-clean-utm` | boolean | `true` | Remove UTM params from URL after capture |
### Configuration Object
```typescript
interface SDKConfig {
apiKey: string;
apiEndpoint?: string;
batchSize?: number;
batchInterval?: number;
maxRetries?: number;
retryDelay?: number;
enableDebug?: boolean;
autoTrack?: boolean;
// Control whether to automatically track page views on initialization
autoTrackPageView?: boolean;
sessionTimeout?: number;
// Cross-domain UTM tracking configuration
enableCrossDomainUTM?: boolean;
crossDomainUTMParams?: string[]; // Which UTM params to pass
excludeDomains?: string[]; // Domains to exclude from UTM passing
// Remove UTM params from URL after capture
autoCleanUTM?: boolean; // default true
}
```
## Usage
### Basic Usage
The SDK automatically initializes when loaded with a valid API key:
```html
<script
src="https://unpkg.com/getu-attribution-sdk@0.2.2/dist/getuai-attribution.min.js"
data-api-key="your_api_key_here"
></script>
```
### Enable Auto Page View Tracking
To automatically track page views when the SDK initializes:
```html
<script
src="https://unpkg.com/getu-attribution-sdk@0.2.2/dist/getuai-attribution.min.js"
data-api-key="your_api_key_here"
data-auto-track-page-view="true"
></script>
```
### Manual Initialization
```javascript
import { init, trackEvent, EventType } from "getu-attribution-sdk";
// Initialize SDK with auto page view tracking
await init({
apiKey: "your_api_key_here",
autoTrack: true,
autoTrackPageView: true, // Automatically track page view on initialization
});
// Track custom event
await trackEvent(EventType.PAGE_VIEW, {
page: "/home",
referrer: "google.com",
});
```
### Tracking Events
#### Page Views
```javascript
// Automatic (when autoTrack is enabled)
// Manual tracking
await trackPageView(
{
page: "/product/123",
category: "electronics",
},
"track_user_id"
);
```
#### Purchases
```javascript
await trackPurchase("user_123", 99.99, Currency.USD, {
product_id: "prod_123",
category: "electronics",
quantity: 1,
});
```
#### Logins
```javascript
await trackLogin("user_123", {
method: "email",
provider: "google",
});
```
#### Signups
```javascript
await trackSignup("user_123", {
method: "email",
provider: "google",
});
```
#### Form Submissions
```javascript
await trackFormSubmit("user_123", {
form_id: "contact_form",
form_type: "contact",
});
```
#### Custom Events
```javascript
await trackEvent(
EventType.ADD_TO_CART,
{
product_id: "prod_123",
price: 29.99,
quantity: 2,
},
"user_123",
29.99,
Currency.USD
);
```
### Attribution Data
```javascript
import { getAttributionData } from "getu-attribution-sdk";
// Get UTM attribution data
const attribution = getAttributionData();
console.log("First touch:", attribution.firstTouch);
console.log("Last touch:", attribution.lastTouch);
console.log("Touchpoints:", attribution.touchpoints);
```
### SDK Status
```javascript
import { getStatus } from "getu-attribution-sdk";
const status = getStatus();
console.log("SDK Status:", status);
// {
// initialized: true,
// session: { sessionId: '...', ... },
// queueSize: 5,
// online: true,
// crossDomainUTM: {
// enabled: true,
// currentParams: { utm_source: 'google', ... }
// }
// }
```
## Event Types
The SDK supports the following event types:
### Ad Touchpoints
- `AD_IMPRESSION` - Ad impression events
- `AD_CLICK` - Ad click events
### Pre-conversion Signals
- `PAGE_VIEW` - Page view events
- `VIDEO_PLAY` - Video play events
### Registration Funnel
- `FORM_SUBMIT` - Form submission events
- `EMAIL_VERIFICATION` - Email verification events
### Login Flow
- `LOGIN_SUCCESS` - Successful login events
### Signup Flow
- `SIGNUP_SUCCESS` - Successful signup events
### Purchase Funnel
- `PRODUCT_VIEW` - Product view events
- `ADD_TO_CART` - Add to cart events
- `PURCHASE_COMPLETE` - Purchase completion events
## Auto-tracking Features
The SDK provides two independent auto-tracking options:
### General Auto-tracking (`autoTrack`)
When `autoTrack` is enabled, the SDK automatically tracks:
- **Form Interactions**: Form submissions
- **Link Clicks**: External link clicks with automatic UTM parameter passing
### Page View Auto-tracking (`autoTrackPageView`)
When `autoTrackPageView` is enabled, the SDK automatically tracks:
- **Page Views**: Automatically tracks a page view event when the SDK initializes
- **Independent Control**: This is separate from the general `autoTrack` setting, allowing you to control page view tracking independently
## Cross-Domain UTM Passing
The SDK automatically adds UTM parameters to external links to maintain attribution tracking across domains:
### Automatic UTM Passing
When a user clicks an external link, the SDK automatically:
1. Detects if the link is to a different domain
2. Checks if the domain should be excluded
3. Adds current UTM parameters to the URL
4. Tracks the enhanced link click
### Configuration
```javascript
// Enable cross-domain UTM passing, default is enableCrossDomainUTM = true
await init({
apiKey: "your_api_key_here",
enableCrossDomainUTM: true,
crossDomainUTMParams: ["utm_source", "utm_medium", "utm_campaign"],
excludeDomains: ["google.com", "facebook.com"], // Exclude specific domains
});
```
### Manual UTM URL Enhancement
```javascript
// Get SDK instance
const sdk = window.getuaiSDK;
// Manually add UTM parameters to any URL
const enhancedURL = sdk.addUTMToURL("https://example.com/page");
// Get current UTM parameters
const utmParams = sdk.getCurrentUTMParams();
console.log(utmParams); // { utm_source: 'google', utm_medium: 'cpc', ... }
```
### Example
If a user visits your site with `?utm_source=google&utm_medium=cpc&utm_campaign=summer_sale`,
and then clicks a link to `https://partner-site.com/product`, the SDK will automatically
modify the link to:
`https://partner-site.com/product?utm_source=google&utm_medium=cpc&utm_campaign=summer_sale`
## Storage
The SDK uses two storage mechanisms:
### LocalStorage
- Stores UTM attribution data
- Stores user session information
- 30-day retention period
- ~5MB storage limit
### IndexedDB
- Stores event queue for offline processing
- Up to ~100MB storage
- 7-day cleanup for old events
- Automatic retry on connection restore
## Offline Support
The SDK automatically handles offline scenarios:
1. Events are queued in IndexedDB when offline
2. Events are sent when connection is restored
3. Failed requests are retried with exponential backoff
4. Critical events (purchases, logins) are sent immediately when possible
## Error Handling
The SDK includes comprehensive error handling:
```javascript
try {
await trackEvent(
EventType.PURCHASE_COMPLETE,
{ amount: 99.99 },
"user_123",
99.99
);
} catch (error) {
console.error("Failed to track purchase:", error);
// Event will be queued for retry
}
```
## Debug Mode
Enable debug mode to see detailed logs:
```html
<script
src="https://unpkg.com/getu-attribution-sdk@0.2.2/dist/getuai-attribution.min.js"
data-api-key="your_api_key_here"
data-debug="true"
></script>
```
Or programmatically:
```javascript
await init({
apiKey: "your_api_key_here",
enableDebug: true,
});
```
## Advanced Usage
### Static Method Usage (Recommended)
You can use static methods directly on the AttributionSDK class:
```javascript
// Initialize SDK
await AttributionSDK.init({
apiKey: "your_api_key_here",
autoTrack: true,
autoTrackPageView: true, // Automatically track page view on initialization
});
// Track events using static methods
await AttributionSDK.trackEvent(
EventType.PURCHASE_COMPLETE,
{ product_id: "123" },
"user_123",
99.99
);
await AttributionSDK.trackPageView();
await AttributionSDK.trackPurchase("user_123", 99.99);
await AttributionSDK.trackLogin("user_123", { method: "email" });
await AttributionSDK.trackSignup("user_123", { method: "email" });
// Get attribution data
const attributionData = AttributionSDK.getAttributionData();
// Add UTM to URL
const enhancedURL = AttributionSDK.addUTMToURL("https://example.com");
// Get current UTM parameters
const utmParams = AttributionSDK.getCurrentUTMParams();
// Flush pending events
await AttributionSDK.flush();
// Get SDK status
const status = AttributionSDK.getStatus();
// Destroy SDK
AttributionSDK.destroy();
```
### Custom SDK Instance
```javascript
import { AttributionSDK } from "getu-attribution-sdk";
const sdk = new AttributionSDK({
apiKey: "your_api_key_here",
enableDebug: true,
autoTrackPageView: true, // Automatically track page view on initialization
});
await sdk.init();
await sdk.trackEvent(EventType.PAGE_VIEW);
```
### Global Function Usage
```javascript
import { init, trackEvent, flush, destroy } from "getu-attribution-sdk";
// Initialize SDK
await init({
apiKey: "your_api_key_here",
enableDebug: true,
autoTrackPageView: true, // Automatically track page view on initialization
});
// Track events
await trackEvent(
EventType.PURCHASE_COMPLETE,
{ product_id: "123" },
"user_123",
99.99
);
// Flush events
await flush();
// Destroy SDK
destroy();
```
### Global Window Object Usage
When using the CDN version, all functions are available on the global `window` object:
```javascript
// Initialize SDK
await window.getuaiSDK.init({
apiKey: "your_api_key_here",
enableDebug: true,
autoTrackPageView: true, // Automatically track page view on initialization
});
// Track events
await window.getuaiSDK.trackEvent(
window.getuaiSDK.EventType.PURCHASE_COMPLETE,
{ product_id: "123" },
"user_123",
99.99
);
// Get attribution data
const attribution = window.getuaiSDK.getAttributionData();
// Add UTM to URL
const enhancedURL = window.getuaiSDK.addUTMToURL("https://example.com");
// Get current UTM parameters
const utmParams = window.getuaiSDK.getCurrentUTMParams();
// Flush events
await window.getuaiSDK.flush();
// Get status
const status = window.getuaiSDK.getStatus();
// Destroy SDK
window.getuaiSDK.destroy();
```
## API Reference
### Core Functions
#### `init(config: SDKConfig): Promise<AttributionSDK>`
Initialize the SDK with configuration.
#### `getSDK(): AttributionSDK | null`
Get the current SDK instance.
#### `waitForSDK(): Promise<AttributionSDK>`
Wait for the SDK to be ready (useful when using auto-initialization).
### Event Tracking Functions
#### `trackEvent(eventType: EventType, eventData?: Record<string, any>, tracking_user_id?: string, revenue?: number, currency?: Currency): Promise<void>`
Track a custom event.
#### `trackPageView(pageData?: Record<string, any>, tracking_user_id?:string): Promise<void>`
Track a page view event.
#### `trackPurchase(tracking_user_id: string, revenue: number, currency?: Currency, purchaseData?: Record<string, any>): Promise<void>`
Track a purchase event.
#### `trackLogin(tracking_user_id: string, loginData?: Record<string, any>): Promise<void>`
Track a login event.
#### `trackSignup(tracking_user_id: string, signupData?: Record<string, any>): Promise<void>`
Track a signup event.
#### `trackFormSubmit(tracking_user_id?: string, formData?: Record<string, any>): Promise<void>`
Track a form submission event.
### Attribution Functions
#### `getAttributionData(): AttributionData | null`
Get the current attribution data including first touch, last touch, and touchpoints.
#### `addUTMToURL(url: string): string`
Add current UTM parameters to a URL.
#### `getCurrentUTMParams(): Record<string, string>`
Get the current UTM parameters.
### Utility Functions
#### `flush(): Promise<void>`
Flush all pending events to the server.
#### `getStatus(): SDKStatus | null`
Get the current SDK status including initialization state, session info, queue size, and online status.
#### `destroy(): void`
Destroy the SDK instance and clean up resources.
## Browser Support
- Chrome 50+
- Firefox 50+
- Safari 10+
- Edge 79+
## TypeScript
The SDK includes full TypeScript support:
```typescript
import {
init,
trackEvent,
EventType,
Currency,
type SDKConfig,
type EventData,
type AttributionData,
} from "getu-attribution-sdk";
const config: SDKConfig = {
apiKey: "your_api_key_here",
enableDebug: true,
};
await init(config);
const eventData: Partial<EventData> = {
event_type: EventType.PURCHASE_COMPLETE,
revenue: 99.99,
currency: Currency.USD,
};
```