@wondercore/custom-analytics-sdk
v2.1.2
Published
A flexible, privacy-compliant analytics SDK for tracking user behavior and conversions
Readme
Custom Analytics SDK
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.
Features
- 🎯 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
Installation
npm install custom-analytics-sdkQuick Start
ES6 Modules
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" });API Reference
Initialization
init(config?)
Initialize the analytics SDK with configuration options.
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,
});Core Methods
track(eventName, properties?, options?)
Track any custom event with optional properties.
analytics.track("video_play", {
video_title: "Product Demo",
video_duration: 120,
video_position: 0,
});trackPageView(properties?)
Track page views (auto-tracked by default).
analytics.trackPageView({
page_category: "product",
user_type: "premium",
});trackClick(element, properties?)
Track element clicks with automatic element data extraction.
document.querySelector("#cta-button").addEventListener("click", (e) => {
analytics.trackClick(e.target, { campaign: "summer-sale" });
});User Management
identify(userId, properties?)
Associate events with a specific user ID.
analytics.identify("user_12345", {
email: "[email protected]",
plan: "premium",
signup_date: "2025-01-15",
});reset()
Reset user session and generate new IDs (including trackId).
// Call on logout
analytics.reset();Utility Methods
flush()
Immediately send all queued events.
analytics.flush();destroy()
Stop all tracking and cleanup resources.
analytics.destroy();Properties
Access SDK properties and status:
// 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) - Example:
"sess_a3f5b8c2" - 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) - Example:
"tk_a3f5b8c2d1e4f6a72" - Storage: Synced across sessionStorage, cookie (10 years), and localStorage
- Validation: Automatic format and checksum verification
- Purpose: Track unique visits with persistent cross-session identification
Auto-Tracking Features
When autoTrack: true, the SDK automatically tracks:
- Page Views: On initial load and route changes
- Click Events: Buttons, links, and elements with
data-trackattribute - Form Submissions: All form submit events
Custom Auto-Tracking
Add data-track attribute to any element:
<button data-track="signup-cta">Sign Up Now</button>
<a href="/pricing" data-track="pricing-link">View Pricing</a>Privacy & Compliance
GDPR Compliance
The SDK automatically respects privacy settings and Do Not Track headers:
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");
}Cookie Management
// 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).
Backend Integration
Expected API Format
Your backend should expect POST requests to the configured endpoint:
// 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,
},
];Event Versioning
All events include a version field indicating the SDK version that generated them:
{
"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
versionfield, treat it as version1.0.0(legacy) - Events from v2.0.0+ include the
trackIdfield for unique visit identification - The
trackIdformat istk_<16 hex chars><1 checksum char>with automatic validation - Events from v2.1.0+ use enhanced
sessionIdformat:sess_<8 hex chars>
Version History & Changes
v2.1.0 (Current)
- Enhanced Session ID Format
- Old format:
sess_<timestamp>_<random base36>(e.g.,sess_1756805723800_grpksxw40) - New format:
sess_<8-char SHA-256 hash>(e.g.,sess_a3f5b8c2) - More concise and consistent with trackId format
- Cryptographically generated for better uniqueness
- Old format:
v2.0.0
- 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
License
MIT License - see LICENSE file for details.
