Skip to content

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.

```html ``` ```bash npm install @analyze.swiss/sdk ```
```javascript
import { Analyze } from '@analyze.swiss/sdk';
const analyze = new Analyze({
apiKey: 'YOUR_API_KEY'
});
```

When using the script tag, the SDK is available globally as window.analyze:

// Track an event
analyze.track('button_click', { button_id: 'signup' });
// Identify a user
analyze.identify('user_123', { email: 'user@example.com' });

Track a custom event with optional properties.

// Simple event
analyze.track('page_viewed');
// Event with properties
analyze.track('product_added', {
product_id: 'SKU-123',
product_name: 'Premium Plan',
price: 99.00,
currency: 'USD'
});
// Event with callback
analyze.track('signup_completed', { plan: 'pro' }, () => {
console.log('Event tracked successfully');
});

Parameters:

ParameterTypeRequiredDescription
eventNamestringYesName of the event
propertiesobjectNoAdditional event data
callbackfunctionNoCalled after event is sent

Identify the current user and associate them with their actions.

// Basic identification
analyze.identify('user_123');
// With user traits
analyze.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:

ParameterTypeRequiredDescription
userIdstringYesUnique user identifier
traitsobjectNoUser properties/attributes

Set or remove super properties that are sent with every event.

// Set super properties
analyze.set({
app_version: '2.1.0',
environment: 'production',
user_type: 'premium'
});
// All subsequent events include these properties
analyze.track('feature_used'); // Includes app_version, environment, user_type
// Remove a super property
analyze.unset(['environment']);

Clear the current user identity and start a new anonymous session.

// After user logs out
analyze.reset();

Manually track a pageview. Useful for SPAs.

// Basic pageview
analyze.pageview();
// With custom properties
analyze.pageview({
page_category: 'pricing',
experiment_variant: 'A'
});
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)
});

With autoCapture: true, the SDK automatically tracks:

EventDescriptionProperties
$pageviewPage navigationdoc_path, page_title, referrer
$clickElement clickselement_tag, element_text, element_classes
$form_submitForm submissionsform_id, form_action
$scroll_depthScroll milestonesdepth (25, 50, 75, 100)
$engagementTime on pageengagement_time_ms, total_time_ms
$outbound_clickExternal linkshref, text
$downloadFile downloadsfile_url, file_extension
$rage_clickRepeated fast clickselement_tag, click_count

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>

Track e-commerce events with our standard schema:

// Product viewed
analyze.track('$product_viewed', {
product_id: 'SKU-123',
name: 'Premium Widget',
price: 49.99,
currency: 'USD',
category: 'Widgets'
});
// Added to cart
analyze.track('$cart_add', {
product_id: 'SKU-123',
quantity: 2,
price: 49.99
});
// Checkout started
analyze.track('$checkout_started', {
cart_total: 99.98,
item_count: 2
});
// Order completed
analyze.track('$order_completed', {
order_id: 'ORD-456',
revenue: 99.98,
currency: 'USD',
products: [
{ product_id: 'SKU-123', quantity: 2, price: 49.99 }
]
});

Track SaaS-specific events:

// User signed up
analyze.track('$signup', {
plan: 'free',
source: 'organic'
});
// User activated (completed onboarding)
analyze.track('$activated', {
time_to_activate_hours: 2
});
// Subscription started
analyze.track('$subscription_started', {
plan: 'pro',
mrr: 49,
billing_cycle: 'monthly'
});
// Feature used
analyze.track('$feature_used', {
feature_name: 'export_csv',
feature_category: 'data'
});
try {
analyze.track('event', { data: 'value' });
} catch (error) {
console.error('Tracking failed:', error);
}
// Or with callbacks
analyze.track('event', { data: 'value' }, (error, response) => {
if (error) {
console.error('Failed:', error);
} else {
console.log('Success:', response);
}
});

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 identification
analyze.identify<UserTraits>('user_123', {
email: 'user@example.com',
name: 'John',
plan: 'pro'
});

Enable debug mode to see all SDK activity in the console:

// Via configuration
const 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>