pwa-analytics-sdk
v1.0.2
Published
Analytics SDK for sending events to analytics backend
Maintainers
Readme
Analytics SDK
A TypeScript SDK for sending analytics events to your analytics backend with batching, retry logic, and TypeScript support.
Installation
npm install analytics-sdkQuick Start
import { AnalyticsSDK } from 'analytics-sdk';
// Initialize the SDK
const analytics = new AnalyticsSDK({
apiKey: 'your-api-key',
baseUrl: 'https://your-analytics-api.com',
batchSize: 10,
flushInterval: 5000, // 5 seconds
});
// Track an event
analytics.track({
eventName: 'button_click',
userId: 'user-123',
payload: {
buttonId: 'submit-btn',
page: 'checkout'
}
});
// Track with all options
analytics.track({
eventName: 'page_view',
userId: 'user-123',
sessionId: 'session-456',
anonymousId: 'anon-789',
pageUrl: 'https://example.com/checkout',
referrer: 'https://example.com/cart',
payload: {
category: 'ecommerce',
value: 99.99
},
metadata: {
appName: 'MyApp',
locale: 'en-US'
}
});
// Manually flush events
await analytics.flush();
// Clean shutdown
await analytics.shutdown();Configuration Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| apiKey | string | required | Your API key for authentication |
| baseUrl | string | required | Base URL of your analytics backend |
| batchSize | number | 10 | Number of events to batch before sending |
| flushInterval | number | 5000 | Time in ms to wait before auto-flushing |
| maxRetries | number | 3 | Number of retry attempts for failed requests |
| timeout | number | 10000 | Request timeout in milliseconds |
| debug | boolean | false | Enable debug logging |
| source | 'CT' | 'GA' | 'CT' | Analytics source identifier |
API Reference
track(event: TrackEventOptions): void
Track an analytics event. Events are queued and sent in batches.
Parameters:
eventName(string, required): Name of the eventuserId(string, optional): User identifiersessionId(string, optional): Session identifieranonymousId(string, optional): Anonymous user identifierpageUrl(string, optional): Current page URLreferrer(string, optional): Referrer URLpayload(object, optional): Custom event datametadata(object, optional): Additional metadata
flush(): Promise<void>
Manually flush all queued events to the backend.
shutdown(): Promise<void>
Flush all events and stop the SDK. Call this before your app exits.
Features
- ✅ Automatic Batching: Events are automatically batched for efficient transmission
- ✅ Retry Logic: Failed requests are automatically retried with exponential backoff
- ✅ TypeScript Support: Full type definitions included
- ✅ Lightweight: Zero dependencies (uses native fetch)
- ✅ Auto-flush: Events are automatically flushed at regular intervals
- ✅ Deduplication: Events are assigned unique IDs to prevent duplicates
Browser Support
This SDK uses the native fetch API. For older browsers, you may need to include a polyfill.
License
MIT
