npm package: @lostkode/analytics
Description: Privacy-focused, GDPR-compliant analytics tracking for LostKode client projects
Author: LostKode
Latest version: 1.0.0

# @lostkode/analytics

Privacy-focused, GDPR-compliant analytics tracking for LostKode client projects.

## Features

- 🔒 **Privacy-First**: No cookies, no personal data, no IP addresses
- ✅ **GDPR Compliant**: Respects DNT (Do Not Track) browser setting
- 🚀 **Easy Integration**: Simple API for tracking page views and events
- ⚡ **Lightweight**: Minimal bundle size
- 🎯 **TypeScript**: Full TypeScript support with type definitions
- ⚛️ **React Support**: Built-in React components and hooks

## Installation

```bash
npm install @lostkode/analytics
```

or

```bash
yarn add @lostkode/analytics
```

## Quick Start

### Vanilla JavaScript

```javascript
import { init } from '@lostkode/analytics';

// Initialize with your API key
const analytics = init({
  apiKey: 'your-api-key-here'
});

// Track page views
analytics.trackPageView();

// Track custom events
analytics.trackEvent({
  eventName: 'button_clicked',
  eventData: { button: 'signup', plan: 'pro' }
});
```

### React

```tsx
import { AnalyticsProvider } from '@lostkode/analytics/react';

function App() {
  return (
    <AnalyticsProvider apiKey="your-api-key-here">
      <YourApp />
    </AnalyticsProvider>
  );
}
```

### React with Hook

```tsx
import { useAnalytics } from '@lostkode/analytics/react';

function MyComponent() {
  const analytics = useAnalytics({ apiKey: 'your-api-key-here' });

  const handleClick = () => {
    analytics.trackEvent({
      eventName: 'button_clicked',
      eventData: { button: 'cta' }
    });
  };

  return <button onClick={handleClick}>Click Me</button>;
}
```

## API Reference

### `init(config)`

Initialize the analytics tracker.

**Parameters:**

- `config.apiKey` (string, required): Your LostKode Analytics API key
- `config.apiEndpoint` (string, optional): Custom API endpoint (defaults to `https://lostkode.com/api/analytics/track`)
- `config.respectDNT` (boolean, optional): Respect Do Not Track browser setting (defaults to `true`)
- `config.consentGiven` (boolean, optional): User consent for city-level tracking (defaults to `false`)

**Returns:** Analytics instance with `trackPageView` and `trackEvent` methods

### `trackPageView(path?)`

Track a page view.

**Parameters:**

- `path` (string, optional): Custom path to track (defaults to current URL path)

### `trackEvent(options)`

Track a custom event.

**Parameters:**

- `options.eventName` (string, required): Name of the event
- `options.eventData` (object, optional): Additional event data

## Consent Management (Optional)

If your project is configured to track city-level geographic data, you **must** obtain user consent for GDPR compliance.

### Using the ConsentPopup Component

```tsx
import { useState, useEffect } from 'react';
import { AnalyticsProvider } from '@lostkode/analytics/react';
import { ConsentPopup } from '@lostkode/analytics/consent';

function App() {
  const [showConsent, setShowConsent] = useState(false);
  const [consentGiven, setConsentGiven] = useState(false);
  
  useEffect(() => {
    // Check if consent was already given
    const consent = localStorage.getItem('_lk_consent_your-api-key');
    if (!consent) {
      setShowConsent(true);
    } else {
      setConsentGiven(consent === 'accepted');
    }
  }, []);

  const handleConsent = (accepted: boolean) => {
    setConsentGiven(accepted);
    setShowConsent(false);
  };

  return (
    <>
      {showConsent && (
        <ConsentPopup
          apiKey="your-api-key"
          onConsent={handleConsent}
          customStyles={{
            backgroundColor: '#ffffff',
            textColor: '#000000',
            buttonAcceptColor: '#10b981',
            buttonDeclineColor: '#ef4444',
            fontFamily: 'Arial, sans-serif'
          }}
          position="bottom"
          message="We use analytics to improve your experience. This includes tracking your approximate location. Learn more in our privacy policy."
        />
      )}
      <AnalyticsProvider 
        apiKey="your-api-key" 
        consentGiven={consentGiven}
      >
        <YourApp />
      </AnalyticsProvider>
    </>
  );
}
```

### Custom Consent Implementation

You can also implement your own consent mechanism:

```tsx
import { AnalyticsProvider } from '@lostkode/analytics/react';

function App() {
  const [consentGiven, setConsentGiven] = useState(false);

  // Your custom consent logic
  const handleCustomConsent = () => {
    setConsentGiven(true);
    localStorage.setItem('my-consent', 'true');
  };

  return (
    <AnalyticsProvider 
      apiKey="your-api-key" 
      consentGiven={consentGiven}
    >
      <YourApp />
    </AnalyticsProvider>
  );
}
```

### Privacy Policy Notice

**Important:** When using city-level tracking, you must inform users in your privacy policy. Add text similar to:

> We use LostKode Analytics to understand how visitors use our website. With your consent, we collect your approximate location (city-level) to provide better localized experiences. This data is anonymized and cannot be used to identify you personally. You can withdraw consent at any time.

## Configuration

### Getting Your API Key

1. Log in to your LostKode dashboard at https://lostkode.com/dashboard
2. Navigate to your project settings
3. Find your Analytics API Key in the Analytics section
4. Copy the key and add it to your environment variables

### Environment Variables

We recommend storing your API key in environment variables:

```bash
# .env
NEXT_PUBLIC_LOSTKODE_API_KEY=your-api-key-here
```

Then use it in your code:

```javascript
const analytics = init({
  apiKey: process.env.NEXT_PUBLIC_LOSTKODE_API_KEY
});
```

## Privacy & GDPR Compliance

This package is designed to be GDPR-compliant by default:

- **No Cookies**: Uses sessionStorage for anonymous session tracking
- **No Personal Data**: Doesn't collect any personally identifiable information
- **No IP Addresses**: IP addresses are not stored
- **Country-Level Geo by Default**: Geographic data is limited to country level by default
- **Optional Region/City Tracking**: Can be enabled with proper user consent
- **DNT Support**: Respects Do Not Track browser settings
- **Anonymous Sessions**: Session IDs are cryptographically random and cannot be linked to individuals

## What Data is Collected?

The following anonymous data is collected:

- Page paths visited
- Referrer URLs
- Browser type (e.g., Chrome, Firefox)
- Operating system (e.g., Windows, macOS)
- Device type (desktop, mobile, tablet)
- Country (country-level only, no precise location)
- Custom event names and data (if you use `trackEvent`)

## Integration Examples

### Next.js

```tsx
// app/layout.tsx
import { AnalyticsProvider } from '@lostkode/analytics/react';

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        <AnalyticsProvider 
          apiKey={process.env.NEXT_PUBLIC_LOSTKODE_API_KEY!}
          autoTrack={true}
        >
          {children}
        </AnalyticsProvider>
      </body>
    </html>
  );
}
```

### Tracking Form Submissions

```tsx
function ContactForm() {
  const analytics = useAnalytics({ 
    apiKey: process.env.NEXT_PUBLIC_LOSTKODE_API_KEY! 
  });

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    // Track form submission
    analytics.trackEvent({
      eventName: 'contact_form_submitted',
      eventData: { 
        formType: 'contact',
        source: 'homepage'
      }
    });

    // Submit form...
  };

  return <form onSubmit={handleSubmit}>...</form>;
}
```

### Tracking Button Clicks

```tsx
function CTAButton() {
  const analytics = useAnalytics({ 
    apiKey: process.env.NEXT_PUBLIC_LOSTKODE_API_KEY! 
  });

  const handleClick = () => {
    analytics.trackEvent({
      eventName: 'cta_clicked',
      eventData: { 
        button: 'get_started',
        location: 'hero_section'
      }
    });
  };

  return <button onClick={handleClick}>Get Started</button>;
}
```

## Browser Support

- Chrome (latest)
- Firefox (latest)
- Safari (latest)
- Edge (latest)

Requires support for:
- `fetch` API
- `crypto.randomUUID` or `crypto.getRandomValues`
- `sessionStorage`

## Troubleshooting

### No Data Showing in Dashboard

1. Verify your API key is correct
2. Check browser console for errors
3. Ensure `respectDNT` isn't blocking tracking (if you have DNT enabled in your browser)
4. Wait a few minutes for data to appear

### TypeScript Errors

Make sure you have the required types installed:

```bash
npm install --save-dev @types/react
```

## License

MIT

## Support

For issues, questions, or feature requests:
- Email: support@lostkode.com
- Documentation: https://lostkode.com/docs/analytics
- Dashboard: https://lostkode.com/dashboard

## Credits

Built with ❤️ by [LostKode](https://lostkode.com)