npm package: @hangarx/browser
Description: HangarX SDK for browser and frontend applications - Track events, analyze growth, and optimize conversions
Author: HangarX Team
Latest version: 1.0.5

# @hangarx/browser

<div align="center">

[![npm version](https://img.shields.io/npm/v/@hangarx/browser.svg)](https://www.npmjs.com/package/@hangarx/browser)
[![Bundle Size](https://img.shields.io/badge/size-5.5KB-brightgreen.svg)](https://bundlephobia.com/package/@hangarx/browser)
[![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)

**Mission Control for Your Growth Analytics** 🚀

Track events, analyze growth, and optimize conversions with AI-powered insights.  
*Like having Jarvis for your analytics—smart, fast, and always ready to assist.*

[Quick Start](#-60-second-takeoff) • [API Reference](#-flight-controls-api) • [Examples](./examples) • [Support](https://github.com/hangarx/hangarx-sdk/issues)

</div>

---

## ⚡ 60-Second Takeoff

**Copy, paste, done.** Add this to your HTML:

```html
<script>
  window.hangarxConfig = { apiKey: 'proj_YOUR_KEY_HERE' };
</script>
<script src="https://unpkg.com/@hangarx/browser@latest/dist/hangarx.min.js"></script>
```

**Start tracking:**

```javascript
// Track events
hangarx.track('button_clicked', { button: 'signup' })

// Identify users
hangarx.identify('user_123', { email: 'pilot@example.com' })

// Track conversions
hangarx.conversion('purchase', 99.99, { plan: 'premium' })
```

**That's it.** You're airborne. ✈️

---

## 🎯 Why HangarX?

| Feature | What You Get |
|---------|-------------|
| **5.5KB** | Lighter than a paper airplane. Won't slow you down. |
| **42x Faster** | Direct Tinybird integration. Real-time analytics at Mach speed. |
| **Multi-Destination** | One SDK → GA4, Mixpanel, Segment. No juggling multiple scripts. |
| **AI-Powered** | Get intelligent insights, not just data dumps. |
| **Privacy-First** | GDPR-compliant `reset()` for clean user sessions. |
| **TypeScript** | Full type safety. Your IDE will thank you. |

---

## 📦 Installation

### CDN (Fastest)

```html
<script>
  window.hangarxConfig = { apiKey: 'proj_YOUR_KEY' };
</script>
<script src="https://unpkg.com/@hangarx/browser@latest/dist/hangarx.min.js"></script>
```

### npm/yarn

```bash
npm install @hangarx/browser
```

```typescript
import HangarX from '@hangarx/browser'

const hangarx = new HangarX({ apiKey: 'proj_YOUR_KEY' })
```

---

## 🚀 Flight Controls (API)

### Track Events

```javascript
hangarx.track('event_name', { 
  property: 'value' 
})
```

**Common events:**
- `page_view` - Page viewed
- `button_clicked` - Button clicked
- `form_submitted` - Form submitted
- `purchase_completed` - Purchase completed

### Identify Users

```javascript
hangarx.identify('user_123', {
  email: 'pilot@example.com',
  plan: 'premium',
  signup_date: '2025-01-15'
})
```

### Track Pages

```javascript
hangarx.page('Home Page', {
  category: 'marketing'
})
```

### Track Conversions

```javascript
hangarx.conversion('purchase', 99.99, {
  product: 'Premium Plan',
  currency: 'USD'
})
```

### Reset Session (Logout)

```javascript
hangarx.reset()  // Clear user data, start fresh
```

---

## 🎨 Framework Integration

### React

```typescript
import { useEffect } from 'react'
import HangarX from '@hangarx/browser'

const hangarx = new HangarX({ apiKey: 'proj_YOUR_KEY' })

function MyComponent() {
  useEffect(() => {
    hangarx.page('My Component')
  }, [])

  return <button onClick={() => hangarx.track('button_clicked')}>
    Click Me
  </button>
}
```

### Next.js

```typescript
// lib/analytics.ts
import HangarX from '@hangarx/browser'

export const analytics = new HangarX({
  apiKey: process.env.NEXT_PUBLIC_HANGARX_API_KEY!
})

// app/layout.tsx
'use client'
import { usePathname } from 'next/navigation'
import { useEffect } from 'react'
import { analytics } from '@/lib/analytics'

export default function RootLayout({ children }) {
  const pathname = usePathname()
  
  useEffect(() => {
    analytics.page(pathname)
  }, [pathname])
  
  return <html><body>{children}</body></html>
}
```

### Vue 3

```typescript
// plugins/analytics.ts
import HangarX from '@hangarx/browser'

const analytics = new HangarX({
  apiKey: import.meta.env.VITE_HANGARX_API_KEY
})

export default {
  install(app) {
    app.config.globalProperties.$analytics = analytics
  }
}
```

---

## ⚡ Turbo Mode: Tinybird Integration

**Get 42x faster analytics** with direct Tinybird integration:

```typescript
const hangarx = new HangarX({
  apiKey: 'proj_YOUR_KEY',
  
  // Enable Tinybird
  tinybird: {
    enabled: true,
    token: 'p.YOUR_TINYBIRD_TOKEN'
  },
  
  // Dual storage: instant + enriched
  storageStrategy: 'dual'
})
```

**What happens:**
- Events hit Tinybird in **~50ms** (instant analytics)
- Also sent to HangarX for AI enrichment (~2s)
- Best of both worlds: speed + intelligence

---

## 🎯 Multi-Destination: One SDK, Many Platforms

Send events to multiple platforms simultaneously:

```typescript
const hangarx = new HangarX({
  apiKey: 'proj_YOUR_KEY',
  
  destinations: [
    {
      type: 'ga4',
      config: {
        measurementId: 'G-XXXXXXXXXX',
        apiSecret: 'your-secret'
      }
    },
    {
      type: 'mixpanel',
      config: { token: 'your-token' }
    },
    {
      type: 'segment',
      config: { writeKey: 'your-key' }
    }
  ]
})

// One event → Four destinations (HangarX + GA4 + Mixpanel + Segment)
hangarx.track('purchase', { amount: 99.99 })
```

---

## 🏢 Multi-Tenancy: Track Across Organizations

Perfect for agencies managing multiple clients:

```typescript
hangarx.track('button_clicked', {
  button: 'signup',
  
  // Multi-tenancy context
  organization_id: 'org_marketing_agency',
  team_id: 'team_client_services',
  client_account_id: 'client_acme_corp',
  project_id: 'proj_acme_website'
})
```

**Hierarchy:**
```
Organizations → Teams → Client Accounts → Projects → Events
```

---

## 🤖 AI-Powered Insights

Get intelligent recommendations, not just raw data:

```typescript
// Get business insights
const insights = await hangarx.getInsights()
console.log(insights.topChannels)
console.log(insights.conversionRate)

// Get AI recommendations
const recommendations = await hangarx.getRecommendations()
// [
//   { type: 'optimize_cta', confidence: 0.92, ... },
//   { type: 'improve_onboarding', confidence: 0.87, ... }
// ]
```

---

## ⚙️ Configuration Options

```typescript
const hangarx = new HangarX({
  // Required
  apiKey: 'proj_YOUR_KEY',
  
  // Optional
  apiEndpoint: 'https://ingest.hangarx.ai',  // Default
  debug: false,                               // Enable debug logs
  autoTrack: true,                            // Auto-track page views
  batchSize: 20,                              // Events per batch
  flushInterval: 10000,                       // Flush every 10s
  
  // Tinybird (42x faster analytics)
  tinybird: {
    enabled: true,
    token: 'p.YOUR_TOKEN'
  },
  storageStrategy: 'dual',  // 'hangarx-only' | 'tinybird-only' | 'dual' | 'tinybird-primary'
  
  // Multi-destination
  destinations: [
    { type: 'ga4', config: { measurementId: 'G-XXX', apiSecret: 'secret' } },
    { type: 'mixpanel', config: { token: 'token' } },
    { type: 'segment', config: { writeKey: 'key' } }
  ]
})
```

---

## 📊 Performance Monitoring

Track SDK performance in real-time:

```typescript
const hangarx = new HangarX({
  apiKey: 'proj_YOUR_KEY',
  performanceMonitoring: true
})

// Get performance metrics
const metrics = hangarx.getPerformanceMetrics()
console.log('Avg flush duration:', metrics.avgFlushDuration)

// Get detailed report
const report = hangarx.getPerformanceReport()
console.log(report)
```

---

## 🔒 Privacy & GDPR

### Reset on Logout

```typescript
// User logs out
hangarx.reset()  // Clears user ID, generates new session
```

### Conditional Tracking

```typescript
if (userHasConsented()) {
  hangarx.track('page_view')
}
```

### No PII by Default

HangarX only tracks what you explicitly send. No sneaky data collection.

---

## 🧪 Testing

### Debug Mode

```typescript
const hangarx = new HangarX({
  apiKey: 'proj_YOUR_KEY',
  debug: true  // See all events in console
})
```

### Manual Flush

```typescript
// Queue events
hangarx.track('event1')
hangarx.track('event2')

// Flush immediately (useful for testing)
await hangarx.flush()
```

---

## 📦 Bundle Size

```
Core SDK:              5.5KB gzipped  ✅
With Tinybird:         6KB gzipped    ✅
With Destinations:     6.5KB gzipped  ✅

Compared to competitors:
- Segment:             ~30KB
- Mixpanel:            ~45KB
- Google Analytics:    ~50KB
- HangarX:             5.5KB  🎉
```

---

## 🚨 Common Issues

### Events not showing up?

```typescript
// 1. Check your API key
console.log(hangarx.config.apiKey)  // Should start with 'proj_'

// 2. Enable debug mode
const hangarx = new HangarX({ apiKey: 'proj_YOUR_KEY', debug: true })

// 3. Check network tab for failed requests

// 4. Manually flush to see errors
await hangarx.flush()
```

### CORS errors?

Make sure you're using the correct endpoint:
```typescript
apiEndpoint: 'https://ingest.hangarx.ai'  // ✅ Correct
apiEndpoint: 'http://localhost:3003'      // ❌ Only for local dev
```

### TypeScript errors?

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

---

## 🎓 Best Practices

### Event Naming

```typescript
// ✅ Good: snake_case, descriptive
hangarx.track('purchase_completed')
hangarx.track('signup_form_submitted')

// ❌ Bad: unclear, inconsistent
hangarx.track('event1')
hangarx.track('PurchaseCompleted')
```

### Property Structure

```typescript
// ✅ Good: consistent, typed
hangarx.track('purchase', {
  product_id: 'prod-456',
  revenue: 99.99,        // number
  currency: 'USD',       // string
  quantity: 1            // number
})

// ❌ Bad: inconsistent types
hangarx.track('purchase', {
  prod: 'Premium',
  amount: '99.99',       // should be number
  type: 'sub'            // unclear
})
```

### Identify Early

```typescript
// ✅ Identify as soon as you know the user
hangarx.identify(user.id, {
  email: user.email,
  created_at: new Date().toISOString()
})
```

---

## 🛠️ Advanced Features

### Screen Tracking (Mobile/SPA)

```typescript
hangarx.screen('Dashboard', {
  section: 'analytics'
})
```

### Campaign Tracking

```typescript
hangarx.campaign('summer_sale_2025', 'clicked', {
  creative: 'banner_v2',
  placement: 'homepage_hero'
})
```

### Custom Destinations

```typescript
class CustomDestination {
  name = 'custom'
  enabled = true
  
  async send(events) {
    await fetch('https://your-api.com/events', {
      method: 'POST',
      body: JSON.stringify(events)
    })
  }
}

const hangarx = new HangarX({
  apiKey: 'proj_YOUR_KEY',
  destinations: [
    { type: 'custom', config: new CustomDestination() }
  ]
})
```

### Lazy Loading Destinations

```typescript
import { LazyDestination } from '@hangarx/browser/destinations/lazy'

const hangarx = new HangarX({
  apiKey: 'proj_YOUR_KEY',
  destinations: [
    {
      type: 'custom',
      config: new LazyDestination('ga4', {
        measurementId: 'G-XXX',
        apiSecret: 'secret'
      })
    }
  ]
})

// GA4 loaded only when first event is sent (reduces initial bundle by 43%)
```

---

## 📚 Resources

- **Documentation:** [docs.hangarx.ai](https://docs.hangarx.ai)
- **Examples:** [./examples](./examples)
- **GitHub:** [github.com/hangarx/hangarx-sdk](https://github.com/hangarx/hangarx-sdk)
- **npm:** [npmjs.com/package/@hangarx/browser](https://www.npmjs.com/package/@hangarx/browser)
- **Support:** [support@hangarx.ai](mailto:support@hangarx.ai)

---

## 🤝 Support

Need help? We're here:

- 📧 **Email:** support@hangarx.ai
- 💬 **Discord:** [discord.gg/hangarx](https://discord.gg/hangarx)
- 🐛 **Issues:** [GitHub Issues](https://github.com/hangarx/hangarx-sdk/issues)
- 📖 **Docs:** [docs.hangarx.ai](https://docs.hangarx.ai)

---

## 📄 License

MIT License - see [LICENSE](../../LICENSE)

---

<div align="center">

**Ready for takeoff?** 🚀

Install HangarX and start tracking in 60 seconds.

```bash
npm install @hangarx/browser
```

*Made with ❤️ by the HangarX crew*

[Website](https://hangarx.ai) • [Docs](https://docs.hangarx.ai) • [Blog](https://hangarx.ai/blog)

</div>