JSPM

  • Created
  • Published
  • Downloads 101
  • Score
    100M100P100Q81943F
  • License MIT

Lightweight TypeScript SDK for sending analytics events and managing remote configurations via Grain's REST API

Package Exports

  • @grainql/analytics-web
  • @grainql/analytics-web/react

Readme

Grain Analytics Web SDK

A lightweight, dependency-free TypeScript SDK for privacy-first analytics and remote configuration management.

npm version Bundle Size

🆕 What's New in v3.0

🔒 Privacy-First by Default:

  • Cookieless - No tracking cookies, daily rotating IDs
  • GDPR Compliant - Cookieless mode requires no consent
  • No IP Storage - GeoIP data only (country, region, city)
  • Query Params Stripped - Privacy-first URL tracking
  • Three Consent Modes - Choose your privacy level

🚨 Breaking Changes: This is a major version with breaking changes. See BREAKING_CHANGES.md and MIGRATION_GUIDE_V2.md.

Features

  • 🔒 Privacy-First - Cookieless by default, GDPR compliant
  • 🚀 Zero dependencies - ~7KB gzipped
  • 📦 Automatic batching - Efficient event delivery
  • 🔄 Retry logic - Reliable with exponential backoff
  • 🎯 TypeScript first - Full type safety
  • ⚙️ Remote Config - Dynamic app control without deployments
  • ⚛️ React Hooks - Seamless React integration
  • 📱 Cross-platform - Browser, Node.js, React Native

Installation

NPM

npm install @grainql/analytics-web

CDN (IIFE)

<!-- Load from CDN -->
<script src="https://cdn.jsdelivr.net/npm/@grainql/analytics-web@latest/dist/index.global.js"></script>

<script>
  // Available as window.Grain
  const grain = window.Grain.createGrainAnalytics({
    tenantId: 'your-tenant-id'
  });
  
  grain.track('page_view', { page: window.location.pathname });
</script>

Quick Start

Vanilla JavaScript/TypeScript

import { createGrainAnalytics } from '@grainql/analytics-web';

// Cookieless by default (no consent needed)
const grain = createGrainAnalytics({
  tenantId: 'your-tenant-id',
  consentMode: 'cookieless', // Default: daily rotating IDs
});

// Track events
grain.track('page_viewed', { page: '/home' });

// Get remote config
const heroText = grain.getConfig('hero_text');

For GDPR Strict (with consent management):

const grain = createGrainAnalytics({
  tenantId: 'your-tenant-id',
  consentMode: 'gdpr-strict', // Requires consent for permanent IDs
  waitForConsent: true, // Queue events until consent granted
});

// Show consent banner
if (!grain.hasConsent()) {
  // Show your consent UI
  showConsentBanner({
    onAccept: () => grain.grantConsent(['analytics']),
    onReject: () => grain.revokeConsent(),
  });
}

React

import { GrainProvider, useConfig, useTrack } from '@grainql/analytics-web/react';

function App() {
  return (
    <GrainProvider config={{ tenantId: 'your-tenant-id' }}>
      <HomePage />
    </GrainProvider>
  );
}

function HomePage() {
  const { value: heroText } = useConfig('hero_text');
  const track = useTrack();
  
  return (
    <div>
      <h1>{heroText || 'Welcome!'}</h1>
      <button onClick={() => track('cta_clicked')}>
        Get Started
      </button>
    </div>
  );
}

Documentation

For comprehensive guides, API reference, and examples, visit our documentation:

📚 Full Documentation

Key Topics

Key Concepts

Event Tracking

Track user actions with automatic batching and retry logic:

grain.track('button_clicked', { button: 'signup' });
await grain.trackPurchase({ orderId: '123', total: 99.99 });

Remote Configuration

Control your app dynamically without code deployments:

const featureEnabled = grain.getConfig('new_feature');
if (featureEnabled === 'true') {
  // Show feature
}

User Identification

Track users across sessions:

grain.setUserId('user_123');
await grain.setProperty({ plan: 'premium' });

Tracks: Journey Visualization

Track user journeys from start to goal to unlock path visualization:

// 1. Define meaningful event names for your journey
grain.track('signup_started', { source: 'homepage' });
grain.track('email_entered', { valid: true });
grain.track('password_created', { strength: 'strong' });
grain.track('signup_completed', { method: 'email' });

// 2. In the dashboard, create a Track:
//    - Start event: 'signup_started'
//    - Goal event: 'signup_completed'
//    - The system will automatically visualize all paths between them

// 3. Best practices for Tracks:
//    - Use consistent event naming (snake_case recommended)
//    - Track intermediate steps (not just start/end)
//    - Add properties to segment paths (e.g., source, device_type)
//    - Exclude noise: heartbeat events are filtered automatically

What you'll see in Tracks:

  • Conversion paths: Most common routes users take to reach the goal
  • Drop-off paths: Where users abandon the journey
  • Hub nodes: Critical events many paths flow through
  • Metrics: Conversion rate, time-to-goal, abandonment points

More Examples

Check the examples directory for:

  • Vanilla JavaScript usage
  • React integration
  • Next.js setup
  • E-commerce tracking
  • Authentication flows

Contributing

We welcome contributions! Please see our contributing guidelines for more details.

License

MIT © Grain Analytics

Support