Skip to content

Tracking Events

Learn how to track events, use channels, tags, and configure notifications.

Basic Tracking

typescript
await kitbase.track({
  channel: 'payments',
  event: 'New Subscription',
  user_id: 'user-123',
  icon: '💰',
  notify: true,
  description: 'User subscribed to premium plan',
  tags: {
    plan: 'premium',
    cycle: 'monthly',
    amount: 9.99,
  },
});

Parameters

ParameterTypeRequiredDescription
channelstringYesCategory for the event (e.g., "payments", "users")
eventstringYesName of the event (e.g., "New Subscription")
user_idstringNoIdentifier for the user
iconstringNoEmoji or icon name
notifybooleanNoSend real-time notification
descriptionstringNoAdditional context
tagsobjectNoKey-value metadata

Response

typescript
interface TrackResponse {
  id: string;        // Unique event ID (e.g., "evt_abc123")
  event: string;     // Event name
  timestamp: string; // ISO 8601 timestamp
}

Channels

Channels organize your events into logical categories. Use consistent channel names across your application:

ChannelUse Case
paymentsSubscriptions, purchases, refunds, billing
usersSignups, logins, profile updates
errorsApplication errors, exceptions, failures
notificationsPush notification delivery status
apiExternal API calls, webhooks received
systemDeployments, server events

Channel Naming

Use lowercase, plural nouns for channel names. This keeps your events organized and easy to filter.

Tags

Tags are key-value pairs that add context to your events. They support three types:

TypeExample
string"premium"
number99.99
booleantrue
typescript
tags: {
  plan: 'premium',           // string
  amount: 99.99,             // number
  is_first_purchase: true,   // boolean
  referral_code: 'SAVE20',   // string
}

Tag Naming

Use lowercase snake_case for tag names:

  • user_type, plan_name, error_code
  • Not: UserType, planName, ERROR-CODE

Automatic Tag Enrichment

The backend automatically enriches your events with additional context:

TagDescription
__browserBrowser name (Chrome, Firefox, Safari)
__browser_versionBrowser version
__osOperating system (Windows, macOS, iOS)
__os_versionOS version
__deviceDevice type (desktop, mobile, tablet)
__countryCountry (from IP)
__regionRegion/State
__cityCity
__session_idSession identifier
__pathPage path
__referrerReferrer URL
__utm_sourceUTM source parameter
__utm_mediumUTM medium parameter
__utm_campaignUTM campaign parameter

Query Filters

Use these enriched tags to filter events in the dashboard by browser, country, device, or UTM parameters.

Notifications

Set notify: true to receive real-time notifications when important events occur:

typescript
await kitbase.track({
  channel: 'payments',
  event: 'Payment Failed',
  user_id: 'user-123',
  icon: '🔴',
  notify: true,  // Get notified immediately
  tags: {
    amount: 99.99,
    error: 'card_declined',
  },
});

Good candidates for notifications:

  • New signups and subscriptions
  • Failed payments
  • Critical errors
  • Security events (login from new device)

Icons

Use emoji or named icons to make events visually distinct:

typescript
// Emoji icons
icon: '💰'  // Payments
icon: '👤'  // Users
icon: '🔴'  // Errors
icon: '✅'  // Success
icon: '🔔'  // Notifications
icon: '🚀'  // Deployments

Use Cases

Track User Signups

typescript
await kitbase.track({
  channel: 'users',
  event: 'User Signed Up',
  user_id: user.email,
  icon: '👤',
  notify: true,
  description: `New user from ${user.referralSource}`,
  tags: {
    source: user.referralSource,
    plan: 'free',
    country: user.country,
  },
});

Track Payments

typescript
await kitbase.track({
  channel: 'payments',
  event: 'Subscription Created',
  user_id: user.id,
  icon: '💰',
  notify: true,
  tags: {
    plan: subscription.plan,
    amount: subscription.amount,
    currency: 'USD',
    interval: 'monthly',
  },
});

Track Errors

typescript
process.on('uncaughtException', async (error) => {
  await kitbase.track({
    channel: 'errors',
    event: 'Uncaught Exception',
    icon: '🔴',
    notify: true,
    description: error.message,
    tags: {
      name: error.name,
      stack: error.stack?.slice(0, 500),
    },
  });
});

Track Feature Usage

typescript
await kitbase.track({
  channel: 'features',
  event: 'Export Generated',
  user_id: user.id,
  icon: '📊',
  tags: {
    format: 'pdf',
    pages: 15,
    duration_ms: 2340,
  },
});

Error Handling

See Error Handling for detailed error handling patterns.

typescript
import { AuthenticationError, ValidationError } from '@kitbase/analytics';

try {
  await kitbase.track({ channel: 'users', event: 'Signup' });
} catch (error) {
  if (error instanceof AuthenticationError) {
    // Invalid API key
  } else if (error instanceof ValidationError) {
    // Missing required field
  }
}
dart
import 'package:kitbase/events.dart';

try {
  await kitbase.track(channel: 'users', event: 'Signup');
} on EventsAuthenticationException {
  // Invalid API key
} on EventsValidationException catch (e) {
  // Missing required field
  print('Missing field: ${e.field}');
}
php
use Kitbase\Events\AuthenticationException;
use Kitbase\Events\ValidationException;

try {
    $kitbase->track(new TrackOptions(
        channel: 'users',
        event: 'Signup',
    ));
} catch (AuthenticationException $e) {
    // Invalid API key
} catch (ValidationException $e) {
    // Missing required field
    echo "Missing field: " . $e->field;
}

Released under the MIT License.