Skip to content

JavaScript SDK

import { Aside, Tabs, TabItem } from ‘@astrojs/starlight/components’;

The analyze.rocks JavaScript SDK provides full control over event tracking, user identification, and analytics configuration.

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

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',
host: 'https://ingest.analyze.rocks',
// 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
// Privacy
cookiePolicy: 'keep', // 'keep', 'anonymize', 'none'
ipPolicy: 'keep', // 'keep', 'anonymize', 'none'
// Advanced
batchSize: 20, // Events per batch (default: 20)
batchTimeout: 10000, // Batch timeout in ms (default: 10000)
maxRetries: 3, // Retry failed requests (default: 3)
debug: false // Enable debug logging (default: false)
});
AttributeDescriptionDefault
data-keyYour public API key (required)-
data-hostIngest endpoint URLhttps://ingest.analyze.rocks
data-cookieCookie policy: keep, anonymize, nonekeep
data-ipIP policy: keep, anonymize, nonekeep
data-debugEnable debug modefalse
data-user-idPre-set user ID-
data-user-emailPre-set user email-

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
$dead_clickClicks with no responseelement_tag, element_selector

Das SDK erfasst automatisch Core Web Vitals mit dem optionalen perf.js Modul:

MetricDescription
LCPLargest Contentful Paint
FIDFirst Input Delay
CLSCumulative Layout Shift
FCPFirst Contentful Paint
TTFBTime to First Byte
INPInteraction to Next Paint
<!-- Mit Performance-Tracking -->
<script src="https://ingest.analyze.rocks/s/a.js" data-key="YOUR_KEY" defer></script>
<script src="https://ingest.analyze.rocks/s/perf.js" defer></script>

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.rocks/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',
host: 'https://ingest.analyze.rocks',
debug: true
});
// Or via script attribute
<script
src="https://ingest.analyze.rocks/s/a.js"
data-key="YOUR_KEY"
data-debug="true"
defer>
</script>

Set properties that persist for the current session:

// Set session properties
analyze.setSessionProperties({
experiment_variant: 'B',
referral_code: 'FRIEND10'
});
// These properties are included in all subsequent events

Das SDK sendet Events automatisch, wenn:

  • Der Tab in den Hintergrund wechselt (visibility change)
  • Die Seite geschlossen wird (beforeunload)
  • Der Batch-Timeout erreicht wird (10 Sekunden)
  • Die Batch-Größe erreicht wird (20 Events)

Dies stellt sicher, dass keine Events verloren gehen.