@thrivestack/analytics-browser
Version:
ThriveStack Analytics Platform - Comprehensive web analytics tracking with privacy-first approach
442 lines (319 loc) • 9.89 kB
Markdown
ThriveStack Analytics Platform - Comprehensive web analytics tracking with privacy-first approach
- **Privacy-First**: Respects Do Not Track settings and provides consent management
- **Automatic Tracking**: Captures page visits, clicks, and form interactions
- **Device Fingerprinting**: Uses FingerprintJS for reliable device identification
- **Session Management**: Automatic session tracking with configurable timeouts
- **Event Batching**: Efficient event batching to reduce API calls
- **Geolocation**: Automatic IP-based location detection
- **UTM Tracking**: Automatic UTM parameter capture
- **TypeScript Support**: Full TypeScript definitions included
- **Simple API**: Easy-to-use singleton pattern
```bash
npm install @thrivestack/analytics
```
This package is available in 4 different build modes to support various deployment scenarios:
Default mode for npm package installations. Uses production API endpoint: `https://api.app.thrivestack.ai/api`
```bash
npm install @thrivestack/analytics-browser
```
```javascript
import { ThriveStack } from '@thrivestack/analytics-browser';
// Or CommonJS: const { ThriveStack } = require('@thrivestack/analytics-browser');
const analytics = new ThriveStack({
apiKey: 'your-api-key',
});
```
**Files generated:**
- `dist/index.production.js` (CommonJS)
- `dist/index.production.esm.js` (ES modules)
Development version for npm package installations. Uses development API endpoint: `https://azure.dev.app.thrivestack.ai/api`
```javascript
// Import the development build specifically
import { ThriveStack } from '@thrivestack/analytics-browser/dist/index.development.esm.js';
const analytics = new ThriveStack({
apiKey: 'your-api-key',
});
```
**Files generated:**
- `dist/index.development.js` (CommonJS)
- `dist/index.development.esm.js` (ES modules)
Single vanilla JS file for CDN hosting with production API endpoint.
```html
<!-- Production CDN build -->
<script src="https://your-cdn.com/thrivestack.production.min.js"></script>
<script>
const analytics = new ThriveStack({
apiKey: 'your-api-key',
});
</script>
```
**File generated:**
- `dist/thrivestack.production.min.js` (UMD, minified, standalone)
Single vanilla JS file for CDN hosting with development API endpoint.
```html
<!-- Development CDN build -->
<script src="https://your-cdn.com/thrivestack.development.min.js"></script>
<script>
const analytics = new ThriveStack({
apiKey: 'your-api-key',
});
</script>
```
**File generated:**
- `dist/thrivestack.development.min.js` (UMD, minified, standalone)
To build all modes:
```bash
npm run build
```
To build specific modes:
```bash
npm run build:production
npm run build:development
npm run build:cdn
npm run build:cdn:production
npm run build:cdn:development
```
- **Production**: `https://api.app.thrivestack.ai/api`
- **Development**: `https://azure.dev.app.thrivestack.ai/api`
You can always override the API endpoint by passing `apiEndpoint` in the options:
```javascript
const analytics = new ThriveStack({
apiKey: 'your-api-key',
apiEndpoint: 'https://custom-endpoint.com/api',
});
```
```bash
npm publish --registry=https://registry.npmjs.org/
```
```typescript
import * as thrivestack from '@thrivestack/analytics';
// Initialize ThriveStack
await thrivestack.init('your-api-key', 'your-source-identifier');
```
```typescript
import * as thrivestack from '@thrivestack/analytics';
// Initialize
await thrivestack.init('your-api-key', 'your-source-identifier');
// Set user information
await thrivestack.setUser('user@example.com', 'user123', {
firstName: 'John',
lastName: 'Doe',
plan: 'premium',
});
// Set group information
await thrivestack.setGroup('group123', 'example.com', 'Example Corp', {
industry: 'technology',
size: 'medium',
});
// Track custom events
await thrivestack.track('button_clicked', {
button_name: 'signup',
page: 'homepage',
});
```
Initialize ThriveStack analytics.
```typescript
await thrivestack.init('your-api-key', 'web-app', {
trackClicks: true,
trackForms: true,
enableConsent: true,
});
```
Set user information and optionally make identify API call.
```typescript
await thrivestack.setUser('user@example.com', 'user123', {
firstName: 'John',
lastName: 'Doe',
plan: 'premium',
});
```
Set group information and optionally make group API call.
```typescript
await thrivestack.setGroup('group123', 'example.com', 'Example Corp', {
industry: 'technology',
size: 'medium',
});
```
Track custom events.
```typescript
await thrivestack.track('purchase_completed', {
amount: 99.99,
currency: 'USD',
product_id: 'prod_123',
});
```
Get the ThriveStack instance for advanced usage.
Check if ThriveStack is initialized.
```typescript
interface ThriveStackOptions {
apiKey: string; // Required: Your ThriveStack API key
apiEndpoint?: string; // Optional: Custom API endpoint
trackClicks?: boolean; // Optional: Enable click tracking (default: true)
trackForms?: boolean; // Optional: Enable form tracking (default: false)
respectDoNotTrack?: boolean; // Optional: Respect DNT setting (default: true)
enableConsent?: boolean; // Optional: Enable consent management (default: false)
batchSize?: number; // Optional: Events per batch (default: 10)
batchInterval?: number; // Optional: Batch interval in ms (default: 2000)
geoIpServiceUrl?: string; // Optional: Custom geolocation service
source?: string; // Optional: Source identifier
sessionTimeout?: number; // Optional: Session timeout in ms (default: 30min)
debounceDelay?: number; // Optional: Session update delay (default: 2000ms)
defaultConsent?: boolean; // Optional: Default consent state
}
```
For advanced usage, you can access the underlying ThriveStack instance:
```typescript
import * as thrivestack from '@thrivestack/analytics';
await thrivestack.init('your-api-key');
const instance = thrivestack.getInstance();
if (instance) {
// Access advanced methods
instance.setConsent('analytics', true);
instance.enableDebugMode();
// Direct event tracking
await instance.track([
{
event_name: 'custom_event',
properties: { custom: 'data' },
context: { device_id: instance.getDeviceId() },
timestamp: new Date().toISOString(),
},
]);
}
```
Automatically captured when:
- Page loads
- Navigation occurs (SPA support)
- History API is used
### Click Event
Automatically captured for elements with the `thrivestack-event` class:
```html
<button class="thrivestack-event">Click me</button>
```
Automatically captured for form interactions:
- Form submissions
- Form field interactions
- Form abandonment
```typescript
import * as thrivestack from '@thrivestack/analytics';
// Initialize with consent management
await thrivestack.init('your-api-key', 'web-app', {
enableConsent: true,
});
const instance = thrivestack.getInstance();
if (instance) {
// Set consent for different categories
instance.setConsent('analytics', true);
instance.setConsent('marketing', false);
// Check if tracking is allowed
if (instance.isTrackingAllowed('analytics')) {
// Track analytics events
}
}
```
```typescript
import * as thrivestack from '@thrivestack/analytics';
await thrivestack.init('your-api-key');
const instance = thrivestack.getInstance();
if (instance) {
// Enable debug mode to see events in console
instance.enableDebugMode();
}
```
```typescript
// In _app.tsx or layout.tsx
import { useEffect } from 'react';
import * as thrivestack from '@thrivestack/analytics';
export default function App({ Component, pageProps }) {
useEffect(() => {
thrivestack.init(
process.env.NEXT_PUBLIC_THRIVESTACK_API_KEY || '',
'nextjs-app'
);
}, []);
return <Component {...pageProps} />;
}
// In a component
import { useEffect } from 'react';
import * as thrivestack from '@thrivestack/analytics';
export default function HomePage() {
useEffect(() => {
thrivestack.track('page_view', {
page_name: 'Home Page',
page_url: window.location.href
});
}, []);
const handleButtonClick = () => {
thrivestack.track('button_clicked', {
button_name: 'signup',
page: 'homepage'
});
};
return (
<button onClick={handleButtonClick}>
Sign Up
</button>
);
}
```
- Chrome 60+
- Firefox 55+
- Safari 12+
- Edge 79+
This package is designed for browser environments. For Node.js server-side tracking, use the appropriate server SDK.
```bash
npm install
```
```bash
npm run build
```
```bash
npm test
```
```bash
npm run lint
```
```bash
npm run format
```
MIT
For support, please contact support@thrivestack.ai or visit our documentation at https://docs.thrivestack.ai