Tracklytic

JavaScript SDK

Tracklytic JavaScript SDK für Web-Anwendungen und Node.js

JavaScript SDK

Das Tracklytic JavaScript SDK ist für Web-Anwendungen und Node.js optimiert und bietet eine einfache Integration in Ihre JavaScript-Projekte.

Installation

npm install tracklytic

CDN (Browser)

<script src="https://unpkg.com/tracklytic@latest/dist/tracklytic.min.js"></script>

ES6 Modules

import { Tracklytic } from 'tracklytic';

CommonJS

const { Tracklytic } = require('tracklytic');

Grundlegende Konfiguration

import { Tracklytic } from 'tracklytic';

const tracker = new Tracklytic({
  apiToken: 'your_api_token_here',
  projectId: 'your_project_id'
});

Erweiterte Konfiguration

const tracker = new Tracklytic({
  apiToken: 'your_api_token_here',
  projectId: 'your_project_id',
  
  // Batch-Konfiguration
  batchSize: 10,           // Events sammeln und in Batches senden
  flushInterval: 5000,     // Alle 5 Sekunden senden
  
  // Debug-Modus
  debug: false,            // Detaillierte Logs aktivieren
  
  // Retry-Konfiguration
  retryAttempts: 3,        // Anzahl der Wiederholungsversuche
  retryDelay: 1000,       // Verzögerung zwischen Wiederholungen
});

Event Tracking

Einfaches Event

tracker.track('page_view', {
  page: '/home',
  title: 'Homepage',
  user_id: 'user_123'
});

Event mit Channel

tracker.track('purchase', {
  product_id: 'prod_123',
  amount: 29.99,
  currency: 'EUR'
}, 'ecommerce');

Event mit erweiterten Optionen

tracker.track('button_click', {
  button_name: 'signup',
  page: '/home'
}, {
  notify: true,           // Benachrichtigung senden
  icon: '🎯',            // Event-Icon
  tags: {                // Zusätzliche Tags
    source: 'web',
    campaign: 'summer_sale',
    position: 'header'
  }
});

User Identification

Nutzer identifizieren

tracker.identify('user_123', {
  name: 'John Doe',
  email: 'john@example.com',
  plan: 'premium',
  signup_date: '2024-01-15',
  preferences: {
    language: 'de',
    timezone: 'Europe/Berlin',
    notifications: true
  }
});

Profil aktualisieren

// Teilweise Updates - nur angegebene Felder werden aktualisiert
tracker.identify('user_123', {
  last_login: new Date().toISOString(),
  total_sessions: 46,
  'preferences.notifications': false
});

Insights Management

Einfache Insights

// Numerische Metriken
tracker.insight('total_users', 1250);

// String-basierte Metriken
tracker.insight('system_status', 'Operational');

// Dezimalzahlen
tracker.insight('conversion_rate', 15.7);

Komplexe Insights

tracker.insight('user_breakdown', {
  total: 1250,
  premium: 312,
  free: 938,
  breakdown: {
    age_18_25: 450,
    age_26_35: 600,
    age_36_45: 200
  },
  conversion_rate: 24.96
});

Insights inkrementieren

// Einfaches Inkrement
tracker.incrementInsight('daily_active_users', 1);

// Größeres Inkrement
tracker.incrementInsight('total_revenue', 29.99);

React Integration

Hook-basierte Integration

import { useEffect, useState } from 'react';
import { Tracklytic } from 'tracklytic';

function useTracklytic() {
  const [tracker] = useState(() => new Tracklytic({
    apiToken: 'your_api_token_here',
    projectId: 'your_project_id'
  }));

  useEffect(() => {
    return () => {
      tracker.flush(); // Events vor dem Unmount senden
    };
  }, [tracker]);

  return tracker;
}

function MyComponent() {
  const tracker = useTracklytic();
  
  const handleClick = () => {
    tracker.track('button_click', {
      button: 'cta',
      page: '/home'
    });
  };
  
  return <button onClick={handleClick}>Click me</button>;
}

Context-basierte Integration

import React, { createContext, useContext } from 'react';
import { Tracklytic } from 'tracklytic';

const TracklyticContext = createContext();

export function TracklyticProvider({ children, apiToken, projectId }) {
  const tracker = new Tracklytic({ apiToken, projectId });
  
  return (
    <TracklyticContext.Provider value={tracker}>
      {children}
    </TracklyticContext.Provider>
  );
}

export function useTracklytic() {
  const tracker = useContext(TracklyticContext);
  if (!tracker) {
    throw new Error('useTracklytic must be used within TracklyticProvider');
  }
  return tracker;
}

Node.js Integration

Express.js Middleware

import express from 'express';
import { Tracklytic } from 'tracklytic';

const app = express();
const tracker = new Tracklytic({
  apiToken: 'your_api_token_here',
  projectId: 'your_project_id'
});

// Middleware für automatisches Tracking
app.use((req, res, next) => {
  // API-Aufruf tracken
  tracker.track('api_call', {
    method: req.method,
    path: req.path,
    user_agent: req.get('User-Agent'),
    ip: req.ip
  });
  
  next();
});

// Route-Handler
app.get('/api/users', (req, res) => {
  tracker.track('users_endpoint_called', {
    user_id: req.user?.id
  });
  
  res.json({ users: [] });
});

Serverless Functions

// Vercel/Netlify Functions
export default async function handler(req, res) {
  const tracker = new Tracklytic({
    apiToken: process.env.TRACKLYTIC_API_TOKEN,
    projectId: process.env.TRACKLYTIC_PROJECT_ID
  });
  
  try {
    // Business-Logik
    const result = await processRequest(req);
    
    // Erfolg tracken
    tracker.track('function_success', {
      function_name: 'api_handler',
      duration: Date.now() - startTime
    });
    
    res.json(result);
  } catch (error) {
    // Fehler tracken
    tracker.track('function_error', {
      function_name: 'api_handler',
      error: error.message
    });
    
    res.status(500).json({ error: 'Internal Server Error' });
  }
}

Best Practices

Event-Namen

// Gut - Beschreibend und konsistent
tracker.track('user_signup_completed');
tracker.track('product_added_to_cart');
tracker.track('payment_processed');

// Schlecht - Vage und inkonsistent
tracker.track('click');
tracker.track('action');
tracker.track('event');

Properties strukturieren

// Strukturierte Properties
tracker.track('purchase', {
  product: {
    id: 'prod_123',
    name: 'Premium Plan',
    category: 'subscription',
    price: 29.99
  },
  transaction: {
    amount: 29.99,
    currency: 'EUR',
    method: 'credit_card',
    id: 'txn_456'
  },
  user: {
    id: 'user_123',
    segment: 'premium',
    location: 'Berlin'
  }
});

Fehlerbehandlung

// Robuste Fehlerbehandlung
const safeTrack = async (event, properties) => {
  try {
    await tracker.track(event, properties);
  } catch (error) {
    console.error(`Failed to track ${event}:`, error);
    
    // Fallback-Logik
    if (error.code === 429) {
      // Rate limit - Event später senden
      setTimeout(() => {
        tracker.track(event, properties);
      }, 60000);
    }
  }
};

Nächste Schritte: Schauen Sie sich das Next.js SDK an.