npm package: @rivtor/analytics
Description: Production-ready privacy-first analytics for B2B SaaS
Author: Rivtor
Latest version: 1.1.0

# @rivtor/analytics

**Production-ready privacy-first analytics for B2B SaaS**

## Features

- **Privacy-First Metrics**: Server-side analytics without cookies (GDPR compliant)
- **Event Tracking**: Simple function to track custom events
- **Funnel Analysis**: Visualize conversion funnels
- **Real-time Dashboard**: Built-in dashboard components
- **Cookieless Tracking**: No cookies required, uses session storage

## Installation

```bash
npm install @rivtor/analytics
# or
yarn add @rivtor/analytics
# or
pnpm add @rivtor/analytics
```

## Quick Start

### 1. Initialize Analytics

Wrap your app with the provider:

```tsx
import { VocoAnalyticsProvider } from '@rivtor/analytics/react';

export default function RootLayout({ children }) {
    return (
        <VocoAnalyticsProvider
            config={{
                trackPageViews: true,
                respectDoNotTrack: true,
                enableCookieless: true,
            }}
        >
            {children}
        </VocoAnalyticsProvider>
    );
}
```

### 2. Track Events

```tsx
'use client';
import { analytics } from '@rivtor/analytics';

export function BuyButton() {
    const handleClick = () => {
        // Track conversion event
        analytics.track('clicked_buy_button', {
            plan: 'pro',
            price: 29,
        });

        // Continue with purchase flow
    };

    return <button onClick={handleClick}>Buy Now</button>;
}
```

### 3. View Analytics Dashboard

```tsx
import { VocoAnalytics } from '@rivtor/analytics/react';
import { analytics } from '@rivtor/analytics/server';

export default async function AnalyticsPage() {
    const data = await analytics.getDashboardData(30);

    return <VocoAnalytics data={data} />;
}
```

## API Reference

### Client Methods

```typescript
import { analytics } from '@rivtor/analytics';

// Initialize (called automatically by provider)
analytics.init({
    trackPageViews: true,
    trackOutboundLinks: true,
    trackScrollDepth: true,
    respectDoNotTrack: true,
    enableCookieless: true,
});

// Set user ID
analytics.setUserId('user_123');

// Track custom event
analytics.track('button_clicked', {
    buttonId: 'cta-button',
    location: 'homepage',
});

// Track page view (automatic if enabled)
analytics.trackPageView({
    path: '/pricing',
    title: 'Pricing Page',
});
```

### Server Methods

```typescript
import { analytics } from '@rivtor/analytics/server';

// Track event server-side
await analytics.trackEvent('user_registered', { plan: 'pro' }, 'user_123');

// Get dashboard data
const data = await analytics.getDashboardData(30);
// Returns: { overview, timeSeries, topPages, topEvents }

// Analyze conversion funnel
const funnel = await analytics.analyzeFunnel({
    name: 'Sign Up Funnel',
    steps: [
        { name: 'Visit', event: 'page_view' },
        { name: 'Sign Up Click', event: 'clicked_signup' },
        { name: 'Completed', event: 'user_registered' },
    ],
});

// Get event analytics
const eventData = await analytics.getEventAnalytics('clicked_buy_button', 30);

// Get top pages
const topPages = await analytics.getTopPages(30, 10);
```

## Funnel Analysis

The built-in funnel analysis helps you understand conversion rates:

```tsx
import { analytics } from '@rivtor/analytics/server';

const signupFunnel = await analytics.analyzeFunnel({
    name: 'User Registration',
    steps: [
        { name: 'Landing Page', event: 'page_view' },
        { name: 'Click Sign Up', event: 'clicked_signup' },
        { name: 'Submit Form', event: 'submitted_form' },
        { name: 'Verified Email', event: 'email_verified' },
    ],
});

console.log(signupFunnel);
// {
//   name: 'User Registration',
//   totalUsers: 10000,
//   overallConversionRate: 0.15,
//   steps: [
//     { name: 'Landing Page', count: 10000, conversionRate: 1.0 },
//     { name: 'Click Sign Up', count: 5000, conversionRate: 0.5 },
//     { name: 'Submit Form', count: 2000, conversionRate: 0.2 },
//     { name: 'Verified Email', count: 1500, conversionRate: 0.15 }
//   ]
// }
```

## Configuration

```typescript
interface AnalyticsConfig {
    // Enable cookieless tracking (uses sessionStorage)
    enableCookieless?: boolean;

    // Respect browser Do Not Track setting
    respectDoNotTrack?: boolean;

    // Automatically track page views
    trackPageViews?: boolean;

    // Track outbound link clicks
    trackOutboundLinks?: boolean;

    // Track scroll depth milestones
    trackScrollDepth?: boolean;

    // Track time on page
    trackTimeOnPage?: boolean;

    // Sample rate (0-1)
    sampleRate?: number;

    // Exclude certain paths from tracking
    excludedPaths?: string[];

    // Exclude certain referrers from tracking
    excludedReferrers?: string[];
}
```

## License

MIT

---

Made with ❤️ by [Rivtor](https://rivtor.com)