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

# Understanding Events

> What events are, event types, naming conventions, and best practices.

Events are the foundation of your data — they record every action users take in your application. This guide explains what events are, the different types you can track, and best practices for naming and structuring them.

***

## What is an Event?

An **event** is a timestamped record of something that happened in your product. It's like a digital breadcrumb trail that captures every meaningful action your users take.

Think of events as the **verbs** of your data model. While user attributes describe **who** someone is (their name, email, plan type), events describe **what** they do (clicked, purchased, logged in, shared).

### The Simple Definition

If you can describe it as "User did X at time Y," it's an event.

**Examples:**

* "Sarah added Red Sneakers to cart at 2:30 PM" → Event: `Added to Cart`
* "John upgraded to Pro plan at 10:15 AM" → Event: `Upgraded Plan`
* "Anonymous visitor viewed pricing page at 3:45 PM" → Event: `Viewed Pricing Page`

### Why Events Matter

Events are powerful because they let you:

1. **Understand user behavior**: See exactly what users do in your product
2. **Measure what matters**: Count how many people signed up, purchased, or churned
3. **Build conversion funnels**: Track the path from first visit to purchase
4. **Trigger automated workflows**: Send email when user abandons cart
5. **Personalize experiences**: "You recently viewed these items"
6. **Calculate business metrics**: Revenue, engagement, retention rates

### What Every Event Captures

Each event in Zixflow automatically records:

* **Who** did it → `userId` (if known) or `anonymousId` (if not)
* **What** they did → Event name like "Purchased" or "Signed Up"
* **When** it happened → Timestamp, precise to the millisecond
* **Where** it happened → Platform (web/iOS/Android), location, device type
* **How** they did it → Context like browser, screen size, app version
* **Custom details** → Properties you add (product name, price, category)

### Event Structure

Here's what a typical event looks like:

```json theme={null}
{
  "event_name": "Added to Cart",
  "user_id": "sarah@example.com",
  "timestamp": "2026-05-04T14:32:15Z",
  "properties": {
    "product_name": "Red Sneakers",
    "product_id": "prod_789",
    "price": 89.99,
    "currency": "USD",
    "quantity": 1
  },
  "context": {
    "platform": "web",
    "browser": "Chrome",
    "screen_size": "1920x1080",
    "country": "United States"
  }
}
```

**Key parts:**

* **event\_name**: The action that happened
* **properties**: Custom details about this specific action
* **context**: Automatically captured information about the user's environment
* **timestamp**: Exactly when it occurred

**What makes events powerful:** Once stored in Zixflow, you can search across millions of events instantly to find patterns, build segments, or trigger campaigns.

***

## Event Types

Zixflow supports four types of events. Each serves a different purpose in tracking user behavior:

### 1. **Track Events** (Custom Actions)

**What:** The events you define based on what matters to your business. This is your primary event type for tracking user behavior.

**When to use:**

* User lifecycle milestones: `Signed Up`, `Completed Onboarding`, `Upgraded Plan`
* Feature usage: `Created Project`, `Ran Report`, `Exported Data`
* Revenue events: `Subscribed`, `Payment Received`, `Refunded`
* Engagement: `Invited Teammate`, `Shared Dashboard`, `Left Comment`

**Examples:**

```javascript theme={null}
// JavaScript
Zixflow.track('Purchased', {
  order_id: 'ord_12345',
  revenue: 89.99,
  currency: 'USD',
  items: ['Red Sneakers', 'White Socks']
});
```

```dart theme={null}
// Flutter/Dart
Zixflow.track(
  name: 'Purchased',
  properties: {
    'order_id': 'ord_12345',
    'revenue': 89.99,
    'currency': 'USD',
    'items': ['Red Sneakers', 'White Socks']
  }
);
```

**What you can do with track events:**

* Build segments: "Users who purchased in the last 30 days"
* Trigger campaigns: "Send thank-you email after Purchase event"
* Run analytics: "What % of signups complete a purchase?"
* Measure conversion: Track funnel from signup → activation → purchase
  'items': \['Red Sneakers', 'White Socks'],
  },
  );

````

---

### 2. **Screen Events** (Mobile Navigation)

**What:** When a user views a screen in your mobile app (iOS, Android, React Native, Flutter).

**When to use:** Mobile applications where you want to track navigation flow.

**Examples:**
- `Home Screen`
- `Product Details`
- `Shopping Cart`
- `Checkout`
- `Profile Settings`

**Auto-tracking:** Our SDK can automatically track screen views when configured. You can also manually track specific screens.

**Database table:** `profile_events` with `event_type = 2` (screen)

**SDK call:**
```dart
// Flutter - Manual screen tracking
Zixflow.instance.screen(
  title: 'Product Details',
  properties: {
    'product_id': 'prod_789',
    'category': 'Shoes',
  },
);
````

**Use cases:**

* Conversion funnel analysis: Signup → Activation → Paid conversion
* Feature adoption tracking: % of users who've used Feature X
* Campaign trigger conditions: "User upgraded to Pro" → Send thank-you email

***

### 3. **Page Events** (Web Navigation)

**What:** When a user views a page on your website or web application.

**When to use:** Web applications, marketing sites, content platforms.

**Examples:**

* `/` (Homepage)
* `/pricing` (Pricing page)
* `/blog/getting-started` (Blog post)
* `/product/red-sneakers` (Product page)
* `/checkout` (Checkout page)

**Auto-tracking:** Can be configured to automatically track page views with our JavaScript SDK.

**Database table:** `profile_events` with `event_type = 3` (page)

**SDK call:**

```javascript theme={null}
// JavaScript - Manual page tracking
Zixflow.page({
  name: 'Product Details',
  properties: {
    path: '/product/red-sneakers',
    url: 'https://store.example.com/product/red-sneakers',
    referrer: 'https://google.com/search',
    title: 'Red Sneakers - Example Store'
  }
});
```

**Common use cases:**

* Track marketing campaign effectiveness
* Understand content engagement
* Build page-view funnels
* Identify high-exit pages

***

### 4. **Identify Events** (User Identification)

**What:** Special event that links anonymous browsing history to a known user profile. Triggers identity resolution and profile creation/update.

**When to use:**

* Immediately after signup (new user)
* On login (returning user)
* When you learn identifying info (email capture via newsletter signup)

**What happens on `identify()`:**

1. Creates or updates the user's profile with the information you provide
2. Records when this identification happened (for audit purposes)
3. **Identity merge**: If you include both `userId` and `anonymousId`, Zixflow automatically:
   * Finds all anonymous activity from this visitor
   * Links it to the identified user profile
   * Updates the user's complete history
   * Prevents duplicate merges (processes once)

**SDK call:**

```javascript theme={null}
// JavaScript - After signup/login
Zixflow.identify({
  userId: 'sarah@example.com',
  traits: {
    name: 'Sarah Johnson',
    email: 'sarah@example.com',
    plan: 'pro',
    created_at: '2026-05-04T10:00:00Z'
  }
});
```

```dart theme={null}
// Flutter - After signup/login
Zixflow.instance.identify(
  userId: 'sarah@example.com',
  traits: {
    'name': 'Sarah Johnson',
    'email': 'sarah@example.com',
    'plan': 'pro',
    'created_at': '2026-05-04T10:00:00Z',
  },
);
```

**What happens behind the scenes:**

1. Creates or updates user profile with provided information
2. Records when identification occurred
3. If both `userId` + `anonymousId` provided:
   * Triggers identity merge workflow (see [Users & Identity](/documentation/events/users-and-identity))
   * All anonymous events linked to identified user
   * System prevents duplicate merges automatically
4. Subsequent events from this device/session use `user_id` instead of `anonymous_id`

***

## Event Properties Explained

Properties add context to events. They answer: *"What details matter about this action?"*

### Property Structure

Properties are key-value pairs attached to events:

```javascript theme={null}
Zixflow.track({
  name: 'Purchased',
  properties: {
    // Order info
    order_id: 'ord_12345',
    revenue: 89.99,
    currency: 'USD',
    
    // Product info
    product_name: 'Red Sneakers',
    product_id: 'prod_789',
    category: 'Shoes',
    
    // Context
    payment_method: 'credit_card',
    shipping_method: 'express',
    coupon_code: 'SAVE10'
  }
});
```

### Common Property Patterns

**Product properties:**

* `product_id`: Unique identifier
* `product_name`: Human-readable name
* `sku`: Stock keeping unit
* `category`: Product category
* `brand`: Manufacturer/brand
* `price`: Unit price
* `currency`: USD, EUR, etc.

**Transaction properties:**

* `order_id`: Unique order identifier
* `revenue`: Total amount
* `tax`: Tax amount
* `shipping`: Shipping cost
* `discount`: Discount applied
* `payment_method`: How they paid

**User action context:**

* `source`: Where did they come from? (homepage, search, email)
* `referrer`: Full referrer URL
* `search_term`: What they searched for
* `filter_applied`: Active filters
* `sort_order`: How they sorted results

### Keep It Simple

**Rule of thumb:** Only track properties you'll actually use for:

* Personalization ("You viewed Red Sneakers")
* Analysis ("Average order value by payment method")
* Triggered campaigns ("Coupon code was used")

**Don't over-track:**

* ❌ 50 properties per event (too much)
* ❌ Duplicate data (if it's a user attribute, don't put it in every event)
* ❌ Sensitive PII (passwords, credit card numbers, SSNs)

***

## System vs Custom Events

### System Events (Auto-Generated)

These events are created automatically by the system — you don't need to call `track()` for them.

#### Device Lifecycle Events

Sent automatically by the SDK and routed to the `device_logs` table (not the main events table):

| Event Name                  | When it fires                                                          |
| --------------------------- | ---------------------------------------------------------------------- |
| `Application Installed`     | First launch after install                                             |
| `Application Opened`        | App moves to foreground                                                |
| `Application Backgrounded`  | App moves to background                                                |
| `Application Foregrounded`  | App returns from background (distinct from cold open)                  |
| `Application Crashed`       | SDK detects an unhandled crash on next launch                          |
| `Device Created or Updated` | SDK registers or updates device info with Zixflow                      |
| `Device Registered`         | Device token successfully registered for push                          |
| `Device Updated`            | Device attributes changed (new OS version, app update, token rotation) |

These events are stored with a 30-day retention window. They feed device health monitoring and platform analytics, but are separate from your business events.

#### User Lifecycle Events

These are server-side lifecycle events that change the state of a user profile. They carry no trait data — only the user ID and the action:

| Lifecycle Event     | Effect on profile                                                           |
| ------------------- | --------------------------------------------------------------------------- |
| `User Deleted`      | Sets `is_deleted = true` + cascades deactivation to all linked devices      |
| `User Suppressed`   | Sets `is_suppressed = true` — blocks all outbound messages on every channel |
| `User Unsuppressed` | Clears the suppressed flag — message delivery resumes                       |

**User Deleted** and **User Suppressed/Unsuppressed** are triggered server-side (via the Track API v1 or your backend). You cannot trigger them from the client SDK.

#### Device Deletion

| Lifecycle Event  | Effect                                                                          |
| ---------------- | ------------------------------------------------------------------------------- |
| `Device Deleted` | Soft delete: sets `active = false`, `push_enabled = false` on the device record |

This stops push notifications being sent to that device without permanently removing the record.

### Custom Events (You Define)

Everything else! You decide what matters for your business:

* User actions: Clicked, Viewed, Purchased, Shared
* Product usage: Feature used, Setting changed, Export created
* Business events: Trial started, Plan upgraded, Referral sent
* Content engagement: Article read, Video watched, Comment posted

***

## When NOT to Use Events

Events are for actions. Attributes are for facts. Don't confuse the two!

### ❌ Wrong: Tracking State Changes as Events

**Bad example:**

```javascript theme={null}
// DON'T DO THIS
Zixflow.track({ name: 'Became Premium User' });
Zixflow.track({ name: 'Email Changed to sarah@example.com' });
Zixflow.track({ name: 'Name Changed to Sarah Johnson' });
```

**Why it's wrong:** These are **attribute updates**, not actions the user took.

### ✅ Right: Update Attributes + Track Action Event

**Good example:**

```javascript theme={null}
// Update the attribute (WHO they are)
Zixflow.setProfileAttributes({
  plan: 'premium',
  email: 'sarah@example.com',
  name: 'Sarah Johnson'
});

// Track the action (WHAT they did)
Zixflow.track({ 
  name: 'Upgraded Plan',
  properties: {
    from_plan: 'free',
    to_plan: 'premium'
  }
});
```

**Why it's right:** The attribute stores the current state. The event records that the upgrade happened (for analytics and triggers).

### Rule of Thumb

**Use attributes for:**

* Current state: email, name, plan, status
* Computed values: total\_purchases, last\_login, lifetime\_value
* Demographics: age, location, company

**Use events for:**

* Actions: clicked, viewed, purchased, upgraded
* One-time occurrences: signed\_up, cancelled, shared
* Timestamps: when things happened

***

## Privacy Considerations

### What NOT to Track

**Never** put these in event names or properties:

* ❌ Passwords or credentials
* ❌ Credit card numbers
* ❌ Social security numbers
* ❌ Medical information
* ❌ Full date of birth (age range is okay)

### What's Safe to Track

✅ User actions and behavior (clicked, viewed, purchased)\
✅ Product data (names, prices, categories)\
✅ Transaction IDs (order\_id, session\_id)\
✅ Aggregated data (count, average, total)\
✅ Email addresses (if user consented)\
✅ Device information (platform, OS version)

### GDPR/CCPA Compliance

Users have the right to:

* **Access their data**: Export all events via API
* **Delete their data**: Remove all events and profile via `DELETE /api/v1/customers/:id`
* **Opt out**: Stop tracking via unsubscribe/opt-out flags

***

**Next:** Learn how anonymous visitors become identified users → [Users & Identity](/documentation/events/users-and-identity)
