A flexible, privacy-compliant analytics SDK for tracking user behavior and conversions
A flexible, privacy-compliant analytics SDK for tracking user behavior, conversions, and marketing attribution. Built as an alternative to Google Analytics with full customization control.
- 🎯 Advanced User Identification: Fingerprinting + cookies + localStorage
- 🆔 TrackId Multi-Storage Sync: Persistent visit tracking across sessionStorage, cookie, and localStorage
- 🔒 Privacy Compliant: GDPR/CCPA ready with consent management
- 📊 Comprehensive Tracking: Page views, clicks, conversions, purchases
- 🚀 Performance Optimized: Batched requests, async processing
- 📱 Cross-Platform: Works on web, mobile, and desktop
- 🛡️ Ad Blocker Resistant: Uses custom endpoints
- 📈 Marketing Attribution: Full UTM parameter support
- 🔧 Highly Configurable: Customize everything
- ✅ Data Validation: Built-in checksum validation for tracking IDs
``html`
npm install custom-analytics-sdk
`javascript
import analytics from "custom-analytics-sdk";
// Initialize the SDK
analytics.init({
endpoint: "https://your-api.com/analytics/events",
debug: true,
});
// Track events
analytics.track("button_click", { button_name: "signup" });
analytics.trackPageView({ page_type: "landing" });
analytics.trackClick(element, { campaign: "signup" });
`
#### init(config?)
Initialize the analytics SDK with configuration options.
`javascript
import analytics from "custom-analytics-sdk";
analytics.init({
endpoint: "https://your-api.com/analytics/events",
batchSize: 10,
flushInterval: 5000,
enableFingerprinting: true,
respectDoNotTrack: true,
debug: true,
autoTrack: true,
});
`
#### track(eventName, properties?, options?)
Track any custom event with optional properties.
`javascript`
analytics.track("video_play", {
video_title: "Product Demo",
video_duration: 120,
video_position: 0,
});
#### trackPageView(properties?)
Track page views (auto-tracked by default).
`javascript`
analytics.trackPageView({
page_category: "product",
user_type: "premium",
});
#### trackClick(element, properties?)
Track element clicks with automatic element data extraction.
`javascript`
document.querySelector("#cta-button").addEventListener("click", (e) => {
analytics.trackClick(e.target, { campaign: "summer-sale" });
});
#### identify(userId, properties?)
Associate events with a specific user ID.
`javascript`
analytics.identify("user_12345", {
email: "user@example.com",
plan: "premium",
signup_date: "2025-01-15",
});
#### reset()
Reset user session and generate new IDs (including trackId).
`javascript`
// Call on logout
analytics.reset();
#### flush()
Immediately send all queued events.
`javascript`
analytics.flush();
#### destroy()
Stop all tracking and cleanup resources.
`javascript`
analytics.destroy();
Access SDK properties and status:
`javascript
// Check if initialized
if (analytics.isInitialized) {
console.log("SDK is ready");
}
// Get user identifiers
console.log("Fingerprint ID:", analytics.fingerprintId);
console.log("User ID:", analytics.userId);
console.log("Session ID:", analytics.sessionId);
console.log("Track ID:", analytics.trackId); // NEW in v
// Get current configuration
console.log("Config:", analytics.config);
`
#### New in v2.1.0: Enhanced Session ID
The session ID now uses cryptographic hash generation:
- Format: sess_<8 hex chars> (13 characters total)"sess_a3f5b8c2"
- Example:
- Generation: SHA-256 hash of timestamp + random value
- Storage: sessionStorage only (cleared when tab/window closes)
- Purpose: Unique identifier per browser session
#### New in v2.0.0: TrackId
The SDK now includes a trackId field that uniquely identifies each visit:
- Format: tk_<16 hex chars><1 checksum char> (20 chars total)"tk_a3f5b8c2d1e4f6a72"
- Example:
- Storage: Synced across sessionStorage, cookie (10 years), and localStorage
- Validation: Automatic format and checksum verification
- Purpose: Track unique visits with persistent cross-session identification
When autoTrack: true, the SDK automatically tracks:
- Page Views: On initial load and route changes
- Click Events: Buttons, links, and elements with data-track attribute
- Form Submissions: All form submit events
Add data-track attribute to any element:
`html`
View Pricing
The SDK automatically respects privacy settings and Do Not Track headers:
`javascript
import analytics from "custom-analytics-sdk";
// Initialize with privacy-first settings
analytics.init({
endpoint: "/analytics/events",
respectDoNotTrack: true,
enableFingerprinting: false, // Disable for stricter privacy
cookieDuration: 30, // Limit cookie duration
debug: true,
});
// Check if tracking is allowed
if (analytics.isInitialized) {
analytics.track("page_view");
} else {
console.log("Tracking blocked due to privacy settings");
}
`
`javascript`
// The SDK uses cookies for user identification
// Configure cookie settings during initialization
analytics.init({
cookieName: "custom_analytics_id", // Custom cookie name
cookieDuration: 365, // Days to keep the cookie
respectDoNotTrack: true, // Respect browser DNT header
...
});
Note on TrackId Cookie: In v2.0.0+, a separate cookie named analytics_track_id is automatically created with a 10-year duration for persistent visit tracking. This cookie is always set and does not require user consent configuration (it's considered functional, not tracking).
Your backend should expect POST requests to the configured endpoint:
`javascript`
// POST /analytics/events
[
{
version: "2.1.0",
fingerprintId: "fp_db535991d396a731",
userId: null,
sessionId: "sess_a3f5b8c2", // UPDATED in v2.1.0 - now uses SHA-256 hash
trackId: "tk_a3f5b8c2d1e4f6a72", // NEW in v2.0.0
projectId: null,
debug: false,
event: "click",
properties: {
tag_name: "button",
id: "",
class_name: "",
text: "點我",
data_track: null,
},
ctx: {
viewport: "390x844",
screen: "390x844",
user_agent:
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Safari/605.1.15",
language: "zh-TW",
timezone: "Asia/Taipei",
timestamp_local: "2025-09-02T09:36:34.083Z",
},
timestamp: 1756805794083,
url: "http://localhost:3000/",
utm_source: null,
utm_medium: null,
utm_campaign: null,
utm_content: null,
utm_term: null,
},
];
All events include a version field indicating the SDK version that generated them:
`javascript`
{
"version": "2.1.0", // SDK version
"event": "click",
"sessionId": "sess_a3f5b8c2", // UPDATED in v2.1.0 - SHA-256 hash format
"trackId": "tk_a3f5b8c2d1e4f6a72", // NEW in v2.0.0
// ... other fields
}
Important Notes:
- If an event does not have a version field, treat it as version 1.0.0 (legacy)trackId
- Events from v2.0.0+ include the field for unique visit identificationtrackId
- The format is tk_<16 hex chars><1 checksum char> with automatic validationsessionId
- Events from v2.1.0+ use enhanced format: sess_<8 hex chars>
#### v2.1.0 (Current)
1. Enhanced Session ID Format
- Old format: sess_ (e.g., sess_1756805723800_grpksxw40)sess_<8-char SHA-256 hash>
- New format: (e.g., sess_a3f5b8c2)
- More concise and consistent with trackId format
- Cryptographically generated for better uniqueness
#### v2.0.0
1. New Event Field: All events now include trackId`
- Your backend should be updated to handle this new field
- Provides unique visit identification with multi-storage persistence
- TrackId is synced across sessionStorage, cookie (10 years), and localStorage
MIT License - see LICENSE file for details.