# `posthog`

| Package | Kind | Provides the role | Needs | Choose with |
| --- | --- | --- | --- | --- |
| [`smf_posthog`](https://pub.dev/packages/smf_posthog) | infrastructure | Analytics | values in `.env`, such as [`dart_define`](https://doc.saymyframe.com/modules/dart-define.md) | `-m posthog` |

`posthog` records what the users of the app do in [PostHog](https://posthog.com), with the [posthog_flutter](https://pub.dev/packages/posthog_flutter) package: the events that the app logs through its `AnalyticsService` and, in an app with a router, a `$screen` event for each screen the user sees.

An app can have several modules of analytics, and its service forwards each call to all of them, so `posthog` works on its own or next to [`firebase_analytics`](https://doc.saymyframe.com/modules/firebase-analytics.md). The code of the app logs through `AnalyticsService` and never through PostHog; see [Crash reporting and analytics](https://doc.saymyframe.com/guides/crash-reporting-and-analytics.md).

The project token and the host go into `.env`, so the module brings [`dart_define`](https://doc.saymyframe.com/modules/dart-define.md) while that module is the only provider of the values in `.env`.

## What it adds to the app

| In the app | What it is |
| --- | --- |
| `posthog_flutter: ^5.61.0` in the dependencies | The SDK of PostHog. In `lib/`, only the file below imports it. |
| `lib/core/analytics/posthog_analytics_service.dart` | `initPostHogAnalytics()`, which starts PostHog, `PostHogAnalyticsService`, the service of the module, `postHogProjectToken()`, which checks the token, and, in an app with a router, `logPostHogScreen()`, the listener of the screen |
| The keys `POSTHOG_PROJECT_TOKEN` and `POSTHOG_HOST` in `.env` | The project token of your PostHog project and its host, through the role of the values in `.env` |
| `com.posthog.posthog.AUTO_INIT` with `false` in `android/app/src/main/AndroidManifest.xml` and `ios/Runner/Info.plist` | Keeps the SDKs of PostHog for Android and iOS from starting on their own before any Dart code runs |
| `com.posthog.posthog.CAPTURE_PUSH_NOTIFICATION_OPENED` with `false` in `ios/Runner/Info.plist` | Keeps the plugin from recording the push messages that the user opens, which belong to the push role |
| The section "PostHog" of the README | The token and the host, the flavor of each event, the screens, what PostHog records and what not, the user, the versions of the SDKs and what to tell the privacy policy |

Whichever module provides it, the analytics role adds `lib/core/analytics/analytics_service.dart` with `AnalyticsService`, `createAnalyticsService()` and `analyticsCollectedFromFirstStart`; see [`firebase_analytics`](https://doc.saymyframe.com/modules/firebase-analytics.md#what-it-adds-to-the-app). PostHog starts asynchronously, so the file also has `initAnalytics()`, which `bootstrap()` awaits. This is `bootstrap()` of an app with this module and `dart_define`, which comes with it:

```dart title="lib/bootstrap.dart"
Future<void> bootstrap() async {
  checkEnvValues(debugPrint);
  await initAnalytics();
}
```

In the [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app, the analytics role describes the service under "Analytics". The module adds where PostHog starts, which events have the flavor, when to call `setUserId(null)` and `setUserId(id)`, and never to call `Posthog().optIn()`, `Posthog().optOut()` or `Posthog().reset()`. In an app with a router, it adds that screens need no code.

## The token and the host

`initPostHogAnalytics()` starts PostHog with `POSTHOG_PROJECT_TOKEN` and `POSTHOG_HOST` of `.env`:

```bash title=".env"
POSTHOG_PROJECT_TOKEN=phc_...
POSTHOG_HOST=
```

The project token starts with `phc_`. Leave the host empty for PostHog's US Cloud, or give it `https://eu.i.posthog.com` for its EU Cloud, or the address of your own PostHog. A project token only lets an app send events to its project, and it goes into the app, where anyone can read it, so it is no secret. A personal API key of PostHog, which starts with `phx_`, never goes into `.env`: the app refuses one, and a build with it has the key inside.

The start throws a `StateError` that names the key, and the role leaves PostHog out, when the build has no token, a token of spaces alone, which PostHog would not start with, or a personal API key, and when the host is no http or https address. The app then starts, logs to its other analytics services if it has any, and a debug build prints why.

## What PostHog records

Every event has the property `app_flavor`, the flavor of the build, such as `dev` or `prod`, except the first events of a new install: PostHog records `Application Installed`, and on Android also `Application Opened`, while it starts, before the app registers the property. A debug build records its events too, so filter the insights and the dashboards of PostHog on `app_flavor` equal to `prod` to count only the users of the release, and leave that filter out of an insight that counts installs.

A sign-in and a sign-up are the events `login` and `sign_up`, with the method in their property `method`, as Firebase Analytics names them.

In an app with a router, the router tells `logPostHogScreen()` each screen that the user sees, which PostHog records as a `$screen` event under the full name of its route, such as `home.home`. The fallback start screen of an app with no route to start on is recorded as `/`. The error screen of the router is not recorded, since the location that the app cannot show may hold anything, such as a token of a link. Nothing is recorded before PostHog started, or in a build without a token. The app has no `PosthogObserver`: one with its defaults would record each screen a second time.

PostHog is set up to record no more than the analytics of the app need:

- a person profile only for a user whom the app identifies with `setUserId()`, and none for an anonymous user;
- no session replay, no survey, and no request for feature flags at each start;
- nothing about push messages, which the push role handles;
- the events of the lifecycle of the app, such as `Application Opened`, and no errors, which the crash reporting of the app reports.

Surveys, which the app does not show, need `surveys = true` in the config of `initPostHogAnalytics()` and a `PosthogObserver` among the observers of the navigators. Give it `routeFilter: (_) => false`, so that it records no screen of its own.

## Collection

`setAnalyticsCollectionEnabled()` of the analytics service opts PostHog in and out, and PostHog keeps that on the device across starts. PostHog starts from Dart, so `analyticsCollectedFromFirstStart` alone decides what it does before the code chose, and the module writes no native line for that: `AUTO_INIT` only keeps its SDKs from starting before Dart. See [Crash reporting and analytics](https://doc.saymyframe.com/guides/crash-reporting-and-analytics.md#the-collection-switch).

Three things hold for PostHog in particular:

- On iOS, PostHog keeps nothing when the code chose what `analyticsCollectedFromFirstStart` says already. So an app that changes that constant from `false` to `true` collects on the devices of iOS whose users declined before.
- PostHog keeps the events that it has not sent yet in a queue on the device, and opting out does not empty it. Events that the app logged before `setAnalyticsCollectionEnabled(false)` may still leave with the next batch of PostHog, also at a later start.
- While collection is off, PostHog still asks its host for the configuration of the project at each start. That request carries no event, but it reaches PostHog with the IP address of the device, which a privacy policy may mention.

## The user

- `setUserId(null)` starts a new anonymous user in PostHog, so call it when the user signs out, not at each start.
- PostHog ignores an identify of another id while it has identified a user, also one of an earlier start. So `setUserId(id)` of another user resets PostHog first: the events of the next user never join the user before, and those of an anonymous user stay linked to the user whom PostHog identifies.
- PostHog keeps the user on the device from one start to the next, but the service does not know that user. After each start, call `setUserId(id)` for a user who is signed in. Until then, the properties that `setUserProperty()` sets wait in memory, and they are lost if the app closes.
- A property that `setUserProperty()` sets for a user without an id waits for the next id.
- While collection is off, PostHog gets neither a new user nor a property, and gets them once collection is on again.

`reset()` of PostHog forgets the setting of collection that PostHog keeps, so the service resets only while it collects, registers the flavor again after a reset, and in an app that collects nothing before its code chose has PostHog keep that collection is on again.

## The versions of the SDKs

posthog_flutter takes the SDKs of PostHog for Android and iOS in a range of versions, so each build takes the newest of the range, and each release of posthog_flutter raises the lowest. So the app does not pin them, or the next `flutter pub upgrade` would stop its build. To ship a build for a store with versions that you checked, pin the SDK for Android in `android/app/build.gradle.kts`:

```kotlin
dependencies {
    implementation("com.posthog:posthog-android") {
        version { strictly("<version>") }
    }
}
```

Raise that version whenever `flutter pub upgrade` raises posthog_flutter: a new posthog_flutter may need a newer SDK than the pin, and Gradle stops the build at a strict version that is too low. On iOS, Swift Package Manager writes the versions that it resolved into a `Package.resolved` of the Xcode workspace, and CocoaPods, in an app that builds with it, into `ios/Podfile.lock`: keep that file in git for a build for the App Store, and change it on purpose.

## Privacy

The App Store and Google Play ask for a privacy policy in the listing of the app and inside the app. PostHog gets what users do in the app, the screens that they see, an id of the device and the id of the user once the code sets one, with the properties of the user, the model and the system of the device, and a coarse location, which PostHog infers from the IP address of the device unless `disableGeoIp` is set when PostHog starts. PostHog keeps the IP address of the device too, unless the settings of the project discard client IP data. The SDKs of PostHog for iOS declare what they collect in their privacy manifests.

## Finish the setup

Right after `smf create`, `POSTHOG_PROJECT_TOKEN` is empty, so the app records nothing in PostHog. The README of the app lists the step by hand in its section "Finish the setup", and the run ends with the link to its guide:

| Step | What you do |
| --- | --- |
| [`posthog.project_token`](https://doc.saymyframe.com/setup/posthog-project-token.md) | Create a PostHog project and copy its project token and its host into `.env`. |

## In tests

posthog_flutter has no mocks for tests, and on Linux and Windows `flutter test` registers a client of it in Dart, which writes to the disk and to the network. So the module keeps a stand-in for the platform side of the package, a device in memory, for the tests of every app with it. Its test checks, on the real posthog_flutter, the config of the start, the flavor, each call of the service as PostHog names it, the property of a user without an id, a change of the user, a sign-out while collection is off, and that without a token the start throws an error that names the key. In an app with a router, it checks that the first screen is recorded once, under the name of its route. On a device, SMF's CI checks that PostHog started exactly when the build has a token, and that it is opted out exactly when the app collects nothing from its first start. See [Contributing](https://doc.saymyframe.com/contributing.md#the-roles-at-run-time).

## Choosing it

`smf create` asks which modules provide the analytics of the app, and the answer may be any number of them, none included:

```text
Analytics: which module provides it?
  firebase_analytics — Firebase Analytics with firebase_analytics
  posthog — PostHog with posthog_flutter
```

With one, once the modules of the app are known, it asks whether the app collects analytics before the user agrees:

```text
Does the app collect analytics before the user agrees?
  Yes, from its first start
  No: only once your code turns it on, as after the user agrees
```

Enter takes the first answer. To choose this module and the answer without the questions, here an app that collects nothing until its code turns collection on:

```bash
smf create my_app -m posthog --analytics-collection=off
```

The module requires the values of `.env`, and `smf create` adds the only module that provides them:

```text
Adding flutter_core: the only provider of the app entry role, which every app needs.
Adding dart_define: the only provider of the env role, which posthog requires.
```
