Package Exports
- @codenificient/analytics-sdk
Readme
@codenificient/analytics-sdk
A powerful TypeScript SDK for multi-tenant analytics tracking with real-time insights, geolocation support, and comprehensive event management.
✨ Features
- 🚀 Real-time Analytics - Track events with instant processing
- 🌍 Geolocation Support - Automatic country and region detection
- 🏢 Multi-tenant Architecture - Support for multiple projects and API keys
- 📊 Comprehensive Tracking - Page views, custom events, and batch operations
- 🔒 TypeScript First - Full type safety and IntelliSense support
- 📱 Universal Compatibility - Works in browsers and Node.js environments
- ⚡ Lightweight - Minimal bundle size with maximum functionality
📦 Installation
npm install @codenificient/analytics-sdkyarn add @codenificient/analytics-sdk🚀 Quick Start
Basic Setup
import { Analytics } from "@codenificient/analytics-sdk";
const analytics = new Analytics({
apiKey: "your-api-key",
endpoint: "https://your-analytics-api.com",
});
// Track a page view
await analytics.pageView("/home");
// Track a custom event
await analytics.track("button-click", {
buttonId: "cta-button",
page: "/home",
userId: "user-123",
});Advanced Usage
import { Analytics } from "@codenificient/analytics-sdk";
const analytics = new Analytics({
apiKey: "your-api-key",
endpoint: "https://your-analytics-api.com",
debug: true, // Enable debug logging
});
// Track multiple events in batch
await analytics.trackBatch([
{
event: "page-view",
properties: { page: "/dashboard", userId: "user-123" },
},
{
event: "feature-used",
properties: { feature: "export-data", timestamp: Date.now() },
},
]);
// Track with custom namespace
await analytics.track(
"user-action",
{
action: "profile-update",
metadata: { fields: ["name", "email"] },
},
"user-events"
);📚 API Reference
Analytics Class
Constructor Options
interface AnalyticsOptions {
apiKey: string; // Required: Your analytics API key
endpoint?: string; // Optional: Analytics API endpoint (default: auto-detect)
debug?: boolean; // Optional: Enable debug logging (default: false)
timeout?: number; // Optional: Request timeout in ms (default: 5000)
}Methods
pageView(url: string, properties?: object)
Track a page view event.
await analytics.pageView("/dashboard", {
title: "User Dashboard",
referrer: "https://google.com",
userId: "user-123",
});track(event: string, properties?: object, namespace?: string)
Track a custom event.
await analytics.track(
"button-click",
{
buttonId: "cta-button",
page: "/home",
value: 29.99,
},
"user-interactions"
);trackBatch(events: EventData[])
Track multiple events in a single request.
await analytics.trackBatch([
{
event: "page-view",
properties: { page: "/home" },
},
{
event: "button-click",
properties: { buttonId: "signup" },
},
]);blogView(slug: string, properties?: object)
Track a blog post view with automatic categorization.
await analytics.blogView("getting-started-with-analytics", {
category: "tutorial",
readTime: 5,
});click(element: string, properties?: object)
Track click events with element identification.
await analytics.click("header-cta", {
position: "top-right",
text: "Get Started",
});custom(event: string, properties?: object, namespace?: string)
Track custom events with full flexibility.
await analytics.custom(
"purchase-completed",
{
orderId: "order-123",
amount: 99.99,
currency: "USD",
items: ["product-a", "product-b"],
},
"ecommerce"
);getAnalytics(projectId?: string)
Retrieve analytics data for a project.
const data = await analytics.getAnalytics("my-project");
console.log(data.totalVisitors, data.topCountries);🌍 Geolocation Features
The SDK automatically detects and includes geolocation data:
- Country Detection - Automatic country identification from IP
- Region & City - Detailed location information
- Timezone - User's timezone for accurate time tracking
- Privacy Compliant - No personal data collection
🏢 Multi-tenant Support
Project Management
// Each project has its own API key
const projectAnalytics = new Analytics({
apiKey: "project-specific-api-key",
});
// Track events for specific project
await projectAnalytics.track("feature-used", {
feature: "advanced-search",
});Namespace Organization
// Organize events by namespace
await analytics.track("user-login", {}, "authentication");
await analytics.track("data-export", {}, "user-actions");
await analytics.track("error-occurred", {}, "system-events");🔧 Configuration
Environment Variables
# .env
ANALYTICS_API_KEY=your-api-key
ANALYTICS_ENDPOINT=https://your-analytics-api.com
ANALYTICS_DEBUG=trueTypeScript Configuration
// tsconfig.json
{
"compilerOptions": {
"moduleResolution": "node",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
}
}📊 Data Structure
Event Properties
interface EventProperties {
// Page information
page?: string;
title?: string;
referrer?: string;
// User information
userId?: string;
sessionId?: string;
// Geolocation (auto-populated)
country?: string;
region?: string;
city?: string;
timezone?: string;
// Custom properties
[key: string]: any;
}Analytics Response
interface AnalyticsData {
totalVisitors: number;
visitorsToday: number;
avgVisitorsDaily: string;
topCountries: Array<{
country: string;
count: number;
}>;
timeseriesData: Array<{
date: string;
events: Array<{ [key: string]: number }>;
}>;
}🚨 Error Handling
try {
await analytics.track("important-event", { data: "value" });
} catch (error) {
console.error("Analytics tracking failed:", error);
// Handle error appropriately
}🔍 Debugging
Enable debug mode to see detailed logging:
const analytics = new Analytics({
apiKey: "your-api-key",
debug: true,
});
// Debug logs will show:
// - API requests and responses
// - Event processing details
// - Error information📈 Performance
- Lightweight - ~15KB minified and gzipped
- Efficient - Batch processing for multiple events
- Non-blocking - Async operations don't block UI
- Retry Logic - Automatic retry for failed requests
🤝 Contributing
We welcome contributions! Please see our Contributing Guide for details.
📄 License
MIT License - see LICENSE for details.