# Migrate from PostHog

> Move a PostHog project to AppHelm. Import events, flags, experiments, cohorts, insights, dashboards and surveys, link people's ids, switch your SDK calls, and check the numbers before you cancel PostHog.

Source: https://apphelm.dev/docs/migrate-posthog

AppHelm covers what most teams use PostHog for: events and autocapture, insights and dashboards, feature flags and experiments, surveys, session replay, web analytics and error tracking. A migration has two halves: **bring your history and definitions across** with the importer, and **switch your code** to the AppHelm SDK. Run both tools side by side until the numbers agree, then remove PostHog.

## The plan

### Install AppHelm beside PostHog
Add the AppHelm SDK next to PostHog's ([Install and configure](https://apphelm.dev/docs/install)). Use the **same user id** you give PostHog as `distinct_id`, in the browser and on your server, so imported and new events join the same people. New data starts arriving now.

### Run a migration
**Settings → Import from PostHog**, with a PostHog personal API key, or with an export file of any size. Read its report, then start it.

### Connect revenue and your CRM
If PostHog's data warehouse held Stripe, HubSpot or a database, connect them in **Settings → Data sources** ([Data pipelines, imports and exports](https://apphelm.dev/docs/data-pipelines)).

### Switch your code
Replace PostHog calls with AppHelm's ([Switch your code](#switch-your-code)). The migrated flags keep their keys, lower-cased, so flag checks only change the client they call. Start the migrated experiments.

### Dual-run, then remove PostHog
Run both for at least one full reporting cycle (two weeks is usual), compare the [checklist](#dual-run-checklist), then remove PostHog from your code and cancel it.

## Run a migration

### With a PostHog personal API key

This is the recommended path: it brings events, people and every definition.

1. In PostHog open **Settings → Personal API keys → Create key** with read access to the project and the scopes `query`, `person`, `cohort`, `feature_flag`, `experiment`, `insight`, `dashboard`, `survey`, `annotation`, `action` and `group`. The key starts with `phx_`.
2. In AppHelm choose the product to fill, the region (**US**, **EU**, or your own PostHog's public https address), the project id (the number in your PostHog project's address), and paste the key.
3. Choose the date range. It defaults to as far back as your plan keeps events, and never more than 400 days: older events would be deleted by the next retention run, so they are never imported.

The key is checked against the project straight away (a wrong key or project is said at once), stored encrypted, used only to read, deleted as soon as the migration ends or is cancelled, and never shown again or written to a log.

### With an export file

Choose **Export file of any size** and pick a file:

- **JSON Lines**: PostHog's batch export of events, and optionally persons.
- **CSV**: a header with `event` and `timestamp`; `distinct_id`, `uuid`, `properties` and other columns are optional.

Either may be gzipped. The page decompresses the file in your browser and sends it in parts of about 8 MB; an interrupted upload resumes when you choose the same file again. Person rows and `$identify`, `$create_alias` and `$groupidentify` events become identity links, traits and groups exactly as from the API. A file has no definitions, so flags, cohorts, insights and dashboards come only with an API-key migration.

### The report comes first

Before anything is written, AppHelm builds a dry-run report: events in the date range counted by name with what each becomes, people and group types, and every flag, experiment, cohort, insight, dashboard, survey, annotation and action, each marked as mapping fully, partly or not at all, with the reasons. Nothing is written until you press **Start**.

Then it runs by itself, a bounded step every few minutes, in this order: definitions, people, groups, events. You can leave the page. It survives deploys, waits as long as PostHog asks when rate-limited, and can be paused, resumed and cancelled. A key PostHog refuses pauses the migration until you paste a new one.

### Limits

| Limit | Value |
| --- | --- |
| Oldest event | Your plan's capture retention (Free 14 days, Builder 30, Portfolio 90, Scale 365), never more than 400 days |
| Imported events per workspace per UTC day | 250,000. A larger history continues the next day by itself |
| Open imports per workspace | 1 at a time |
| Undo | Within 30 days after the migration finishes |
| Monthly event allowance | Imported events **don't** count against it |

Imported events never trigger alerts or webhooks, and a privacy deletion always wins over an import.

### Undo

**Undo migration** (within 30 days) removes everything the migration wrote: its events and the issues they added, identity links, imported traits and groups, and the flags (switched off and archived), cohorts, insights, dashboards, surveys and annotations it created. Live data, and anything you made yourself, is untouched.

## What moves across

| PostHog | AppHelm | Notes |
| --- | --- | --- |
| Project | Product | One migration fills one product |
| Events | Events, at their own dates | `$pageview` becomes `page_viewed`; `$pageleave`, `$autocapture`, `$rageclick` and `$screen` keep their names. Other `$` events (`$feature_flag_called`, `$snapshot`, `$web_vitals` …) are left out and counted. Deduplicated by uuid |
| `$exception` | Error issues | Grouped like live exceptions, so imported and live occurrences share an issue. Never alerts and never reopens a resolved issue |
| Person | Identity links and imported traits | See [People](#people) |
| Group | Imported group properties | Kept per group type and key |
| Feature flag | Flag with the same key, lower-cased | See [Flags and experiments](#flags-and-experiments) |
| Experiment | Draft experiment on the migrated flag | Results stay in PostHog |
| Cohort | Static cohort, or segment | A static cohort keeps its people (up to 10,000). A dynamic cohort becomes a segment when its rules are a flat AND or OR of exact person properties and "did event X (at least N times) in the last D days" (at most 90 days); anything else is listed as not mapped |
| Action | Expanded where it is used | AppHelm has no saved actions. A one-event action (with URL or property filters) is expanded into each insight that uses it; a multi-step or element-selector action is not mapped |
| Insight | Saved insight | Trends (series, maths, formulas, breakdowns, compare, cumulative), funnels, retention, paths, stickiness and lifecycle. SQL (HogQL) insights are not mapped: rewrite them in **Analytics → SQL** ([Insights, dashboards and SQL](https://apphelm.dev/docs/insights)) |
| Dashboard | Dashboard | Its mapped insights and text cards; at most 12 insights and 8 text cards |
| Survey | Draft survey | Open, single and multiple choice, rating and link questions, display rules and colours. Branching and flag targeting are not mapped. Needs your privacy policy version set |
| Annotation | Annotation | |
| Session recordings | Not migrated | New sessions record in AppHelm. Export recordings from PostHog first if you must keep them |
| Data warehouse sources | Data sources | Reconnect them in Settings → Data sources |

Properties are filtered the way live ingest filters them: `$ip`, user agents, element chains, input values, PostHog's project token and other `$` bookkeeping are never imported; custom properties keep at most 20 keys, strings are scrubbed of emails, keys and tokens, and keys named like a secret or contact detail are dropped.

### People

PostHog keeps a person as a set of distinct ids and properties. AppHelm brings them across as:

- **Identity links.** Each of a person's other distinct ids is linked to the id they signed in with, under the same rules as a live `$create_alias`: two identified people are never merged. Funnels, retention and paths then follow the person across their anonymous and identified ids.
- **Imported traits.** Properties are kept with their source and date and shown on the person page. `$` properties and anything named like a contact detail (email, phone, name) are left out.

A migration **does not create customer profiles**. Customer profiles (the people in **Customers**, with lifecycle states and outcomes) come from your server's `identify` calls, which is also where consent and trait provenance are recorded. Importing PostHog people as customer profiles is planned for after launch. Because every imported event carries the person's id hashed the same way as live events, a person's history joins their profile as soon as your server identifies them.

People deleted through AppHelm's privacy tools are skipped, and stay deleted.

### Flags and experiments

A flag keeps its rollout, multivariate variants with their payloads, and release conditions on person properties, country, browser, OS, device type, app version, cohorts and other flags.

> **Condition sets combine differently:** PostHog releases a flag to anyone matching **any** of its condition sets; AppHelm combines conditions with **AND**. A flag with several condition sets keeps only the first, is saved as a **draft**, and the report says so. Regex, date and "not contains" operators, group-level flags and variant overrides are listed as not mapped. A flag that maps completely keeps its on or off state; anything that doesn't behave exactly as in PostHog is saved as a draft for you to review before you turn it on.

Experiments are created as **drafts** on their migrated flag, with funnel, conversion, count, mean (sum of a property) and ratio metrics. Their results stay in PostHog: PostHog's exposure events (`$feature_flag_called`) are not imported, because they would mix into AppHelm's exposures. Start each experiment once your app evaluates the flag through AppHelm. See [Experiments](https://apphelm.dev/docs/experiments).

## Switch your code

Most PostHog calls have an AppHelm call with the same shape. The main differences:

- **Browser and mobile events need consent.** The browser SDK sends nothing until `setConsent({ analytics: true })`; see [Privacy, consent and data controls](https://apphelm.dev/docs/privacy).
- **Server events name the person.** Pass the same user id as `distinct_id`; AppHelm hashes it the way the browser hashes its id, so the two join.
- **Flags are fail-closed** and never count against your event allowance. `getFeatureFlag` answers the variant for a multivariate flag, `true` for an enabled boolean flag, and `false` when the flag is off or can't be evaluated, as PostHog's does.

### Capture events

React:
```tsx
import { useTrack } from "@sansavision/apphelm/react";

const track = useTrack();
track({ name: "invoice_sent", properties: { amount: 42 } }); // posthog.capture("invoice_sent", { amount: 42 })
```

JavaScript (browser):
```js
analytics.track({ name: "invoice_sent", properties: { amount: 42 } });
```

React Native / Expo:
```ts
mobile.track({ name: "invoice_sent", properties: { amount: 42 } });
```

iOS (Swift):
```swift
apphelm.track("invoice_sent", properties: ["amount": 42])
```

Android (Kotlin):
```kotlin
Apphelm.track("invoice_sent", mapOf("amount" to 42))
```

Flutter:
```dart
apphelm.track('invoice_sent', properties: {'amount': 42});
```

Node.js:
```ts
await apphelm.capture({ distinctId: user.id, event: "invoice_sent", properties: { amount: 42 } });
```

Python:
```python
apphelm.capture("org_…", "prd_…", distinct_id=user.id, event_name="invoice_sent", properties={"amount": 42})
```

Java / Kotlin (JVM):
```kotlin
apphelm.capture(user.id, "invoice_sent", mapOf("amount" to 42), mapOf("company" to company.id))
```

Go:
```go
client.Capture(apphelm.Capture{
	DistinctID: user.ID,
	Event:      "invoice_sent",
	Properties: apphelm.Properties{"amount": 42},
	Groups:     map[string]string{"company": user.CompanyID},
})
```

Ruby:
```ruby
APPHELM.capture(distinct_id: user.id, event: "invoice_sent", properties: { amount: 42 }, groups: { company: user.company_id })
```

PHP:
```php
$apphelm->capture(distinctId: (string) $user->id, event: 'invoice_sent', properties: ['amount' => 42]);
```

.NET (C#):
```csharp
apphelm.Capture(user.Id, "invoice_sent", new Dictionary<string, object?> { ["amount"] = 42 });
```

Rust:
```rust
apphelm.capture(Event::new(&user.id, "invoice_sent").property("amount", 42).group("company", &company.id))?;
```

Elixir:
```elixir
Apphelm.capture(user.id, "invoice_sent", %{amount: 42}, groups: %{company: account.id})
```

HTTP (curl):
```bash
curl -X POST https://apphelm.dev/api/v1/events \
  -H "Authorization: Bearer $APPHELM_API_KEY" -H "Content-Type: application/json" \
  --data '{"workspaceId":"org_…","productId":"prd_…","eventName":"invoice_sent","properties":{"distinct_id":"user-123","amount":42}}'
```

Server SDKs take `groups` on an event as PostHog's do; they are sent as `$groups`. `register`, `unregister` and `reset` exist on the browser and React Native clients with PostHog's meaning.

### Identify people and groups

JavaScript (browser):
```js
analytics.identify(user.id, { plan: "pro" });            // posthog.identify
analytics.group("company", company.id, { name: "Acme" }); // posthog.group
analytics.reset();                                        // posthog.reset, at sign-out
```

React Native / Expo:
```ts
mobile.identify(user.id, { plan: "pro" });
mobile.group("company", company.id, { name: "Acme" });
```

iOS (Swift):
```swift
apphelm.identify(user.id, traits: ["plan": "pro"])
apphelm.group(type: "company", key: org.id, traits: ["name": org.name])
```

Android (Kotlin):
```kotlin
Apphelm.identify(user.id, mapOf("plan" to "pro"))
Apphelm.group("company", account.id, mapOf("name" to account.name))
```

Flutter:
```dart
apphelm.identify(user.id, traits: {'plan': 'pro'});
apphelm.group('company', org.id, traits: {'name': org.name});
```

Python:
```python
apphelm.identify("org_…", "prd_…", distinct_id=user.id, traits={"plan": "pro"}, anon_distinct_id=anon_id)
apphelm.group("org_…", "prd_…", "company", company.id, {"name": company.name})
```

Go:
```go
client.Identify(apphelm.Identify{DistinctID: user.ID, AnonDistinctID: anonID, Traits: apphelm.Properties{"plan": "pro"}})
client.GroupIdentify(apphelm.GroupIdentify{Type: "company", Key: company.ID, Properties: apphelm.Properties{"name": company.Name}})
```

Ruby:
```ruby
APPHELM.identify(distinct_id: user.id, anon_distinct_id: cookies[:anon_id], traits: { plan: "pro" })
APPHELM.group_identify(group_type: "company", group_key: company.id, properties: { name: company.name })
```

PHP:
```php
$apphelm->identify((string) $user->id, ['plan' => 'pro']);
$apphelm->groupIdentify('company', (string) $company->id, ['name' => $company->name]);
```

.NET (C#):
```csharp
apphelm.Identify(user.Id, new Dictionary<string, object?> { ["plan"] = "pro" });
apphelm.GroupIdentify("company", company.Id, new Dictionary<string, object?> { ["name"] = company.Name });
```

Rust:
```rust
apphelm.identify(Identify::new(&user.id).set("plan", "pro").anon_distinct_id(anon_id))?;
apphelm.group_identify(GroupIdentify::new("company", &company.id).property("name", &company.name))?;
```

Elixir:
```elixir
Apphelm.identify(user.id, traits: %{plan: "pro"}, anon_distinct_id: anon_id)
Apphelm.group_identify("company", account.id, %{name: account.name})
```

These send `$identify` and `$groupidentify`, which link ids for analytics as PostHog's do. Customer profiles with governed traits are a separate server call, where every trait carries its provenance: [Users, people and groups](https://apphelm.dev/docs/identify) explains both, and why the browser's traits are kept as "stated by the browser".

**Only for Node.js:**

The Node client's `identify(userId, options)` is the customer-profile call: `await apphelm.identify(user.id)`. Traits passed to it need `traitSources` naming where each came from. For PostHog-style `$identify` from the browser, call `identify` on the browser client.

### Feature flags

React:
```tsx
import { useFeatureFlag, useFeatureFlagVariant, useFeatureFlagPayload } from "@sansavision/apphelm/react";

const on = useFeatureFlag("new-checkout");         // posthog.isFeatureEnabled
const variant = useFeatureFlagVariant("pricing");  // posthog.getFeatureFlag: "blue", true or false
const limits = useFeatureFlagPayload("limits");    // posthog.getFeatureFlagPayload
```

JavaScript (browser):
```js
analytics.isEnabled("new-checkout");
analytics.getFeatureFlag("pricing");        // "blue", true or false
analytics.getFeatureFlagPayload("limits");  // the JSON payload, or null
```

React Native / Expo:
```ts
await mobile.isEnabled("new-checkout");
await mobile.getFeatureFlag("pricing");
```

Android (Kotlin):
```kotlin
Apphelm.isFeatureEnabled("new-checkout")
Apphelm.getFeatureFlag("pricing")
Apphelm.getFeatureFlagPayload("limits")
```

Flutter:
```dart
apphelm.isFeatureEnabled('new-checkout');
apphelm.getFeatureFlag('pricing');
apphelm.getFeatureFlagPayload('limits');
```

Node.js:
```ts
await apphelm.isEnabled("new-checkout", user.id);
await apphelm.getFeatureFlag("pricing", user.id);
await apphelm.getAllFlagsAndPayloads(user.id); // { featureFlags, featureFlagPayloads }
```

Python:
```python
apphelm.is_enabled("new-checkout", user.id, "prd_…")
apphelm.get_feature_flag("org_…", "prd_…", "pricing", user.id)
```

Go:
```go
client.IsEnabled(ctx, "new-checkout", user.ID, nil)
client.GetFeatureFlag(ctx, "pricing", user.ID, nil)
client.GetFeatureFlagPayload(ctx, "limits", user.ID, nil)
```

Ruby:
```ruby
APPHELM.is_enabled("new-checkout", user.id)
APPHELM.get_feature_flag("pricing", user.id)
APPHELM.get_feature_flag_payload("limits", user.id)
```

PHP:
```php
$apphelm->isEnabled('new-checkout', (string) $user->id);
$apphelm->getFeatureFlag('pricing', (string) $user->id);
$apphelm->getFeatureFlagPayload('limits', (string) $user->id);
```

.NET (C#):
```csharp
await apphelm.IsFeatureEnabledAsync("new-checkout", user.Id);
await apphelm.GetFeatureFlagAsync("pricing", user.Id);
await apphelm.GetFeatureFlagPayloadAsync("limits", user.Id);
```

Rust:
```rust
apphelm.is_enabled("new-checkout", &user.id, &FlagOptions::new());
apphelm.get_feature_flag("pricing", &user.id, &FlagOptions::new());
```

Elixir:
```elixir
Apphelm.enabled?("new-checkout", user.id)
Apphelm.get_feature_flag("pricing", user.id)
Apphelm.get_feature_flag_payload("limits", user.id)
```

HTTP (curl):
```bash
curl -X POST https://apphelm.dev/api/v1/flags/evaluate \
  -H "Authorization: Bearer $APPHELM_API_KEY" -H "Content-Type: application/json" \
  --data '{"productId":"prd_…","distinctId":"user-123","flagKey":"pricing"}'
```

Reading a flag that a running experiment uses records an exposure, `apphelm.flag_evaluated` (PostHog's `$feature_flag_called`), once per person and variant. Before 0.7.0 the SDKs answered `"on"` for an enabled boolean flag; from 0.7.0 they answer `true`, as PostHog does. Local evaluation, bootstrapping and targeting are on [Feature flags](https://apphelm.dev/docs/feature-flags).

### Surveys

Migrated surveys arrive as drafts: open each, check its questions and targeting, and launch it. In the browser, surveys set to show automatically (by URL, selector, event or screen) appear once launched, with no code. React Native (`@sansavision/apphelm/react-native-surveys`) and Flutter (`enableAutomaticSurveys`) show them after one setup call; iOS and Android are headless: ask with `surveyEligible` and draw the question in your own UI. To show a survey yourself in the browser, as with PostHog's API surveys, use `apphelm.surveys.eligible`, then `present`, or `respond` and `dismiss`. See [Surveys](https://apphelm.dev/docs/surveys).

### Everything else

| PostHog | AppHelm |
| --- | --- |
| `posthog.captureException(err)` | `apphelm.captureException(err)` ([Errors and issues](https://apphelm.dev/docs/errors)) |
| Session replay (`session_recording` options) | The browser SDK's `replay` option; records after `setConsent({ analytics: true, replay: true })` ([Session replay](https://apphelm.dev/docs/session-replay)) |
| Autocapture, `$pageview`, `$pageleave` | On by default in the browser SDK; pageviews are `page_viewed` ([Events and autocapture](https://apphelm.dev/docs/events)) |
| `$ai_generation` events (LLM analytics) | The same `$ai_*` events, from AppHelm's LLM wrappers ([LLM analytics](https://apphelm.dev/docs/llm-analytics)) |
| Early access features | `getEarlyAccessFeatures` and `updateEarlyAccessFeatureEnrollment` on the Node client |
| HogQL | AppHelm SQL, which takes most HogQL queries unchanged ([Insights, dashboards and SQL](https://apphelm.dev/docs/insights)) |

## API mapping

AppHelm's REST API lives at `https://apphelm.dev/api/v1` and takes a server key as a Bearer token ([Using the API](https://apphelm.dev/docs/api-overview)).

| PostHog API | AppHelm API |
| --- | --- |
| `POST /capture`, `/batch` (project key) | `POST /api/v1/events` (server key), or `POST /api/events` with `X-Apphelm-Key` from a browser |
| `POST /flags`, `/decide` | `POST /api/v1/flags/evaluate` (server); the browser SDK calls `/api/flags/bootstrap` |
| `/api/projects/:id/feature_flags` | `/api/v1/flags` and `/api/v1/flags/{id}` |
| Local evaluation definitions | `GET /api/v1/flags` (needs `products:read`) |
| Remote config | `GET /api/v1/flags/remote-config` |
| `/api/projects/:id/experiments` | `/api/v1/experiments` |
| `/api/projects/:id/surveys` | `/api/v1/surveys` |
| `/api/projects/:id/insights` | `/api/v1/saved-insights` |
| `/api/projects/:id/dashboards` | `/api/v1/dashboards` |
| `/api/projects/:id/cohorts` | `/api/v1/cohorts` |
| `/api/projects/:id/annotations` | `/api/v1/annotations` |
| `/api/projects/:id/query` (HogQL) | `POST /api/v1/query/sql`; `GET /api/v1/query` for trends, funnels, retention and paths |
| `/api/projects/:id/session_recordings` | `GET /api/v1/sessions` (metadata only) |
| Batch exports | `/api/v1/pipelines` ([Data pipelines, imports and exports](https://apphelm.dev/docs/data-pipelines)) |
| Person deletion | `POST /api/v1/privacy/delete` |

The migration itself is on the API and on [MCP](https://apphelm.dev/docs/mcp) too, with a key that holds `imports:write` (an owner or admin must add that scope by name):

```bash
# Start: builds the report, writes nothing
curl https://apphelm.dev/api/v1/imports -H "Authorization: Bearer $APPHELM_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" -H "Content-Type: application/json" \
  --data '{"productId":"prd_…","host":"eu","projectId":"12345","apiKey":"phx_…"}'

# Read the report and progress
curl https://apphelm.dev/api/v1/imports/phm_… -H "Authorization: Bearer $APPHELM_API_KEY"

# Start it (or pause, resume, cancel, discard, undo, replace_key)
curl https://apphelm.dev/api/v1/imports/phm_… -H "Authorization: Bearer $APPHELM_API_KEY" \
  -H "Content-Type: application/json" --data '{"action":"start"}'
```

## Dual-run checklist

Compare the same days in both tools:

- [ ] Daily events and unique users of your top five events. Imported days show as their own dashed line on the volume chart.
- [ ] Your main funnel's conversion, with the same steps and window.
- [ ] Week-1 retention of new users.
- [ ] Exposure counts for two or three flags (AppHelm counts `apphelm.flag_evaluated`).
- [ ] Every item the report listed as partly mapped or not mapped has an owner: redone in AppHelm, or knowingly dropped.
- [ ] Revenue: last month's Stripe charges in AppHelm match Stripe.
- [ ] The top error issues appear with similar counts.

Small differences are expected: AppHelm counts people by a 64-bit hash pair, PostHog by person id; bots and internal traffic are filtered by different rules; and events older than your plan's retention are not imported.

## Cancel PostHog

1. Remove the PostHog snippet and SDK calls; keep the AppHelm ones.
2. Delete the PostHog personal API key you created for the migration (AppHelm already deleted its copy).
3. Export what you must keep: recordings, and raw events older than your AppHelm plan keeps.
4. Cancel the PostHog subscription or delete the project.

## Troubleshooting

| Symptom | Likely cause | What to do |
| --- | --- | --- |
| "PostHog refused the personal API key" | The key lacks a scope, or belongs to another project | Create a key with read access to the project and the scopes listed above, and paste it again |
| The migration waits with "no room left today" | The workspace imported 250,000 events today | Nothing: it continues after midnight UTC |
| Old events are missing | They are older than your plan's capture retention | Expected; upgrading the plan before migrating keeps more history |
| A flag arrived as a draft | It has several condition sets, or an operator AppHelm lacks | Read the reason in the report, adjust its conditions, then turn it on |
| An imported person doesn't appear in Customers | Imports create identity links and traits, not customer profiles | Identify them from your server; their imported history joins the profile |
| Browser events don't arrive | Analytics consent hasn't been given | Call `setConsent({ analytics: true })` from your consent banner |
| Funnels split one person in two | The browser and the server use different ids | Give both the same user id (`identify` in the browser, `distinct_id` on the server) |
| Something went wrong | Anything | **Undo migration** within 30 days removes everything it wrote |
