@hangarx/browser
v1.0.5
Published
HangarX SDK for browser and frontend applications - Track events, analyze growth, and optimize conversions
Readme
@hangarx/browser
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 • API Reference • Examples • Support
⚡ 60-Second Takeoff
Copy, paste, done. Add this to your 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:
// Track events
hangarx.track('button_clicked', { button: 'signup' })
// Identify users
hangarx.identify('user_123', { email: '[email protected]' })
// 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)
<script>
window.hangarxConfig = { apiKey: 'proj_YOUR_KEY' };
</script>
<script src="https://unpkg.com/@hangarx/browser@latest/dist/hangarx.min.js"></script>npm/yarn
npm install @hangarx/browserimport HangarX from '@hangarx/browser'
const hangarx = new HangarX({ apiKey: 'proj_YOUR_KEY' })🚀 Flight Controls (API)
Track Events
hangarx.track('event_name', {
property: 'value'
})Common events:
page_view- Page viewedbutton_clicked- Button clickedform_submitted- Form submittedpurchase_completed- Purchase completed
Identify Users
hangarx.identify('user_123', {
email: '[email protected]',
plan: 'premium',
signup_date: '2025-01-15'
})Track Pages
hangarx.page('Home Page', {
category: 'marketing'
})Track Conversions
hangarx.conversion('purchase', 99.99, {
product: 'Premium Plan',
currency: 'USD'
})Reset Session (Logout)
hangarx.reset() // Clear user data, start fresh🎨 Framework Integration
React
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
// 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
// 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:
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:
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:
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:
// 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
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:
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
// User logs out
hangarx.reset() // Clears user ID, generates new sessionConditional Tracking
if (userHasConsented()) {
hangarx.track('page_view')
}No PII by Default
HangarX only tracks what you explicitly send. No sneaky data collection.
🧪 Testing
Debug Mode
const hangarx = new HangarX({
apiKey: 'proj_YOUR_KEY',
debug: true // See all events in console
})Manual Flush
// 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?
// 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:
apiEndpoint: 'https://ingest.hangarx.ai' // ✅ Correct
apiEndpoint: 'http://localhost:3003' // ❌ Only for local devTypeScript errors?
npm install --save-dev @types/node🎓 Best Practices
Event Naming
// ✅ Good: snake_case, descriptive
hangarx.track('purchase_completed')
hangarx.track('signup_form_submitted')
// ❌ Bad: unclear, inconsistent
hangarx.track('event1')
hangarx.track('PurchaseCompleted')Property Structure
// ✅ 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
// ✅ 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)
hangarx.screen('Dashboard', {
section: 'analytics'
})Campaign Tracking
hangarx.campaign('summer_sale_2025', 'clicked', {
creative: 'banner_v2',
placement: 'homepage_hero'
})Custom Destinations
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
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
- Examples: ./examples
- GitHub: github.com/hangarx/hangarx-sdk
- npm: npmjs.com/package/@hangarx/browser
- Support: [email protected]
🤝 Support
Need help? We're here:
- 📧 Email: [email protected]
- 💬 Discord: discord.gg/hangarx
- 🐛 Issues: GitHub Issues
- 📖 Docs: docs.hangarx.ai
📄 License
MIT License - see LICENSE
Ready for takeoff? 🚀
Install HangarX and start tracking in 60 seconds.
npm install @hangarx/browserMade with ❤️ by the HangarX crew
