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

# Product Analytics with PostHog

> Track user behavior and product metrics in your Zentra-powered application

Zentra integrates with [PostHog](https://posthog.com) for product analytics, enabling you to track user behavior, analyze conversion funnels, and make data-driven decisions.

<Note>
  PostHog integration is available for all Zentra tenants. Events are automatically captured from the Zentra backend, and you can add custom events from your application.
</Note>

## What Gets Tracked

Zentra automatically sends the following events to PostHog:

| Event                   | Description             | Properties                           |
| ----------------------- | ----------------------- | ------------------------------------ |
| `payment.completed`     | Successful payment      | `amount_minor`, `currency`, `method` |
| `payment.failed`        | Failed payment          | `reason`, `amount_minor`             |
| `transfer.completed`    | Bank transfer completed | `amount_minor`, `destination`        |
| `card.issued`           | New card created        | `cardType`, `tier`                   |
| `kyc.verified`          | KYC verification passed | `tier`, `documents`                  |
| `user.signed_up`        | New user registration   | `channel`, `referral`                |
| `session.authenticated` | User logged in          | `method`, `deviceType`               |

## Configuration

### 1. Get Your PostHog API Key

1. Sign up at [posthog.com](https://posthog.com) or self-host
2. Create a new project
3. Copy your **Project API Key**

### 2. Configure in Backend

Add your PostHog credentials to your environment:

```bash theme={null}
# .env
POSTHOG_API_KEY=phc_your_project_api_key
POSTHOG_HOST=https://app.posthog.com  # or your self-hosted URL
```

The Zentra Backend will automatically start sending events once configured.

## Custom Events

### From Your Backend

Add custom events from your application code:

```typescript theme={null}
import { PosthogService } from './analytics/posthog.service';

@Injectable()
export class CheckoutService {
  constructor(private readonly posthog: PosthogService) {}

  async completeCheckout(userId: string, cart: Cart) {
    // Your checkout logic...
    
    // Track custom event
    this.posthog.capture({
      distinctId: userId,
      event: 'checkout.completed',
      properties: {
        cartValue: cart.total,
        itemCount: cart.items.length,
        currency: 'NGN',
      },
    });
  }
}
```

### From Your Frontend

Install the PostHog JavaScript SDK:

```bash theme={null}
npm install posthog-js
```

Initialize and track events:

```typescript theme={null}
import posthog from 'posthog-js';

// Initialize (usually in your app entry point)
posthog.init('phc_your_project_api_key', {
  api_host: 'https://app.posthog.com',
});

// Identify user (after login)
posthog.identify(userId, {
  email: user.email,
  tier: user.kycTier,
});

// Track custom events
posthog.capture('button_clicked', {
  button: 'pay_now',
  page: '/checkout',
});
```

## Building Dashboards

### Conversion Funnel

Track your payment conversion funnel:

1. Go to **Insights** → **New Insight** → **Funnel**
2. Add steps:
   * `payment.pending`
   * `payment.completed`
3. Filter by `payment.method` to compare channels

### User Cohorts

Create cohorts based on behavior:

```
Users who have completed payment AND issued a card in the last 30 days
```

### Retention Analysis

Measure user retention:

1. Go to **Insights** → **Retention**
2. Set **Starting event**: `user.signed_up`
3. Set **Return event**: `payment.completed`

## Feature Flags

Use PostHog feature flags to control rollouts:

```typescript theme={null}
// Check feature flag
if (posthog.isFeatureEnabled('new_checkout_flow')) {
  // Show new checkout
} else {
  // Show classic checkout
}
```

## Best Practices

<AccordionGroup>
  <Accordion title="Use Consistent Event Names">
    Follow a naming convention like `noun.verb` (e.g., `payment.completed`, `card.issued`). This makes filtering and analysis easier.
  </Accordion>

  <Accordion title="Include Relevant Properties">
    Always include properties that help with analysis:

    * `amount_minor` and `currency` for transactions
    * `platform` (ios/android/web) for multi-platform apps
    * `user_tier` for segmentation
  </Accordion>

  <Accordion title="Respect User Privacy">
    Don't track personally identifiable information (PII) in event properties. Use user IDs instead of emails in event data.
  </Accordion>

  <Accordion title="Set Up Alerts">
    Configure alerts for anomalies:

    * Payment failure rate spikes
    * Drop in daily active users
    * Unusual transaction volumes
  </Accordion>
</AccordionGroup>

## Related Resources

<CardGroup cols={2}>
  <Card title="PostHog Docs" icon="book" href="https://posthog.com/docs">
    Official PostHog documentation
  </Card>

  <Card title="Tenant Analytics API" icon="chart-line" href="/api-reference/analytics/tenant-analytics">
    Programmatic access to your metrics
  </Card>
</CardGroup>
