JavaScript SDK
import { Aside, Tabs, TabItem } from ‘@astrojs/starlight/components’;
The analyze.swiss JavaScript SDK provides full control over event tracking, user identification, and analytics configuration.
Installation
Section titled “Installation”```javascriptimport { Analyze } from '@analyze.swiss/sdk';
const analyze = new Analyze({ apiKey: 'YOUR_API_KEY'});```Global Object
Section titled “Global Object”When using the script tag, the SDK is available globally as window.analyze:
// Track an eventanalyze.track('button_click', { button_id: 'signup' });
// Identify a useranalyze.identify('user_123', { email: 'user@example.com' });Core Methods
Section titled “Core Methods”track(eventName, properties?)
Section titled “track(eventName, properties?)”Track a custom event with optional properties.
// Simple eventanalyze.track('page_viewed');
// Event with propertiesanalyze.track('product_added', { product_id: 'SKU-123', product_name: 'Premium Plan', price: 99.00, currency: 'USD'});
// Event with callbackanalyze.track('signup_completed', { plan: 'pro' }, () => { console.log('Event tracked successfully');});Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
eventName | string | Yes | Name of the event |
properties | object | No | Additional event data |
callback | function | No | Called after event is sent |
identify(userId, traits?)
Section titled “identify(userId, traits?)”Identify the current user and associate them with their actions.
// Basic identificationanalyze.identify('user_123');
// With user traitsanalyze.identify('user_123', { email: 'john@example.com', name: 'John Doe', plan: 'enterprise', created_at: '2024-01-15', company: { id: 'company_456', name: 'Acme Inc', industry: 'Technology' }});Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
userId | string | Yes | Unique user identifier |
traits | object | No | User properties/attributes |
set(properties) / unset(propertyKeys)
Section titled “set(properties) / unset(propertyKeys)”Set or remove super properties that are sent with every event.
// Set super propertiesanalyze.set({ app_version: '2.1.0', environment: 'production', user_type: 'premium'});
// All subsequent events include these propertiesanalyze.track('feature_used'); // Includes app_version, environment, user_type
// Remove a super propertyanalyze.unset(['environment']);reset()
Section titled “reset()”Clear the current user identity and start a new anonymous session.
// After user logs outanalyze.reset();pageview(properties?)
Section titled “pageview(properties?)”Manually track a pageview. Useful for SPAs.
// Basic pageviewanalyze.pageview();
// With custom propertiesanalyze.pageview({ page_category: 'pricing', experiment_variant: 'A'});Configuration Options
Section titled “Configuration Options”const analyze = new Analyze({ // Required apiKey: 'pk_live_xxxxx',
// Optional autoCapture: true, // Auto-track events (default: true) trackLocalhost: false, // Track on localhost (default: false) respectDnt: true, // Respect Do Not Track (default: true) maskInputs: true, // Mask sensitive inputs (default: true) crossDomain: ['site1.com', 'site2.com'], // Cross-domain tracking
// Advanced batchSize: 10, // Events per batch (default: 10) batchTimeout: 5000, // Batch timeout in ms (default: 5000) maxRetries: 3, // Retry failed requests (default: 3) debug: false // Enable debug logging (default: false)});Auto-Captured Events
Section titled “Auto-Captured Events”With autoCapture: true, the SDK automatically tracks:
| Event | Description | Properties |
|---|---|---|
$pageview | Page navigation | doc_path, page_title, referrer |
$click | Element clicks | element_tag, element_text, element_classes |
$form_submit | Form submissions | form_id, form_action |
$scroll_depth | Scroll milestones | depth (25, 50, 75, 100) |
$engagement | Time on page | engagement_time_ms, total_time_ms |
$outbound_click | External links | href, text |
$download | File downloads | file_url, file_extension |
$rage_click | Repeated fast clicks | element_tag, click_count |
Excluding Elements from Auto-Capture
Section titled “Excluding Elements from Auto-Capture”Add the data-analyze-ignore attribute to exclude elements:
<!-- This button won't be tracked --><button data-analyze-ignore>Don't Track Me</button>
<!-- Exclude entire sections --><div data-analyze-ignore> <button>Not tracked</button> <a href="/link">Not tracked</a></div>E-commerce Tracking
Section titled “E-commerce Tracking”Track e-commerce events with our standard schema:
// Product viewedanalyze.track('$product_viewed', { product_id: 'SKU-123', name: 'Premium Widget', price: 49.99, currency: 'USD', category: 'Widgets'});
// Added to cartanalyze.track('$cart_add', { product_id: 'SKU-123', quantity: 2, price: 49.99});
// Checkout startedanalyze.track('$checkout_started', { cart_total: 99.98, item_count: 2});
// Order completedanalyze.track('$order_completed', { order_id: 'ORD-456', revenue: 99.98, currency: 'USD', products: [ { product_id: 'SKU-123', quantity: 2, price: 49.99 } ]});SaaS Tracking
Section titled “SaaS Tracking”Track SaaS-specific events:
// User signed upanalyze.track('$signup', { plan: 'free', source: 'organic'});
// User activated (completed onboarding)analyze.track('$activated', { time_to_activate_hours: 2});
// Subscription startedanalyze.track('$subscription_started', { plan: 'pro', mrr: 49, billing_cycle: 'monthly'});
// Feature usedanalyze.track('$feature_used', { feature_name: 'export_csv', feature_category: 'data'});Error Handling
Section titled “Error Handling”try { analyze.track('event', { data: 'value' });} catch (error) { console.error('Tracking failed:', error);}
// Or with callbacksanalyze.track('event', { data: 'value' }, (error, response) => { if (error) { console.error('Failed:', error); } else { console.log('Success:', response); }});TypeScript Support
Section titled “TypeScript Support”The SDK includes TypeScript definitions:
import { Analyze, TrackOptions, IdentifyOptions } from '@analyze.swiss/sdk';
interface UserTraits { email: string; name: string; plan: 'free' | 'pro' | 'enterprise';}
const analyze = new Analyze({ apiKey: 'YOUR_KEY' });
// Typed identificationanalyze.identify<UserTraits>('user_123', { email: 'user@example.com', name: 'John', plan: 'pro'});Debug Mode
Section titled “Debug Mode”Enable debug mode to see all SDK activity in the console:
// Via configurationconst analyze = new Analyze({ apiKey: 'YOUR_KEY', debug: true});
// Or via script attribute<script src="https://analyze-ingest.thismatters.workers.dev/s/a.js" data-api-key="YOUR_KEY" data-debug="true" defer></script>Next Steps
Section titled “Next Steps”- React SDK – React-specific integration
- Next.js SDK – Next.js optimized SDK
- Server API – Backend event tracking