> ## Documentation Index
> Fetch the complete documentation index at: https://docs.engagefabric.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Event Tracking

> Track user events with EngageFabric to trigger gamification rules. Ingest custom events, batch processing, and event-to-action mapping.

## Overview

Event tracking is the foundation of EngageFabric's gamification system. When players perform actions in your application, you send events to EngageFabric. The Rules Engine then evaluates these events and automatically triggers rewards like XP, currency, quest progress, and badges.

## How It Works

```mermaid theme={null}
sequenceDiagram
    participant App as Your App
    participant EF as EngageFabric
    participant RE as Rules Engine
    participant Player as Player State

    App->>EF: Track Event
    EF->>RE: Evaluate Rules
    RE->>Player: Update XP, Currency, Quests
    EF-->>App: Event Processed
```

## Tracking Events

### Basic Event

<CodeGroup>
  ```javascript SDK theme={null}
  import { EngageFabric } from '@engagefabricsdk/sdk';

  const client = new EngageFabric({
    apiKey: 'your-api-key',
    projectId: 'your-project-id'
  });

  // Track a simple event
  await client.events.track({
    externalUserId: 'user-123',
    eventType: 'lesson_completed',
    properties: {
      lessonId: 'lesson-456',
      score: 95,
      timeSpent: 300
    }
  });
  ```

  ```bash cURL theme={null}
  curl -X POST https://api.engagefabric.com/api/v1/events \
    -H "Authorization: Bearer your-api-key" \
    -H "Content-Type: application/json" \
    -d '{
      "externalUserId": "user-123",
      "eventType": "lesson_completed",
      "properties": {
        "lessonId": "lesson-456",
        "score": 95,
        "timeSpent": 300
      }
    }'
  ```
</CodeGroup>

### Event with Idempotency

Use idempotency keys to prevent duplicate event processing:

```javascript theme={null}
await client.events.track({
  externalUserId: 'user-123',
  eventType: 'purchase_completed',
  idempotencyKey: 'order-789', // Prevents duplicate processing
  properties: {
    orderId: 'order-789',
    amount: 99.99,
    items: ['item-1', 'item-2']
  }
});
```

## Common Event Types

Here are recommended event types for different use cases:

### Learning Platform

```javascript theme={null}
// Course progress
await client.events.track({
  externalUserId: 'user-123',
  eventType: 'lesson_completed',
  properties: { lessonId: 'l-1', courseId: 'c-1', score: 85 }
});

// Quiz completion
await client.events.track({
  externalUserId: 'user-123',
  eventType: 'quiz_passed',
  properties: { quizId: 'q-1', score: 90, attempts: 1 }
});
```

### E-commerce

```javascript theme={null}
// Purchase
await client.events.track({
  externalUserId: 'user-123',
  eventType: 'purchase_completed',
  properties: { orderId: 'o-1', amount: 149.99, category: 'electronics' }
});

// Review submitted
await client.events.track({
  externalUserId: 'user-123',
  eventType: 'review_submitted',
  properties: { productId: 'p-1', rating: 5 }
});
```

### Fitness App

```javascript theme={null}
// Workout completed
await client.events.track({
  externalUserId: 'user-123',
  eventType: 'workout_completed',
  properties: { type: 'running', duration: 1800, distance: 5000 }
});

// Goal achieved
await client.events.track({
  externalUserId: 'user-123',
  eventType: 'daily_goal_achieved',
  properties: { steps: 10500, caloriesBurned: 450 }
});
```

## Batch Events

Send multiple events in a single request for better performance:

```javascript theme={null}
await client.events.trackBatch([
  {
    externalUserId: 'user-123',
    eventType: 'page_viewed',
    properties: { page: '/dashboard' }
  },
  {
    externalUserId: 'user-123',
    eventType: 'feature_used',
    properties: { feature: 'export' }
  }
]);
```

## Rules Engine Integration

Events are processed by the Rules Engine to trigger automated rewards.

### Example Rule Configuration

```json theme={null}
{
  "name": "Lesson Completion Reward",
  "trigger": {
    "eventType": "lesson_completed"
  },
  "conditions": [
    {
      "type": "property_gte",
      "property": "score",
      "value": 80
    }
  ],
  "actions": [
    {
      "type": "grant_xp",
      "amount": 100
    },
    {
      "type": "grant_currency",
      "currency": "coins",
      "amount": 25
    },
    {
      "type": "progress_quest",
      "questId": "complete-10-lessons"
    }
  ]
}
```

This rule:

1. Triggers on `lesson_completed` events
2. Checks if `score >= 80`
3. Awards 100 XP, 25 coins, and progresses a quest

## Event Properties

Properties provide context for rule evaluation:

| Property Type | Example               | Use Case                |
| ------------- | --------------------- | ----------------------- |
| `string`      | `category: "science"` | Filter by category      |
| `number`      | `score: 95`           | Threshold conditions    |
| `boolean`     | `isPremium: true`     | User segmentation       |
| `array`       | `tags: ["featured"]`  | Multiple categorization |

## Real-Time Updates

When events trigger rewards, connected clients receive real-time updates via WebSocket:

```javascript theme={null}
// Subscribe to player updates
client.subscribe('player:user-123', (update) => {
  console.log('Player updated:', update);
  // { type: 'xp_updated', xp: 1600, level: 5 }
});

// Track event - subscribers will be notified of changes
await client.events.track({
  externalUserId: 'user-123',
  eventType: 'lesson_completed',
  properties: { score: 90 }
});
```

## Best Practices

<CardGroup cols={2}>
  <Card title="Consistent Naming" icon="tag">
    Use snake\_case for event types: `lesson_completed`, `purchase_made`
  </Card>

  <Card title="Rich Properties" icon="list">
    Include relevant context in properties for flexible rule creation
  </Card>

  <Card title="Idempotency Keys" icon="key">
    Use idempotency keys for important events to prevent duplicates
  </Card>

  <Card title="Batch When Possible" icon="layer-group">
    Batch multiple events together to reduce API calls
  </Card>
</CardGroup>

## Debugging Events

### View Event History

```javascript theme={null}
const events = await client.events.list({
  externalUserId: 'user-123',
  eventType: 'lesson_completed',
  limit: 10
});
```

### Check Processing Status

```javascript theme={null}
const status = await client.events.getStatus('event-id');
console.log(status);
// {
//   id: 'event-id',
//   status: 'processed',
//   rulesTriggered: ['lesson-completion-reward'],
//   actionsExecuted: ['grant_xp', 'grant_currency']
// }
```

## Related

<CardGroup cols={2}>
  <Card title="Rules Engine" icon="gears" href="/concepts/rules-engine">
    Configure rules to respond to events
  </Card>

  <Card title="Player Management" icon="user" href="/guides/player-management">
    Learn about player state and profiles
  </Card>
</CardGroup>
