JSPM

@codenificient/analytics-sdk

2.0.0
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 256
  • Score
    100M100P100Q89188F
  • License MIT

TypeScript SDK for multi-tenant analytics tracking with real-time insights and geolocation support

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

bun add @codenificient/analytics-sdk
# Or with npm
npm install @codenificient/analytics-sdk
# Or with yarn
yarn 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"
);

CRUD Operation Tracking

Track database operations for real-time visibility into your app's data flow.

create(resource: string, properties?: object)

Track when a resource is created.

await analytics.create("user", {
  userId: "user-123",
  email: "user@example.com",
});

await analytics.create("post", {
  postId: "post-456",
  authorId: "user-123",
  title: "My First Post",
});
read(resource: string, properties?: object)

Track when a resource is fetched/read.

await analytics.read("user", {
  userId: "user-123",
});

await analytics.read("posts", {
  filter: "published",
  limit: 10,
});
update(resource: string, properties?: object)

Track when a resource is updated.

await analytics.update("user", {
  userId: "user-123",
  fields: ["name", "avatar"],
});

await analytics.update("settings", {
  setting: "theme",
  value: "dark",
});
delete(resource: string, properties?: object)

Track when a resource is deleted.

await analytics.delete("post", {
  postId: "post-456",
  reason: "user-requested",
});

Error Tracking

Capture and track errors for debugging and monitoring.

error(errorType: string, properties?: object)

Track a general error event.

await analytics.error("validation_error", {
  field: "email",
  message: "Invalid email format",
});

await analytics.error("auth_failed", {
  reason: "invalid_credentials",
  attemptCount: 3,
});
exception(error: Error, properties?: object)

Track a JavaScript exception with full stack trace.

try {
  await riskyOperation();
} catch (err) {
  await analytics.exception(err as Error, {
    context: "payment-processing",
    userId: "user-123",
  });
}
apiError(endpoint: string, statusCode: number, properties?: object)

Track API errors with endpoint and status code.

await analytics.apiError("/api/users", 500, {
  requestId: "req-789",
  message: "Internal server error",
});

await analytics.apiError("/api/auth/login", 401, {
  reason: "token_expired",
});
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=true

TypeScript 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.

🆘 Support