From e3231baca39a1d28580ee36041d11956cdf5908f Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Wed, 4 Nov 2026 17:45:44 -0500 Subject: [PATCH 1/3] chore(feature-flags): snapshot the 3.x Android flag pages The Android flag variants install posthog-android 3.x, but read the live flag code page and the Android flag install page, which move to 4.0 on release day. They now read 2026-11-04 snapshots of both pages. The flag code page is a group shared doc, so a variant's own shared_docs entry now replaces the group's one with the same file name. Every other variant still reads it live. Co-Authored-By: Claude Opus 5.5 --- context/docs-snapshots/legacy/README.md | 8 + .../feature-flags/adding-feature-flag-code.md | 3188 +++++++++++++++++ .../legacy/feature-flags/android.md | 158 + context/skills/feature-flags/config.yaml | 4 +- .../feature-flags-step/config.yaml | 4 +- .../instrument-feature-flags/config.yaml | 2 +- scripts/lib/skill-generator.js | 15 +- scripts/lib/tests/doc-snapshots.test.js | 35 +- 8 files changed, 3409 insertions(+), 5 deletions(-) create mode 100644 context/docs-snapshots/legacy/feature-flags/adding-feature-flag-code.md create mode 100644 context/docs-snapshots/legacy/feature-flags/android.md diff --git a/context/docs-snapshots/legacy/README.md b/context/docs-snapshots/legacy/README.md index e295639e7..5a839159b 100644 --- a/context/docs-snapshots/legacy/README.md +++ b/context/docs-snapshots/legacy/README.md @@ -11,6 +11,12 @@ and the legacy variants must keep describing the majors they install. Refresh a copy only to pick up a fix to the legacy page itself, never from a page that already describes a v1 major. The v1 variants point at the live pages. +`feature-flags/` holds the two feature flag pages the Android variants read, +taken on 2026-11-04 while they still described posthog-android 3.x. The +`adding-feature-flag-code` page is a group `shared_docs` entry that every other +variant keeps reading live: a variant's own `shared_docs` entry replaces the +group's one with the same file name. + | File | Source | | --- | --- | | `python.md` | https://posthog.com/docs/libraries/python.md | @@ -26,3 +32,5 @@ page that already describes a v1 major. The v1 variants point at the live pages. | `flutter.md` | https://posthog.com/docs/libraries/flutter.md | | `django.md` | https://posthog.com/docs/libraries/django.md | | `flask.md` | https://posthog.com/docs/libraries/flask.md | +| `feature-flags/android.md` | https://posthog.com/docs/feature-flags/installation/android.md | +| `feature-flags/adding-feature-flag-code.md` | https://posthog.com/docs/feature-flags/adding-feature-flag-code.md | diff --git a/context/docs-snapshots/legacy/feature-flags/adding-feature-flag-code.md b/context/docs-snapshots/legacy/feature-flags/adding-feature-flag-code.md new file mode 100644 index 000000000..19f17ac7f --- /dev/null +++ b/context/docs-snapshots/legacy/feature-flags/adding-feature-flag-code.md @@ -0,0 +1,3188 @@ +> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt + +# Adding feature flag code + +Canonical URL: https://posthog.com/docs/feature-flags/adding-feature-flag-code + +> **Cloud region:** This page uses US Cloud hosts. For an EU Cloud project, use `https://eu.posthog.com` instead of `https://us.posthog.com` (app host for links). + +Once you've created your feature flag in PostHog, the next step is to add your code: + +## Web + +### Boolean feature flags + +```javascript +const result = posthog.getFeatureFlagResult('flag-key') +if (result?.enabled) { + // Do something differently for this user + + // Optional: fetch the payload from the same evaluation result + const matchedFlagPayload = result?.payload +} +``` + +### Multivariate feature flags + +```javascript +const result = posthog.getFeatureFlagResult('flag-key') +if (result?.variant == 'variant-key') { // replace 'variant-key' with the key of your variant + // Do something differently for this user + + // Optional: fetch the payload from the same evaluation result + const matchedFlagPayload = result?.payload +} +``` + +### Inspecting all feature flags + +You can inspect all currently loaded feature flags with `getAllFeatureFlags()`. It returns each flag's `key`, `enabled` state, `variant`, and `payload`, and does not send a `$feature_flag_called` event, so calling it won't affect your experiment results or flag usage analytics: + +```javascript +for (const flag of posthog.getAllFeatureFlags()) { + console.log(flag.key, flag.enabled, flag.variant, flag.payload) +} +``` + +### Ensuring flags are loaded before usage + +Every time a user loads a page, we send a request in the background to fetch the feature flags that apply to that user. We store those flags in your chosen persistence option (local storage by default). + +This means that for most pages, the feature flags are available immediately — **except for the first time a user visits**. + +To handle this, you can use the `onFeatureFlags` callback to wait for the feature flag request to finish: + +```javascript +posthog.onFeatureFlags(function (flags, flagVariants, { errorsLoading }) { + // feature flags are guaranteed to be available at this point + if (posthog.isFeatureEnabled('flag-key')) { + // do something + } +}) +``` + +#### Callback parameters + +The `onFeatureFlags` callback receives the following parameters: + +- `flags: string[]`: An object containing the feature flags that apply to the user. + +- `flagVariants: Record`: An object containing the variants that apply to the user. + +- `{ errorsLoading }: { errorsLoading?: boolean }`: An object containing a boolean indicating if an error occurred during the request to load the feature flags. This is `true` if the request timed out or if there was an error. It will be `false` or `undefined` if the request was successful. + +You won't usually need to use these, but they are useful if you want to be extra careful about feature flags not being loaded yet because of a network error and/or a network timeout (see `feature_flag_request_timeout_ms`). + +### Evaluating only specific flags + +By default, the JavaScript SDK requests that every eligible feature flag be evaluated for the current user. If you'd only like to evaluate and return a subset of flags, pass `flag_keys` when initializing PostHog: + +```javascript +posthog.init('', { + api_host: 'https://us.i.posthog.com', + defaults: '2026-08-30', + flag_keys: ['checkout-flow', 'new-dashboard'], +}) +``` + +PostHog scopes evaluation and the response to those keys for this SDK instance. Dependency flags required to evaluate requested flags may also be evaluated and returned. Leave `flag_keys` unset to evaluate all eligible flags. + +### Reloading feature flags + +Feature flag values are cached. If something has changed with your user and you'd like to refetch their flag values, call: + +```javascript +posthog.reloadFeatureFlags() +``` + +### Overriding server properties + +Sometimes, you might want to evaluate feature flags using properties that haven't been ingested yet, or were set incorrectly earlier. You can do so by setting properties the flag depends on with these calls: + +```javascript +posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'}) +``` + +> **Note:** These are set for the entire session. Successive calls are additive: all properties you set are combined together and sent for flag evaluation. + +Whenever you set these properties, we also trigger a reload of feature flags to ensure we have the latest values. You can disable this by passing in the optional parameter for reloading: + +```javascript +posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'}, false) +``` + +At any point, you can reset these properties by calling `resetPersonPropertiesForFlags`: + +```javascript +posthog.resetPersonPropertiesForFlags() +``` + +The same holds for [group](https://posthog.com/manual/group-analytics.md) properties: + +```javascript +// set properties for a group +posthog.setGroupPropertiesForFlags({'company': {'property1': 'value', property2: 'value2'}}) + +// reset properties for a given group: +posthog.resetGroupPropertiesForFlags('company') + +// reset properties for all groups: +posthog.resetGroupPropertiesForFlags() +``` + +> **Note:** You don't need to add the group names here, since these properties are automatically attached to the current group (set via `posthog.group()`). When you change the group, these properties are reset. + +#### Automatic overrides + +Whenever you call `posthog.identify` with person properties, we automatically add these properties to flag evaluation calls to help determine the correct flag values. The same is true for when you call `posthog.group()`. + +#### Default overridden properties + +By default, we always override some properties based on the user IP address. + +The list of properties that this overrides: + +1. `$geoip_city_name` +2. `$geoip_country_name` +3. `$geoip_country_code` +4. `$geoip_continent_name` +5. `$geoip_continent_code` +6. `$geoip_postal_code` +7. `$geoip_time_zone` + +This enables any geolocation-based flags to work without manually setting these properties. + +### Request timeout + +You can configure the `feature_flag_request_timeout_ms` parameter when initializing your PostHog client to set a flag request timeout. This helps prevent your code from being blocked in the case when PostHog's servers are too slow to respond. By default, this is set at 3 seconds. + +```javascript +posthog.init('', { + api_host: 'https://us.i.posthog.com', + defaults: '2026-08-30', + feature_flag_request_timeout_ms: 3000 // Time in milliseconds. Default is 3000 (3 seconds). +}) +``` + +### Feature flag error handling + +When using the PostHog SDK, it's important to handle potential errors that may occur during feature flag operations. Here's an example of how to wrap PostHog SDK methods in an error handler: + +```javascript +function handleFeatureFlag(client, flagKey, distinctId) { + try { + const isEnabled = client.isFeatureEnabled(flagKey, distinctId); + console.log(`Feature flag '${flagKey}' for user '${distinctId}' is ${isEnabled ? 'enabled' : 'disabled'}`); + return isEnabled; + } catch (error) { + console.error(`Error fetching feature flag '${flagKey}': ${error.message}`); + // Optionally, you can return a default value or throw the error + // return false; // Default to disabled + throw error; + } +} + +// Usage example +try { + const flagEnabled = handleFeatureFlag(client, 'new-feature', 'user-123'); + if (flagEnabled) { + // Implement new feature logic + } else { + // Implement old feature logic + } +} catch (error) { + // Handle the error at a higher level + console.error('Feature flag check failed, using default behavior'); + // Implement fallback logic +} +``` + +## React + +There are two ways to implement feature flags in React: + +1. Using hooks. +2. Using the `` component. + +### Method 1: Using hooks + +PostHog provides several hooks to make it easy to use feature flags in your React app. + +| Hook | Description | +| --- | --- | +| `useFeatureFlagEnabled` | Returns whether the feature flag is enabled. This sends a `$feature_flag_called` event. Without a default value, it returns `boolean \| undefined` while flags are loading or absent. Pass an optional default value to return that value instead and narrow the return type to `boolean`. | +| `useFeatureFlagVariantKey` | Returns the variant key of the feature flag. This sends a `$feature_flag_called` event. | +| `useActiveFeatureFlags` | Returns an array of active feature flags. This does *not* send a `$feature_flag_called` event. | +| `useFeatureFlagPayload` | Returns the payload of the feature flag. This does *not* send a `$feature_flag_called` event. Always use this with `useFeatureFlagEnabled` or `useFeatureFlagVariantKey`. | + +#### Example 1: Using a boolean feature flag + +```jsx +import { useFeatureFlagEnabled, useFeatureFlagPayload } from '@posthog/react' + +function App() { + const showWelcomeMessage = useFeatureFlagEnabled('flag-key') + const payload = useFeatureFlagPayload('flag-key') + + return ( +
+ { + showWelcomeMessage ? ( +
+

Welcome!

+

Thanks for trying out our feature flags.

+
+ ) : ( +
+

No welcome message

+

Because the feature flag evaluated to false.

+
+ ) + } +
+ ); +} + +export default App; +``` + +To avoid handling `undefined` while flags are loading, pass a default value as the second argument: + +```jsx +const showWelcomeMessage = useFeatureFlagEnabled('flag-key', false) +``` + +#### Example 2: Using a multivariate feature flag + +```jsx +import { useFeatureFlagVariantKey } from '@posthog/react' + +function App() { + const variantKey = useFeatureFlagVariantKey('show-welcome-message') + let welcomeMessage = '' + if (variantKey === 'variant-a') { + welcomeMessage = 'Welcome to the Alpha!' + } else if (variantKey === 'variant-b') { + welcomeMessage = 'Welcome to the Beta!' + } + + return ( +
+ { + welcomeMessage ? ( +
+

{welcomeMessage}

+

Thanks for trying out our feature flags.

+
+ ) : ( +
+

No welcome message

+

Because the feature flag evaluated to false.

+
+ ) + } +
+ ); +} + +export default App; +``` + +#### Example 3: Using a flag payload + +**Payload hook** + +The `useFeatureFlagPayload` hook does *not* send a [`$feature_flag_called`](https://posthog.com/docs/experiments/new-experimentation-engine#experiment-exposure) event, which is required for the experiment to be tracked. To ensure the exposure event is sent, you should **always** use the `useFeatureFlagPayload` hook with either the `useFeatureFlagEnabled` or `useFeatureFlagVariantKey` hook. + +```jsx +import { useFeatureFlagEnabled, useFeatureFlagPayload } from '@posthog/react' + +function App() { + const variant = useFeatureFlagEnabled('show-welcome-message') + const payload = useFeatureFlagPayload('show-welcome-message') + + return ( + <> + { + variant ? ( +
+

{payload?.welcomeTitle}

+

{payload?.welcomeMessage}

+
+ ) :
+

No custom welcome message

+

Because the feature flag evaluated to false.

+
+ } + + ) +} +``` + +### Method 2: Using the PostHogFeature component + +The `PostHogFeature` component simplifies code by handling feature flag related logic. + +It also automatically captures metrics, like how many times a user interacts with this feature. + +> **Note:** You still need the [`PostHogProvider`](https://posthog.com/docs/libraries/react.md#installation) at the top level for this to work. + +Here is an example: + +```jsx +import { PostHogFeature } from '@posthog/react' + +function App() { + + return ( + +
+

Hello

+

Thanks for trying out our feature flags.

+
+
+ ) +} +``` + +- The `match` on the component can be either `true`, or the variant key, to match on a specific variant. + +- If you also want to show a default message, you can pass these in the `fallback` attribute. + +If you wish to customise logic around when the component is considered visible, you can pass in `visibilityObserverOptions` to the feature. These take the same options as the [IntersectionObserver API](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API). By default, we use a threshold of 0.1. + +#### Payloads + +If your flag has a payload, you can pass a function to children whose first argument is the payload. For example: + +```jsx +import { PostHogFeature } from '@posthog/react' + +function App() { + + return ( + + {(payload) => { + return ( +
+

{payload.welcomeMessage}

+

Thanks for trying out our feature flags.

+
+ ) + }} +
+ ) +} +``` + +### Request timeout + +You can configure the `feature_flag_request_timeout_ms` parameter when initializing your PostHog client to set a flag request timeout. This helps prevent your code from being blocked in the case when PostHog's servers are too slow to respond. By default, this is set at 3 seconds. + +```javascript +posthog.init('', { + api_host: 'https://us.i.posthog.com', + defaults: '2026-08-30', + feature_flag_request_timeout_ms: 3000 // Time in milliseconds. Default is 3000 (3 seconds). +} +) +``` + +### Error handling + +When using the PostHog SDK, it's important to handle potential errors that may occur during feature flag operations. Here's an example of how to wrap PostHog SDK methods in an error handler: + +```javascript +function handleFeatureFlag(client, flagKey, distinctId) { + try { + const isEnabled = client.isFeatureEnabled(flagKey, distinctId); + console.log(`Feature flag '${flagKey}' for user '${distinctId}' is ${isEnabled ? 'enabled' : 'disabled'}`); + return isEnabled; + } catch (error) { + console.error(`Error fetching feature flag '${flagKey}': ${error.message}`); + // Optionally, you can return a default value or throw the error + // return false; // Default to disabled + throw error; + } +} + +// Usage example +try { + const flagEnabled = handleFeatureFlag(client, 'new-feature', 'user-123'); + if (flagEnabled) { + // Implement new feature logic + } else { + // Implement old feature logic + } +} catch (error) { + // Handle the error at a higher level + console.error('Feature flag check failed, using default behavior'); + // Implement fallback logic +} +``` + +## Node.js + +There are two steps to implement feature flags in Node: + +### Step 1: Evaluate flags once + +Call `client.evaluateFlags()` once for the user, then read values from the returned snapshot. + +#### Boolean feature flags + +```javascript +const flags = await client.evaluateFlags('distinct_id_of_your_user') + +if (flags.isEnabled('flag-key')) { + // Do something differently for this user + // Optional: fetch the payload + const matchedFlagPayload = flags.getFlagPayload('flag-key') +} +``` + +#### Multivariate feature flags + +```javascript +const flags = await client.evaluateFlags('distinct_id_of_your_user') +const enabledVariant = flags.getFlag('flag-key') + +if (enabledVariant === 'variant-key') { // replace 'variant-key' with the key of your variant + // Do something differently for this user + // Optional: fetch the payload + const matchedFlagPayload = flags.getFlagPayload('flag-key') +} +``` + +`flags.getFlag()` returns the variant string for multivariate flags, `true` for enabled boolean flags, `false` for disabled flags, and `undefined` when the flag wasn't returned by the evaluation. + +> **Note:** `client.isFeatureEnabled()`, `client.getFeatureFlag()`, `client.getFeatureFlagPayload()`, and `capture({ sendFeatureFlags: true })` still work during the migration period, but they're deprecated. Prefer `evaluateFlags()` for new code. + +### Step 2: Include feature flag information when capturing events + +If you want use your feature flag to breakdown or filter events in your [insights](https://posthog.com/docs/product-analytics/insights.md), you'll need to include feature flag information in those events. This ensures that the feature flag value is attributed correctly to the event. + +> **Note:** This step is only required for events captured using our server-side SDKs or [API](https://posthog.com/docs/api.md). + +There are two methods you can use to include feature flag information in your events: + +#### Method 1: Pass the evaluated flags snapshot to `capture()` + +Pass the same `flags` object that you used for branching. This attaches the exact flag values from that evaluation and doesn't make another `/flags` request. + +```javascript +const flags = await client.evaluateFlags('distinct_id_of_your_user') + +if (flags.isEnabled('flag-key')) { + // Do something differently for this user +} + +client.capture({ + distinctId: 'distinct_id_of_your_user', + event: 'event_name', + flags, +}) +``` + +By default, this attaches every flag in the snapshot using `$feature/` properties and `$active_feature_flags`. + +To reduce event property bloat, pass a filtered snapshot: + +```javascript +// Attach only flags accessed with isEnabled() or getFlag() before this call +client.capture({ + distinctId: 'distinct_id_of_your_user', + event: 'event_name', + flags: flags.onlyAccessed(), +}) + +// Attach only specific flags +client.capture({ + distinctId: 'distinct_id_of_your_user', + event: 'event_name', + flags: flags.only(['checkout-flow', 'new-dashboard']), +}) +``` + +`onlyAccessed()` is order-dependent. If you call it before accessing any flags with `isEnabled()` or `getFlag()`, no feature flag properties are attached. + +#### Method 2: Include the `$feature/feature_flag_name` property manually + +In the event properties, include `$feature/feature_flag_name: variant_key`: + +```javascript +client.capture({ + distinctId: 'distinct_id_of_your_user', + event: 'event_name', + properties: { + // Replace feature-flag-key with your flag key and 'variant-key' with the key of your variant + '$feature/feature-flag-key': 'variant-key', + }, +}) +``` + +### Evaluating only specific flags + +By default, `evaluateFlags()` evaluates every flag for the user. If you only need a few flags, pass `flagKeys` to request only those flags: + +```javascript +const flags = await client.evaluateFlags('distinct_id_of_your_user', { + flagKeys: ['checkout-flow', 'new-dashboard'], +}) +``` + +### Sending `$feature_flag_called` events + +Capturing `$feature_flag_called` events enables PostHog to know when a flag was accessed by a user and provide [analytics and insights](https://posthog.com/docs/product-analytics/insights.md) on the flag. With `evaluateFlags()`, the SDK sends this event when you call `flags.isEnabled()` or `flags.getFlag()` for a flag. + +The SDK deduplicates these events per `(distinct_id, flag, value)` in a local cache. If you reinitialize the PostHog client, the cache resets and `$feature_flag_called` events may be sent again. PostHog handles duplicates, so duplicate `$feature_flag_called` events don't affect your analytics. + +`flags.getFlagPayload()` doesn't send `$feature_flag_called` events and doesn't count as an access for `onlyAccessed()`. + +### Advanced: Overriding server properties + +Sometimes, you may want to evaluate feature flags using [person properties](https://posthog.com/docs/product-analytics/person-properties.md), [groups](https://posthog.com/docs/product-analytics/group-analytics.md), or group properties that haven't been ingested yet, or were set incorrectly earlier. + +You can provide properties to evaluate the flag with by using the `person properties`, `groups`, and `group properties` arguments. PostHog will then use these values to evaluate the flag, instead of any properties currently stored on your PostHog server. + +For example: + +```javascript +const flags = await client.evaluateFlags('distinct_id_of_the_user', { + personProperties: { + property_name: 'value', + }, + groups: { + your_group_type: 'your_group_id', + another_group_type: 'your_group_id', + }, + groupProperties: { + your_group_type: { + group_property_name: 'value', + }, + another_group_type: { + group_property_name: 'value', + }, + }, +}) + +if (flags.isEnabled('flag-key')) { + // Do something differently for this user +} +``` + +### Overriding GeoIP properties + +By default, a user's GeoIP properties are set using the IP address they use to capture events on the frontend. You may want to override the these properties when evaluating feature flags. A common reason to do this is when you're not using PostHog on your frontend, so the user has no GeoIP properties. + +You can override GeoIP properties by including them in the `person_properties` parameter when evaluating feature flags. This is useful when you're evaluating flags on your backend and want to use the client's location instead of your server's location. + +The following GeoIP properties can be overridden: + +- `$geoip_country_code` +- `$geoip_country_name` +- `$geoip_city_name` +- `$geoip_city_confidence` +- `$geoip_continent_code` +- `$geoip_continent_name` +- `$geoip_latitude` +- `$geoip_longitude` +- `$geoip_postal_code` +- `$geoip_subdivision_1_code` +- `$geoip_subdivision_1_name` +- `$geoip_subdivision_2_code` +- `$geoip_subdivision_2_name` +- `$geoip_subdivision_3_code` +- `$geoip_subdivision_3_name` +- `$geoip_time_zone` + +Simply include any of these properties in the `person_properties` parameter alongside your other person properties when calling feature flags. + +### Request timeout + +You can configure the `featureFlagsRequestTimeoutMs` parameter when initializing your PostHog client to set a flag request timeout. This helps prevent your code from being blocked if PostHog's servers are too slow to respond. By default, this is set to 3 seconds. + +```javascript +const client = new PostHog('', { + host: 'https://us.i.posthog.com', + featureFlagsRequestTimeoutMs: 3000, // Time in milliseconds. Defaults to 3000 (3 seconds). +}) +``` + +## Python + +There are two steps to implement feature flags in Python: + +### Step 1: Evaluate flags once + +Call `posthog.evaluate_flags()` once for the user, then read values from the returned snapshot. + +#### Boolean feature flags + +```python +flags = posthog.evaluate_flags("distinct_id_of_your_user") + +if flags.is_enabled("flag-key"): + # Do something differently for this user + # Optional: fetch the payload + matched_flag_payload = flags.get_flag_payload("flag-key") +``` + +#### Multivariate feature flags + +```python +flags = posthog.evaluate_flags("distinct_id_of_your_user") + +enabled_variant = flags.get_flag("flag-key") + +if enabled_variant == "variant-key": # replace "variant-key" with the key of your variant + # Do something differently for this user + # Optional: fetch the payload + matched_flag_payload = flags.get_flag_payload("flag-key") +``` + +`flags.get_flag()` returns the variant string for multivariate flags, `True` for enabled boolean flags, `False` for disabled flags, and `None` when the flag wasn't returned by the evaluation. + +> **Note:** `posthog.feature_enabled()`, `posthog.get_feature_flag()`, `posthog.get_feature_flag_payload()`, and `posthog.capture(send_feature_flags=True)` still work during the migration period, but they're deprecated. Prefer `posthog.evaluate_flags()` for new code. + +### Step 2: Include feature flag information when capturing events + +If you want use your feature flag to breakdown or filter events in your [insights](https://posthog.com/docs/product-analytics/insights.md), you'll need to include feature flag information in those events. This ensures that the feature flag value is attributed correctly to the event. + +> **Note:** This step is only required for events captured using our server-side SDKs or [API](https://posthog.com/docs/api.md). + +There are two methods you can use to include feature flag information in your events: + +#### Method 1: Pass the evaluated flags snapshot to `capture()` + +Pass the same `flags` object that you used for branching. This attaches the exact flag values from that evaluation and doesn't make another `/flags` request. + +```python +flags = posthog.evaluate_flags("distinct_id_of_your_user") + +if flags.is_enabled("flag-key"): + # Do something differently for this user + pass + +posthog.capture( + "event_name", + distinct_id="distinct_id_of_your_user", + flags=flags, +) +``` + +By default, this attaches every flag in the snapshot using `$feature/` properties and `$active_feature_flags`. + +To reduce event property bloat, pass a filtered snapshot: + +```python +# Attach only flags accessed with is_enabled() or get_flag() before this call +posthog.capture( + "event_name", + distinct_id="distinct_id_of_your_user", + flags=flags.only_accessed(), +) + +# Attach only specific flags +posthog.capture( + "event_name", + distinct_id="distinct_id_of_your_user", + flags=flags.only(["checkout-flow", "new-dashboard"]), +) +``` + +`only_accessed()` is order-dependent. If you call it before accessing any flags with `is_enabled()` or `get_flag()`, no feature flag properties are attached. + +#### Method 2: Include the `$feature/feature_flag_name` property manually + +In the event properties, include `$feature/feature_flag_name: variant_key`: + +```python +posthog.capture( + "event_name", + distinct_id="distinct_id_of_the_user", + properties={ + # Replace feature-flag-key with your flag key and "variant-key" with the key of your variant + "$feature/feature-flag-key": "variant-key", + }, +) +``` + +### Evaluating only specific flags + +By default, `posthog.evaluate_flags()` evaluates every flag for the user. If you only need a few flags, pass `flag_keys` to request only those flags: + +```python +flags = posthog.evaluate_flags( + "distinct_id_of_your_user", + flag_keys=["checkout-flow", "new-dashboard"], +) +``` + +### Sending `$feature_flag_called` events + +Capturing `$feature_flag_called` events enables PostHog to know when a flag was accessed by a user and provide [analytics and insights](https://posthog.com/docs/product-analytics/insights.md) on the flag. With `posthog.evaluate_flags()`, the SDK sends this event when you call `flags.is_enabled()` or `flags.get_flag()` for a flag. + +The SDK deduplicates these events per `(distinct_id, flag, value)` in a local cache. If you reinitialize the PostHog client, the cache resets and `$feature_flag_called` events may be sent again. PostHog handles duplicates, so duplicate `$feature_flag_called` events don't affect your analytics. + +`flags.get_flag_payload()` doesn't send `$feature_flag_called` events and doesn't count as an access for `only_accessed()`. + +### Advanced: Overriding server properties + +Sometimes, you may want to evaluate feature flags using [person properties](https://posthog.com/docs/product-analytics/person-properties.md), [groups](https://posthog.com/docs/product-analytics/group-analytics.md), or group properties that haven't been ingested yet, or were set incorrectly earlier. + +You can provide properties to evaluate the flag with by using the `person properties`, `groups`, and `group properties` arguments. PostHog will then use these values to evaluate the flag, instead of any properties currently stored on your PostHog server. + +For example: + +```python +flags = posthog.evaluate_flags( + "distinct_id_of_the_user", + person_properties={"property_name": "value"}, + groups={ + "your_group_type": "your_group_id", + "another_group_type": "your_group_id", + }, + group_properties={ + "your_group_type": {"group_property_name": "value"}, + "another_group_type": {"group_property_name": "value"}, + }, +) + +if flags.is_enabled("flag-key"): + # Do something differently for this user +``` + +### Overriding GeoIP properties + +By default, a user's GeoIP properties are set using the IP address they use to capture events on the frontend. You may want to override the these properties when evaluating feature flags. A common reason to do this is when you're not using PostHog on your frontend, so the user has no GeoIP properties. + +You can override GeoIP properties by including them in the `person_properties` parameter when evaluating feature flags. This is useful when you're evaluating flags on your backend and want to use the client's location instead of your server's location. + +The following GeoIP properties can be overridden: + +- `$geoip_country_code` +- `$geoip_country_name` +- `$geoip_city_name` +- `$geoip_city_confidence` +- `$geoip_continent_code` +- `$geoip_continent_name` +- `$geoip_latitude` +- `$geoip_longitude` +- `$geoip_postal_code` +- `$geoip_subdivision_1_code` +- `$geoip_subdivision_1_name` +- `$geoip_subdivision_2_code` +- `$geoip_subdivision_2_name` +- `$geoip_subdivision_3_code` +- `$geoip_subdivision_3_name` +- `$geoip_time_zone` + +Simply include any of these properties in the `person_properties` parameter alongside your other person properties when calling feature flags. + +### Request timeout + +You can configure the `feature_flags_request_timeout_seconds` parameter when initializing your PostHog client to set a flag request timeout. This helps prevent your code from being blocked if PostHog's servers are too slow to respond. By default, this is set to 3 seconds. + +```python +posthog = Posthog( + "", + host="https://us.i.posthog.com", + feature_flags_request_timeout_seconds=3, # Time in seconds. Defaults to 3. +) +``` + +## PHP + +There are two steps to implement feature flags in PHP: + +### Step 1: Evaluate flags once + +Call `PostHog::evaluateFlags()` once for the user, then read values from the returned snapshot. + +#### Boolean feature flags + +```php +$flags = PostHog::evaluateFlags('distinct_id_of_your_user'); + +if ($flags->isEnabled('flag-key')) { + // Do something differently for this user + // Optional: fetch the payload + $matchedFlagPayload = $flags->getFlagPayload('flag-key'); +} +``` + +#### Multivariate feature flags + +```php +$flags = PostHog::evaluateFlags('distinct_id_of_your_user'); + +$enabledVariant = $flags->getFlag('flag-key'); + +if ($enabledVariant === 'variant-key') { // replace 'variant-key' with the key of your variant + // Do something differently for this user + // Optional: fetch the payload + $matchedFlagPayload = $flags->getFlagPayload('flag-key'); +} +``` + +`$flags->getFlag()` returns the variant string for multivariate flags, `true` for enabled boolean flags, `false` for disabled flags, and `null` when the flag wasn't returned by the evaluation. + +You can also call `$flags->getKeys()` to list the evaluated flag keys, or `$flags->getEventProperties()` to get the `$feature/` and `$active_feature_flags` properties that would be attached to a captured event. + +> **Note:** `PostHog::isFeatureEnabled()`, `PostHog::getFeatureFlag()`, `PostHog::getFeatureFlagPayload()`, and `capture(['send_feature_flags' => true])` still work during the migration period, but they're deprecated. Prefer `evaluateFlags()` for new code. + +### Step 2: Include feature flag information when capturing events + +If you want use your feature flag to breakdown or filter events in your [insights](https://posthog.com/docs/product-analytics/insights.md), you'll need to include feature flag information in those events. This ensures that the feature flag value is attributed correctly to the event. + +> **Note:** This step is only required for events captured using our server-side SDKs or [API](https://posthog.com/docs/api.md). + +There are two methods you can use to include feature flag information in your events: + +#### Method 1: Pass the evaluated flags snapshot to `capture()` + +Pass the same `flags` object that you used for branching. This attaches the exact flag values from that evaluation and doesn't make another `/flags` request. + +```php +$flags = PostHog::evaluateFlags('distinct_id_of_your_user'); + +if ($flags->isEnabled('flag-key')) { + // Do something differently for this user +} + +PostHog::capture([ + 'distinctId' => 'distinct_id_of_your_user', + 'event' => 'event_name', + 'flags' => $flags, +]); +``` + +By default, this attaches every flag in the snapshot using `$feature/` properties and `$active_feature_flags`. + +To reduce event property bloat, pass a filtered snapshot: + +```php +// Attach only flags accessed with isEnabled() or getFlag() before this call +PostHog::capture([ + 'distinctId' => 'distinct_id_of_your_user', + 'event' => 'event_name', + 'flags' => $flags->onlyAccessed(), +]); + +// Attach only specific flags +PostHog::capture([ + 'distinctId' => 'distinct_id_of_your_user', + 'event' => 'event_name', + 'flags' => $flags->only(['checkout-flow', 'new-dashboard']), +]); +``` + +`onlyAccessed()` is order-dependent. If you call it before accessing any flags with `isEnabled()` or `getFlag()`, no feature flag properties are attached. + +#### Method 2: Include the `$feature/feature_flag_name` property manually + +In the event properties, include `$feature/feature_flag_name: variant_key`: + +```php +PostHog::capture([ + 'distinctId' => 'distinct_id_of_your_user', + 'event' => 'event_name', + 'properties' => [ + // Replace feature-flag-key with your flag key and 'variant-key' with the key of your variant + '$feature/feature-flag-key' => 'variant-key', + ], +]); +``` + +### Evaluating only specific flags + +By default, `evaluateFlags()` evaluates every flag for the user. If you only need a few flags, pass `flagKeys` to request only those flags: + +```php +$flags = PostHog::evaluateFlags( + distinctId: 'distinct_id_of_your_user', + flagKeys: ['checkout-flow', 'new-dashboard'], +); +``` + +### Optional evaluation parameters + +`evaluateFlags()` also accepts optional parameters for local evaluation and GeoIP behavior: + +```php +$flags = PostHog::evaluateFlags( + distinctId: 'distinct_id_of_your_user', + groups: ['company' => 'company_id_in_your_db'], + personProperties: ['plan' => 'pro'], + groupProperties: ['company' => ['employees' => 11]], + onlyEvaluateLocally: false, // Defaults to false. Set to true to avoid a remote fallback. + disableGeoip: false, // Defaults to false. Set to true to disable GeoIP enrichment during remote evaluation. + flagKeys: ['checkout-flow', 'new-dashboard'], +); +``` + +### Sending `$feature_flag_called` events + +Capturing `$feature_flag_called` events enables PostHog to know when a flag was accessed by a user and provide [analytics and insights](https://posthog.com/docs/product-analytics/insights.md) on the flag. With `evaluateFlags()`, the SDK sends this event when you call `$flags->isEnabled()` or `$flags->getFlag()` for a flag. + +The SDK deduplicates these events per `(flag key, distinct_id)` in a local cache. If you reinitialize the PostHog client, the cache resets and `$feature_flag_called` events may be sent again. PostHog handles duplicates, so duplicate `$feature_flag_called` events don't affect your analytics. + +`$flags->getFlagPayload()` doesn't send `$feature_flag_called` events and doesn't count as an access for `onlyAccessed()`. + +### Advanced: Overriding server properties + +Sometimes, you may want to evaluate feature flags using [person properties](https://posthog.com/docs/product-analytics/person-properties.md), [groups](https://posthog.com/docs/product-analytics/group-analytics.md), or group properties that haven't been ingested yet, or were set incorrectly earlier. + +You can provide properties to evaluate the flag with by using the `person properties`, `groups`, and `group properties` arguments. PostHog will then use these values to evaluate the flag, instead of any properties currently stored on your PostHog server. + +For example: + +```php +$flags = PostHog::evaluateFlags( + distinctId: 'distinct_id_of_the_user', + groups: [ + 'your_group_type' => 'your_group_id', + 'another_group_type' => 'your_group_id', + ], + personProperties: ['property_name' => 'value'], + groupProperties: [ + 'your_group_type' => ['group_property_name' => 'value'], + 'another_group_type' => ['group_property_name' => 'value'], + ], +); + +if ($flags->isEnabled('flag-key')) { + // Do something differently for this user +} +``` + +### Overriding GeoIP properties + +By default, a user's GeoIP properties are set using the IP address they use to capture events on the frontend. You may want to override the these properties when evaluating feature flags. A common reason to do this is when you're not using PostHog on your frontend, so the user has no GeoIP properties. + +You can override GeoIP properties by including them in the `person_properties` parameter when evaluating feature flags. This is useful when you're evaluating flags on your backend and want to use the client's location instead of your server's location. + +The following GeoIP properties can be overridden: + +- `$geoip_country_code` +- `$geoip_country_name` +- `$geoip_city_name` +- `$geoip_city_confidence` +- `$geoip_continent_code` +- `$geoip_continent_name` +- `$geoip_latitude` +- `$geoip_longitude` +- `$geoip_postal_code` +- `$geoip_subdivision_1_code` +- `$geoip_subdivision_1_name` +- `$geoip_subdivision_2_code` +- `$geoip_subdivision_2_name` +- `$geoip_subdivision_3_code` +- `$geoip_subdivision_3_name` +- `$geoip_time_zone` + +Simply include any of these properties in the `person_properties` parameter alongside your other person properties when calling feature flags. + +### Request timeout + +You can configure the `feature_flag_request_timeout_ms` parameter when initializing your PostHog client to set a flag request timeout. This helps prevent your code from being blocked if PostHog's servers are too slow to respond. By default, this is set to 3 seconds. + +```php +PostHog::init("", + [ + 'host' => 'https://us.i.posthog.com', + 'feature_flag_request_timeout_ms' => 3000, // Time in milliseconds. Defaults to 3000 (3 seconds). + ] +); +``` + +## Ruby + +There are two steps to implement feature flags in Ruby: + +### Step 1: Evaluate flags once + +Call `posthog.evaluate_flags()` once for the user, then read values from the returned snapshot. + +#### Boolean feature flags + +```ruby +flags = posthog.evaluate_flags('distinct_id_of_your_user') + +if flags.enabled?('flag-key') + # Do something differently for this user + # Optional: fetch the payload + matched_flag_payload = flags.get_flag_payload('flag-key') +end +``` + +#### Multivariate feature flags + +```ruby +flags = posthog.evaluate_flags('distinct_id_of_your_user') + +enabled_variant = flags.get_flag('flag-key') + +if enabled_variant == 'variant-key' # replace 'variant-key' with the key of your variant + # Do something differently for this user + # Optional: fetch the payload + matched_flag_payload = flags.get_flag_payload('flag-key') +end +``` + +`flags.get_flag()` returns the variant string for multivariate flags, `true` for enabled boolean flags, `false` for disabled flags, and `nil` when the flag wasn't returned by the evaluation. + +> **Note:** `posthog.is_feature_enabled()`, `posthog.get_feature_flag()`, `posthog.get_feature_flag_result()`, `posthog.get_feature_flag_payload()`, and `capture({ ..., send_feature_flags: true })` still work during the migration period, but they're deprecated. Prefer `evaluate_flags()` for new code. + +### Step 2: Include feature flag information when capturing events + +If you want use your feature flag to breakdown or filter events in your [insights](https://posthog.com/docs/product-analytics/insights.md), you'll need to include feature flag information in those events. This ensures that the feature flag value is attributed correctly to the event. + +> **Note:** This step is only required for events captured using our server-side SDKs or [API](https://posthog.com/docs/api.md). + +There are two methods you can use to include feature flag information in your events: + +#### Method 1: Pass the evaluated flags snapshot to `capture()` + +Pass the same `flags` object that you used for branching. This attaches the exact flag values from that evaluation and doesn't make another `/flags` request. + +```ruby +flags = posthog.evaluate_flags('distinct_id_of_your_user') + +if flags.enabled?('flag-key') + # Do something differently for this user +end + +posthog.capture({ + distinct_id: 'distinct_id_of_your_user', + event: 'event_name', + flags: flags, +}) +``` + +By default, this attaches every flag in the snapshot using `$feature/` properties and `$active_feature_flags`. + +To reduce event property bloat, pass a filtered snapshot: + +```ruby +# Attach only flags accessed with enabled?() or get_flag() before this call +posthog.capture({ + distinct_id: 'distinct_id_of_your_user', + event: 'event_name', + flags: flags.only_accessed, +}) + +# Attach only specific flags +posthog.capture({ + distinct_id: 'distinct_id_of_your_user', + event: 'event_name', + flags: flags.only(['checkout-flow', 'new-dashboard']), +}) +``` + +`only_accessed` is order-dependent. If you call it before accessing any flags with `enabled?()` or `get_flag()`, no feature flag properties are attached. + +#### Method 2: Include the `$feature/feature_flag_name` property manually + +In the event properties, include `$feature/feature_flag_name: variant_key`: + +```ruby +posthog.capture({ + distinct_id: 'distinct_id_of_your_user', + event: 'event_name', + properties: { + # Replace feature-flag-key with your flag key and 'variant-key' with the key of your variant + '$feature/feature-flag-key': 'variant-key', + }, +}) +``` + +### Evaluating only specific flags + +By default, `evaluate_flags()` evaluates every flag for the user. If you only need a few flags, pass `flag_keys` to request only those flags: + +```ruby +flags = posthog.evaluate_flags( + 'distinct_id_of_your_user', + flag_keys: ['checkout-flow', 'new-dashboard'], +) +``` + +### Evaluating locally only + +If you want to skip the remote `/flags` request and only use locally cached definitions, pass `only_evaluate_locally: true`: + +```ruby +flags = posthog.evaluate_flags( + 'distinct_id_of_your_user', + only_evaluate_locally: true, +) +``` + +### Disabling GeoIP for flag evaluation + +Pass `disable_geoip: true` to disable GeoIP lookup for remote flag evaluation: + +```ruby +flags = posthog.evaluate_flags( + 'distinct_id_of_your_user', + disable_geoip: true, +) +``` + +### Sending `$feature_flag_called` events + +Capturing `$feature_flag_called` events enables PostHog to know when a flag was accessed by a user and provide [analytics and insights](https://posthog.com/docs/product-analytics/insights.md) on the flag. With `evaluate_flags()`, the SDK sends this event when you call `flags.enabled?()` or `flags.get_flag()` for a flag. + +The SDK deduplicates these events per `(distinct_id, flag, value)` in a local cache. If you reinitialize the PostHog client, the cache resets and `$feature_flag_called` events may be sent again. PostHog handles duplicates, so duplicate `$feature_flag_called` events don't affect your analytics. + +`flags.get_flag_payload()` doesn't send `$feature_flag_called` events and doesn't count as an access for `only_accessed`. + +### Advanced: Overriding server properties + +Sometimes, you may want to evaluate feature flags using [person properties](https://posthog.com/docs/product-analytics/person-properties.md), [groups](https://posthog.com/docs/product-analytics/group-analytics.md), or group properties that haven't been ingested yet, or were set incorrectly earlier. + +You can provide properties to evaluate the flag with by using the `person properties`, `groups`, and `group properties` arguments. PostHog will then use these values to evaluate the flag, instead of any properties currently stored on your PostHog server. + +For example: + +```ruby +flags = posthog.evaluate_flags( + 'distinct_id_of_the_user', + person_properties: { + property_name: 'value' + }, + groups: { + your_group_type: 'your_group_id', + another_group_type: 'your_group_id', + }, + group_properties: { + your_group_type: { + group_property_name: 'value' + }, + another_group_type: { + group_property_name: 'value' + }, + }, +) + +if flags.enabled?('flag-key') + # Do something differently for this user +end +``` + +### Overriding GeoIP properties + +By default, a user's GeoIP properties are set using the IP address they use to capture events on the frontend. You may want to override the these properties when evaluating feature flags. A common reason to do this is when you're not using PostHog on your frontend, so the user has no GeoIP properties. + +You can override GeoIP properties by including them in the `person_properties` parameter when evaluating feature flags. This is useful when you're evaluating flags on your backend and want to use the client's location instead of your server's location. + +The following GeoIP properties can be overridden: + +- `$geoip_country_code` +- `$geoip_country_name` +- `$geoip_city_name` +- `$geoip_city_confidence` +- `$geoip_continent_code` +- `$geoip_continent_name` +- `$geoip_latitude` +- `$geoip_longitude` +- `$geoip_postal_code` +- `$geoip_subdivision_1_code` +- `$geoip_subdivision_1_name` +- `$geoip_subdivision_2_code` +- `$geoip_subdivision_2_name` +- `$geoip_subdivision_3_code` +- `$geoip_subdivision_3_name` +- `$geoip_time_zone` + +Simply include any of these properties in the `person_properties` parameter alongside your other person properties when calling feature flags. + +### Request timeout + +You can configure the `feature_flag_request_timeout_seconds` parameter when initializing your PostHog client to set a flag request timeout. This helps prevent your code from being blocked if PostHog's servers are too slow to respond. By default, this is set to 3 seconds. + +```ruby +posthog = PostHog::Client.new({ + # rest of your configuration... + feature_flag_request_timeout_seconds: 3 # Time in seconds. Defaults to 3. +}) +``` + +## Go + +There are two steps to implement feature flags in Go: + +### Step 1: Evaluate flags once + +Call `client.EvaluateFlags()` once for the user, then read values from the returned snapshot. + +#### Boolean feature flags + +```go +flags, err := client.EvaluateFlags(posthog.EvaluateFlagsPayload{ + DistinctId: "distinct_id_of_your_user", +}) +if err != nil { + // Handle error (e.g. capture error and fallback to default behavior) +} + +if flags.IsEnabled("flag-key") { + // Do something differently for this user + // Optional: fetch the payload + matchedFlagPayload := flags.GetFlagPayload("flag-key") +} +``` + +#### Multivariate feature flags + +```go +flags, err := client.EvaluateFlags(posthog.EvaluateFlagsPayload{ + DistinctId: "distinct_id_of_your_user", +}) +if err != nil { + // Handle error (e.g. capture error and fallback to default behavior) +} + +enabledVariant := flags.GetFlag("flag-key") + +if enabledVariant == "variant-key" { // replace "variant-key" with the key of your variant + // Do something differently for this user + // Optional: fetch the payload + matchedFlagPayload := flags.GetFlagPayload("flag-key") +} +``` + +`flags.GetFlag()` returns the variant string for multivariate flags, `true` for enabled boolean flags, `false` for disabled flags, and `nil` when the flag wasn't returned by the evaluation. + +> **Note:** `client.IsFeatureEnabled()`, `client.GetFeatureFlag()`, `client.GetFeatureFlagPayload()`, and `Capture.SendFeatureFlags` still work during the migration period, but they're deprecated. Prefer `EvaluateFlags()` for new code. + +### Step 2: Include feature flag information when capturing events + +If you want use your feature flag to breakdown or filter events in your [insights](https://posthog.com/docs/product-analytics/insights.md), you'll need to include feature flag information in those events. This ensures that the feature flag value is attributed correctly to the event. + +> **Note:** This step is only required for events captured using our server-side SDKs or [API](https://posthog.com/docs/api.md). + +There are two methods you can use to include feature flag information in your events: + +#### Method 1: Pass the evaluated flags snapshot to `Capture` + +Pass the same `flags` object that you used for branching. This attaches the exact flag values from that evaluation and doesn't make another `/flags` request. + +```go +flags, err := client.EvaluateFlags(posthog.EvaluateFlagsPayload{ + DistinctId: "distinct_id_of_your_user", +}) +if err != nil { + // Handle error +} + +if flags.IsEnabled("flag-key") { + // Do something differently for this user +} + +client.Enqueue(posthog.Capture{ + DistinctId: "distinct_id_of_your_user", + Event: "event_name", + Flags: flags, +}) +``` + +By default, this attaches every flag in the snapshot using `$feature/` properties and `$active_feature_flags`. + +To reduce event property bloat, pass a filtered snapshot: + +```go +// Attach only flags accessed with IsEnabled() or GetFlag() before this call +client.Enqueue(posthog.Capture{ + DistinctId: "distinct_id_of_your_user", + Event: "event_name", + Flags: flags.OnlyAccessed(), +}) + +// Attach only specific flags +client.Enqueue(posthog.Capture{ + DistinctId: "distinct_id_of_your_user", + Event: "event_name", + Flags: flags.Only([]string{"checkout-flow", "new-dashboard"}), +}) +``` + +`OnlyAccessed()` is order-dependent. If you call it before accessing any flags with `IsEnabled()` or `GetFlag()`, no feature flag properties are attached. + +#### Method 2: Include the `$feature/feature_flag_name` property manually + +In the event properties, include `$feature/feature_flag_name: variant_key`: + +```go +client.Enqueue(posthog.Capture{ + DistinctId: "distinct_id_of_your_user", + Event: "event_name", + Properties: posthog.NewProperties(). + Set("$feature/feature-flag-key", "variant-key"), // replace feature-flag-key with your flag key. Replace "variant-key" with the key of your variant +}) +``` + +### Evaluating only specific flags + +By default, `EvaluateFlags()` evaluates every flag for the user. If you only need a few flags, pass `FlagKeys` to request only those flags: + +```go +flags, err := client.EvaluateFlags(posthog.EvaluateFlagsPayload{ + DistinctId: "distinct_id_of_your_user", + FlagKeys: []string{"checkout-flow", "new-dashboard"}, +}) +``` + +### Sending `$feature_flag_called` events + +Capturing `$feature_flag_called` events enables PostHog to know when a flag was accessed by a user and provide [analytics and insights](https://posthog.com/docs/product-analytics/insights.md) on the flag. With `EvaluateFlags()`, the SDK sends this event when you call `flags.IsEnabled()` or `flags.GetFlag()` for a flag. + +The SDK deduplicates these events per `(distinct_id, flag, value)` in a local cache. If you reinitialize the PostHog client, the cache resets and `$feature_flag_called` events may be sent again. PostHog handles duplicates, so duplicate `$feature_flag_called` events don't affect your analytics. + +`flags.GetFlagPayload()` doesn't send `$feature_flag_called` events and doesn't count as an access for `OnlyAccessed()`. + +### Advanced: Overriding server properties + +Sometimes, you may want to evaluate feature flags using [person properties](https://posthog.com/docs/product-analytics/person-properties.md), [groups](https://posthog.com/docs/product-analytics/group-analytics.md), or group properties that haven't been ingested yet, or were set incorrectly earlier. + +You can provide properties to evaluate the flag with by using the `person properties`, `groups`, and `group properties` arguments. PostHog will then use these values to evaluate the flag, instead of any properties currently stored on your PostHog server. + +For example: + +```go +flags, err := client.EvaluateFlags(posthog.EvaluateFlagsPayload{ + DistinctId: "distinct_id_of_the_user", + Groups: posthog.NewGroups(). + Set("your_group_type", "your_group_id"). + Set("another_group_type", "your_group_id"), + PersonProperties: posthog.NewProperties(). + Set("property_name", "value"), + GroupProperties: map[string]posthog.Properties{ + "your_group_type": posthog.NewProperties(). + Set("group_property_name", "value"), + "another_group_type": posthog.NewProperties(). + Set("group_property_name", "value"), + }, +}) +if err != nil { + // Handle error +} + +if flags.IsEnabled("flag-key") { + // Do something differently for this user +} +``` + +### Overriding GeoIP properties + +By default, a user's GeoIP properties are set using the IP address they use to capture events on the frontend. You may want to override the these properties when evaluating feature flags. A common reason to do this is when you're not using PostHog on your frontend, so the user has no GeoIP properties. + +You can override GeoIP properties by including them in the `person_properties` parameter when evaluating feature flags. This is useful when you're evaluating flags on your backend and want to use the client's location instead of your server's location. + +The following GeoIP properties can be overridden: + +- `$geoip_country_code` +- `$geoip_country_name` +- `$geoip_city_name` +- `$geoip_city_confidence` +- `$geoip_continent_code` +- `$geoip_continent_name` +- `$geoip_latitude` +- `$geoip_longitude` +- `$geoip_postal_code` +- `$geoip_subdivision_1_code` +- `$geoip_subdivision_1_name` +- `$geoip_subdivision_2_code` +- `$geoip_subdivision_2_name` +- `$geoip_subdivision_3_code` +- `$geoip_subdivision_3_name` +- `$geoip_time_zone` + +Simply include any of these properties in the `person_properties` parameter alongside your other person properties when calling feature flags. + +### Request timeout + +You can configure the `FeatureFlagRequestTimeout` parameter when initializing your PostHog client to set a flag request timeout. This helps prevent your code from being blocked if PostHog's servers are too slow to respond. By default, this is set to 3 seconds. + +```go +// import "time" + +client, _ := posthog.NewWithConfig( + os.Getenv(""), + posthog.Config{ + PersonalApiKey: "your personal API key", // Optional, but much more performant. If this token is not supplied, then fetching feature flag values will be slower. + Endpoint: "https://us.i.posthog.com", + FeatureFlagRequestTimeout: 3 * time.Second, // Defaults to 3 seconds. + }, +) +``` + +## React Native + +There are two ways to implement feature flags in React Native: + +1. Using hooks. +2. Loading the flag directly. + +### Method 1: Using hooks + +#### Example 1: Boolean feature flags + +```jsx +import { useFeatureFlag } from 'posthog-react-native' + +const MyComponent = () => { + const booleanFlag = useFeatureFlag('key-for-your-boolean-flag') + + if (booleanFlag === undefined) { + // the response is undefined if the flags are being loaded + return null + } + + // Optional use the 'useFeatureFlagWithPayload' hook for fetching the feature flag payload + + return booleanFlag ? Testing feature 😄 : Not Testing feature 😢 +} +``` + +#### Example 2: Multivariate feature flags + +```jsx +import { useFeatureFlag } from 'posthog-react-native' + +const MyComponent = () => { + const multiVariantFeature = useFeatureFlag('key-for-your-multivariate-flag') + + if (multiVariantFeature === undefined) { + // the response is undefined if the flags are being loaded + return null + } else if (multiVariantFeature === 'variant-name') { // replace 'variant-name' with the name of your variant + // Do something + } + + // Optional use the 'useFeatureFlagWithPayload' hook for fetching the feature flag payload + + return
+} +``` + +### Method 2: Loading the flag directly + +```jsx +// Defaults to undefined if not loaded yet or if there was a problem loading +posthog.isFeatureEnabled('key-for-your-boolean-flag') + +// Defaults to undefined if not loaded yet or if there was a problem loading +posthog.getFeatureFlag('key-for-your-boolean-flag') + +// Multivariant feature flags are returned as a string +posthog.getFeatureFlag('key-for-your-multivariate-flag') + +// Optional: fetch the payload (returns 'JsonType' or undefined if not loaded yet or if there was a problem loading) +posthog.getFeatureFlagResult('key-for-your-multivariate-flag')?.payload +``` + +### Inspecting all feature flags + +You can inspect all currently loaded feature flags with `getAllFeatureFlags()`. It returns each flag's `key`, `enabled` state, `variant`, and `payload`, and does not send a `$feature_flag_called` event, so calling it won't affect your experiment results or flag usage analytics: + +```jsx +for (const flag of posthog.getAllFeatureFlags()) { + console.log(flag.key, flag.enabled, flag.variant, flag.payload) +} +``` + +### Ensuring flags are loaded before usage + +Every time a user opens the app, we send a request in the background to fetch the feature flags that apply to that user. We store those flags in the storage. + +This means that for most screens, the feature flags are available immediately — **except for the first time a user visits**. + +To handle this, you can use the `onFeatureFlags` callback to wait for the feature flag request to finish: + +```jsx +posthog.onFeatureFlags((flags) => { + // feature flags are guaranteed to be available at this point + if (posthog.isFeatureEnabled('flag-key')) { + // do something + } +}) +``` + +### Reloading flags + +PostHog loads feature flags when instantiated and refreshes whenever methods are called that affect the flag. + +If want to manually trigger a refresh, you can call `reloadFeatureFlagsAsync()`: + +```jsx +posthog.reloadFeatureFlagsAsync().then((refreshedFlags) => console.log(refreshedFlags)) +``` + +Or when you want to trigger the reload, but don't care about the result: + +```jsx +posthog.reloadFeatureFlags() +``` + +### Feature flag caching + +The React Native SDK caches feature flag values in AsyncStorage. Cached values persist indefinitely with no TTL until updated by a successful API call. This enables offline support and reduces latency, but means **inactive users may see stale flag values** from their last session. + +For example, if a user last opened your app when a flag was `false`, that value remains cached even after you roll it out to 100%. When they reopen the app, the SDK returns the cached `false` first, then fetches the fresh `true` value from the API. + +To ensure fresh flag values: + +```jsx +// Force refresh on app start +await posthog.reloadFeatureFlagsAsync() +``` + +Or clear cached values for inactive users: + +```jsx +if (lastActiveDate < migrationDate) { + posthog.reset() // Clears all cached data +} +``` + +### Request timeout + +You can configure the `featureFlagsRequestTimeoutMs` parameter when initializing your PostHog client to set a flag request timeout. This helps prevent your code from being blocked in the case when PostHog's servers are too slow to respond. By default, this is set at 10 seconds. + +```jsx +export const posthog = new PostHog('', { + // usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com' + host: 'https://us.i.posthog.com', + featureFlagsRequestTimeoutMs: 10000 // Time in milliseconds. Default is 10000 (10 seconds). +}) +``` + +### Error handling + +When using the PostHog SDK, it's important to handle potential errors that may occur during feature flag operations. Here's an example of how to wrap PostHog SDK methods in an error handler: + +```jsx +function handleFeatureFlag(client, flagKey, distinctId) { + try { + const isEnabled = client.isFeatureEnabled(flagKey, distinctId); + console.log(`Feature flag '${flagKey}' for user '${distinctId}' is ${isEnabled ? 'enabled' : 'disabled'}`); + return isEnabled; + } catch (error) { + console.error(`Error fetching feature flag '${flagKey}': ${error.message}`); + // Optionally, you can return a default value or throw the error + // return false; // Default to disabled + throw error; + } +} + +// Usage example +try { + const flagEnabled = handleFeatureFlag(client, 'new-feature', 'user-123'); + if (flagEnabled) { + // Implement new feature logic + } else { + // Implement old feature logic + } +} catch (error) { + // Handle the error at a higher level + console.error('Feature flag check failed, using default behavior'); + // Implement fallback logic +} +``` + +### Overriding server properties + +Sometimes, you might want to evaluate feature flags using properties that haven't been ingested yet, or were set incorrectly earlier. You can do so by setting properties the flag depends on with these calls: + +```jsx +posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'}) +``` + +Note that these are set for the entire session. Successive calls are additive: all properties you set are combined together and sent for flag evaluation. + +Whenever you set these properties, we also trigger a reload of feature flags to ensure we have the latest values. You can disable this by passing in the optional parameter for reloading: + +```jsx +posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'}, false) +``` + +At any point, you can reset these properties by calling `resetPersonPropertiesForFlags`: + +```jsx +posthog.resetPersonPropertiesForFlags() +``` + +The same holds for [group](https://posthog.com/docs/product-analytics/group-analytics.md) properties: + +```jsx +// set properties for a group +posthog.setGroupPropertiesForFlags({'company': {'property1': 'value', property2: 'value2'}}) + +// reset properties for all groups: +posthog.resetGroupPropertiesForFlags() +``` + +> **Note:** You don't need to add the group names here, since these properties are automatically attached to the current group (set via `posthog.group()`). When you change the group, these properties are reset. + +**Automatic overrides** + +Whenever you call `posthog.identify` with person properties, we automatically add these properties to flag evaluation calls to help determine the correct flag values. The same is true for when you call `posthog.group()`. + +**Default overridden properties** + +By default, we always override some properties based on the user IP address. + +The list of properties that this overrides: + +1. $geoip\_city\_name +2. $geoip\_country\_name +3. $geoip\_country\_code +4. $geoip\_continent\_name +5. $geoip\_continent\_code +6. $geoip\_postal\_code +7. $geoip\_time\_zone + +This enables any geolocation-based flags to work without manually setting these properties. + +## Android + +### Boolean feature flags + +```kotlin +import com.posthog.PostHog + +val result = PostHog.getFeatureFlagResult("flag-key") +if (result?.enabled == true) { + // Do something differently for this user + + // Optional: fetch the payload from the same evaluation result + val matchedFlagPayload = result.payload +} +``` + +### Multivariate feature flags + +```kotlin +import com.posthog.PostHog + +val result = PostHog.getFeatureFlagResult("flag-key") +if (result?.variant == "variant-key") { // replace "variant-key" with the key of your variant + // Do something differently for this user + + // Optional: fetch the payload from the same evaluation result + val matchedFlagPayload = result.payload +} +``` + +### Inspecting all feature flags + +You can inspect all currently loaded feature flags with `PostHog.getAllFeatureFlags()`. It returns each flag's `key`, `enabled` state, `variant`, and `payload`, and does not send a `$feature_flag_called` event, so calling it won't affect your experiment results or flag usage analytics: + +```kotlin +import com.posthog.PostHog + +PostHog.getAllFeatureFlags()?.forEach { flag -> + println("${flag.key} ${flag.enabled} ${flag.variant} ${flag.payload}") +} +``` + +### Ensuring flags are loaded before usage + +Every time a user opens the app, we send a request in the background to fetch the feature flags that apply to that user. We store those flags in the storage. + +This means that for most screens, the feature flags are available immediately – **except for the first time a user visits**. + +To handle this, you can use the `onFeatureFlags` callback to wait for the feature flag request to finish: + +```kotlin +import com.posthog.PostHog +import com.posthog.android.PostHogAndroidConfig +import com.posthog.PostHogOnFeatureFlags + +// During SDK initialization +val config = PostHogAndroidConfig(apiKey = "").apply { + onFeatureFlags = PostHogOnFeatureFlags { + if (PostHog.isFeatureEnabled("flag-key")) { + // do something + } + } +} + +// And/or after the SDK is initialized +PostHog.reloadFeatureFlags { + if (PostHog.isFeatureEnabled("flag-key")) { + // do something + } +} +``` + +### Reloading feature flags + +Feature flag values are cached. If something has changed with your user and you'd like to refetch their flag values, call: + +```kotlin +import com.posthog.PostHog + +PostHog.reloadFeatureFlags() +``` + +### Tracking feature usage + +To track when someone sees or interacts with a feature, use `captureFeatureView` and `captureFeatureInteraction`. + +```kotlin +import com.posthog.PostHog + +PostHog.captureFeatureView("flag-key", flagVariant = "variant-key") +PostHog.captureFeatureInteraction("flag-key", flagVariant = "variant-key") +``` + +## iOS + +### Boolean feature flags + +```swift +if let result = PostHogSDK.shared.getFeatureFlagResult("flag-key"), result.enabled { + // Do something differently for this user + + // Optional: fetch the payload from the same evaluation result + let matchedFlagPayload = result.payload +} +``` + +### Multivariate feature flags + +```swift +if let result = PostHogSDK.shared.getFeatureFlagResult("flag-key"), result.variant == "variant-key" { // replace "variant-key" with the key of your variant + // Do something differently for this user + + // Optional: fetch the payload from the same evaluation result + let matchedFlagPayload = result.payload +} +``` + +### Typed payloads + +If your payload is a JSON object, you can decode it into a `Decodable` type: + +```swift +struct FlagPayload: Decodable { + let title: String +} + +if let result = PostHogSDK.shared.getFeatureFlagResult("flag-key"), + let payload = result.payloadAs(FlagPayload.self) { + // Use payload.title +} +``` + +### Inspecting all feature flags + +You can inspect all currently loaded feature flags with `getAllFeatureFlags()`. It returns each flag's `key`, `enabled` state, `variant`, and `payload`, and does not send a `$feature_flag_called` event, so calling it won't affect your experiment results or flag usage analytics: + +```swift +for flag in PostHogSDK.shared.getAllFeatureFlags() ?? [] { + print(flag.key, flag.enabled, flag.variant as Any, flag.payload as Any) +} +``` + +### Reloading feature flags + +Feature flag values are cached. If something has changed with your user and you'd like to refetch their flag values, call: + +```swift +PostHogSDK.shared.reloadFeatureFlags() +``` + +### Ensuring flags are loaded before usage + +Every time a user opens the app, we send a request in the background to fetch the feature flags that apply to that user. We store those flags in the storage. + +This means that for most screens, the feature flags are available immediately – **except for the first time a user visits**. + +To handle this, you can use the `onFeatureFlags` callback to be notified when flags are loaded or change. It's available in version 3.89.0+: + +```swift +let subscription = PostHogSDK.shared.onFeatureFlags { loaded in + if loaded.errorsLoading { + // Loading failed, so the flags are the last known values, which can be empty. + // Fall back to your default experience if you need fresh values. + return + } + if PostHogSDK.shared.isFeatureEnabled("flag-key") { + // do something + } +} + +// Later, to stop receiving updates +subscription.unsubscribe() +``` + +The callback runs on the main thread. It's called when flags load – including from [bootstrap values](https://posthog.com/docs/feature-flags/bootstrapping.md) – and again each time they're reloaded, for example after `reloadFeatureFlags()`, `reset()`, or an `identify()` or `group()` call that changes the distinct ID or group. A reload doesn't have to change any values, so treat each call as "flags may have changed". If flags have already loaded when you register, it's called shortly afterwards with the current values. You can register before calling `setup()`. + +#### Callback parameters + +The callback receives a `PostHogFeatureFlagsLoaded` object with the following properties: + +- `flags: [String]`: The keys of the enabled feature flags. + +- `variants: [String: Any]`: The values of the enabled feature flags, keyed by flag key. A value is `true` for an enabled boolean flag, or the variant key for a multivariate flag. + +- `errorsLoading: Bool`: `true` if the latest attempt to load feature flags failed, for example because the device is offline. The flags and variants then hold the last known values, which can be empty – for example, on a fresh install with no [bootstrap values](https://posthog.com/docs/feature-flags/bootstrapping.md). In that case, `isFeatureEnabled` returns `false` because the flag is unknown, not because PostHog evaluated it as disabled. + +On versions earlier than 3.89.0, observe the `PostHogSDK.didReceiveFeatureFlags` notification instead. Register the observer before calling `setup()`: + +```swift +let observer = NotificationCenter.default.addObserver( + forName: PostHogSDK.didReceiveFeatureFlags, + object: nil, + queue: .main +) { _ in + if PostHogSDK.shared.isFeatureEnabled("flag-key") { + // do something + } +} + +// Later, to stop receiving updates +NotificationCenter.default.removeObserver(observer) +``` + +Alternatively, you can use the completion block of the `reloadFeatureFlags(_:)` method. This allows you to execute logic immediately after the flags are reloaded: + +```swift +// Reload feature flags and check if a specific feature is enabled +PostHogSDK.shared.reloadFeatureFlags { + if PostHogSDK.shared.isFeatureEnabled("flag-key") { + // do something + } +} +``` + +### Tracking feature usage + +To track when someone sees or interacts with a feature, use `captureFeatureView` and `captureFeatureInteraction`. + +```swift +PostHogSDK.shared.captureFeatureView(flag: "flag-key", flagVariant: "variant-key") +PostHogSDK.shared.captureFeatureInteraction(flag: "flag-key", flagVariant: "variant-key") +``` + +## Flutter + +### Boolean feature flags + +```dart +final result = await Posthog().getFeatureFlagResult('flag-key'); +if (result != null && result.enabled) { + // Do something differently for this user + + // Optional: fetch the payload from the same evaluation result + final matchedFlagPayload = result.payload; +} +``` + +### Multivariate feature flags + +```dart +final result = await Posthog().getFeatureFlagResult('flag-key'); +if (result != null && result.variant == 'variant-key') { // replace 'variant-key' with the key of your variant + // Do something differently for this user + + // Optional: fetch the payload from the same evaluation result + final matchedFlagPayload = result.payload; +} +``` + +### Ensuring flags are loaded before usage + +> To use the `onFeatureFlags` callback, you must [set up the SDK manually](#installation). On Android and iOS, disable `com.posthog.posthog.AUTO_INIT` first. + +Every time a user opens the app, we send a request in the background to fetch the feature flags that apply to that user. We store those flags in the storage. + +This means that for most screens, the feature flags are available immediately – **except for the first time a user visits**. + +To handle this, you can use the `onFeatureFlags` callback in your config to be notified when flags are loaded: + +```dart +final config = PostHogConfig(''); +config.host = 'https://us.i.posthog.com'; +config.onFeatureFlags = () async { + if (await Posthog().isFeatureEnabled('flag-key')) { + // do something + } +}; +await Posthog().setup(config); +``` + +### Reloading feature flags + +Feature flag values are cached. If something has changed with your user and you'd like to refetch their flag values, call: + +```dart +await Posthog().reloadFeatureFlags(); +``` + +## Java + +There are two steps to implement feature flags in Java: + +### Step 1: Evaluate flags once + +Call `posthog.evaluateFlags()` once for the user, then read values from the returned snapshot. + +#### Boolean feature flags + +```java +PostHogFeatureFlagEvaluations flags = posthog.evaluateFlags("distinct_id_of_your_user"); + +if (flags.isEnabled("flag-key")) { + // Do something differently for this user + + // Optional: fetch the payload + String matchedFlagPayload = flags.getFlagPayload("flag-key"); +} +``` + +#### Multivariate feature flags + +```java +PostHogFeatureFlagEvaluations flags = posthog.evaluateFlags("distinct_id_of_your_user"); + +Object flagValue = flags.getFlag("flag-key"); +String enabledVariant = flagValue instanceof String ? (String) flagValue : null; + +if ("variant-key".equals(enabledVariant)) { // replace "variant-key" with the key of your variant + // Do something differently for this user + + // Optional: fetch the payload + String matchedFlagPayload = flags.getFlagPayload("flag-key"); +} +``` + +`flags.getFlag()` returns the variant string for multivariate flags, `true` for enabled boolean flags, `false` for disabled flags, and `null` when the flag wasn't returned by the evaluation. + +> **Note:** `posthog.isFeatureEnabled()`, `posthog.getFeatureFlag()`, `posthog.getFeatureFlagPayload()`, and `PostHogCaptureOptions.builder().appendFeatureFlags(true)` still work during the migration period, but they're deprecated. Prefer `evaluateFlags()` for new code. + +### Step 2: Include feature flag information when capturing events + +If you want use your feature flag to breakdown or filter events in your [insights](https://posthog.com/docs/product-analytics/insights.md), you'll need to include feature flag information in those events. This ensures that the feature flag value is attributed correctly to the event. + +> **Note:** This step is only required for events captured using our server-side SDKs or [API](https://posthog.com/docs/api.md). + +There are two methods you can use to include feature flag information in your events: + +#### Method 1: Pass the evaluated flags snapshot to `capture()` + +Pass the same `flags` object that you used for branching. This attaches the exact flag values from that evaluation and doesn't make another `/flags` request. + +```java +PostHogFeatureFlagEvaluations flags = posthog.evaluateFlags("distinct_id_of_your_user"); + +if (flags.isEnabled("flag-key")) { + // Do something differently for this user +} + +posthog.capture( + "distinct_id_of_your_user", + "event_name", + PostHogCaptureOptions.builder() + .flags(flags) + .build() +); +``` + +By default, this attaches every flag in the snapshot using `$feature/` properties and `$active_feature_flags`. + +To reduce event property bloat, pass a filtered snapshot: + +```java +// Attach only flags accessed with isEnabled() or getFlag() before this call +posthog.capture( + "distinct_id_of_your_user", + "event_name", + PostHogCaptureOptions.builder() + .flags(flags.onlyAccessed()) + .build() +); + +// Attach only specific flags +posthog.capture( + "distinct_id_of_your_user", + "event_name", + PostHogCaptureOptions.builder() + .flags(flags.only("checkout-flow", "new-dashboard")) + .build() +); +``` + +`onlyAccessed()` is order-dependent. If you call it before accessing any flags with `isEnabled()` or `getFlag()`, no feature flag properties are attached. + +#### Method 2: Include the `$feature/feature_flag_name` property manually + +In the event properties, include `$feature/feature_flag_name: variant_key`: + +```java +posthog.capture( + "distinct_id_of_your_user", + "event_name", + PostHogCaptureOptions.builder() + .property("$feature/feature-flag-key", "variant-key") // replace feature-flag-key with your flag key. Replace "variant-key" with the key of your variant + .build() +); +``` + +### Evaluating only specific flags + +By default, `evaluateFlags()` evaluates every flag for the user. If you only need a few flags, pass `flagKeys` to request only those flags: + +```java +import java.util.Arrays; + +PostHogFeatureFlagEvaluations flags = posthog.evaluateFlags( + "distinct_id_of_your_user", + PostHogEvaluateFlagsOptions.builder() + .flagKeys(Arrays.asList("checkout-flow", "new-dashboard")) + .build() +); +``` + +### Sending `$feature_flag_called` events + +Capturing `$feature_flag_called` events enables PostHog to know when a flag was accessed by a user and provide [analytics and insights](https://posthog.com/docs/product-analytics/insights.md) on the flag. With `evaluateFlags()`, the SDK sends this event when you call `flags.isEnabled()` or `flags.getFlag()` for a flag. + +The SDK deduplicates these events per `(distinct_id, flag, value)` in a local cache. If you reinitialize the PostHog client, the cache resets and `$feature_flag_called` events may be sent again. PostHog handles duplicates, so duplicate `$feature_flag_called` events don't affect your analytics. + +`flags.getFlagPayload()` doesn't send `$feature_flag_called` events and doesn't count as an access for `onlyAccessed()`. + +### Advanced: Overriding server properties + +Sometimes, you may want to evaluate feature flags using [person properties](https://posthog.com/docs/product-analytics/person-properties.md), [groups](https://posthog.com/docs/product-analytics/group-analytics.md), or group properties that haven't been ingested yet, or were set incorrectly earlier. + +You can provide properties to evaluate the flag with by using the `person properties`, `groups`, and `group properties` arguments. PostHog will then use these values to evaluate the flag, instead of any properties currently stored on your PostHog server. + +For example: + +```java +import com.posthog.server.PostHogEvaluateFlagsOptions; + +PostHogFeatureFlagEvaluations flags = posthog.evaluateFlags( + "distinct_id_of_the_user", + PostHogEvaluateFlagsOptions.builder() + .group("your_group_type", "your_group_id") + .group("another_group_type", "your_group_id") + .groupProperty("your_group_type", "group_property_name", "value") + .groupProperty("another_group_type", "group_property_name", "value") + .personProperty("property_name", "value") + .build() +); + +if (flags.isEnabled("flag-key")) { + // Do something differently for this user +} +``` + +### Overriding GeoIP properties + +By default, a user's GeoIP properties are set using the IP address they use to capture events on the frontend. You may want to override the these properties when evaluating feature flags. A common reason to do this is when you're not using PostHog on your frontend, so the user has no GeoIP properties. + +You can override GeoIP properties by including them in the `person_properties` parameter when evaluating feature flags. This is useful when you're evaluating flags on your backend and want to use the client's location instead of your server's location. + +The following GeoIP properties can be overridden: + +- `$geoip_country_code` +- `$geoip_country_name` +- `$geoip_city_name` +- `$geoip_city_confidence` +- `$geoip_continent_code` +- `$geoip_continent_name` +- `$geoip_latitude` +- `$geoip_longitude` +- `$geoip_postal_code` +- `$geoip_subdivision_1_code` +- `$geoip_subdivision_1_name` +- `$geoip_subdivision_2_code` +- `$geoip_subdivision_2_name` +- `$geoip_subdivision_3_code` +- `$geoip_subdivision_3_name` +- `$geoip_time_zone` + +Simply include any of these properties in the `person_properties` parameter alongside your other person properties when calling feature flags. + +## Rust + +There are two steps to implement feature flags in Rust: + +### Step 1: Evaluate flags once + +Call `client.evaluate_flags()` once for the user, then read values from the returned snapshot. + +#### Boolean feature flags + +```rust +use posthog_rs::EvaluateFlagsOptions; + +let flags = client.evaluate_flags( + "distinct_id_of_your_user", + EvaluateFlagsOptions::default(), +).await.unwrap(); + +if flags.is_enabled("flag-key") { + // Do something differently for this user + // Optional: fetch the payload + let matched_flag_payload = flags.get_flag_payload("flag-key"); +} +``` + +#### Multivariate feature flags + +```rust +use posthog_rs::{EvaluateFlagsOptions, FlagValue}; + +let flags = client.evaluate_flags( + "distinct_id_of_your_user", + EvaluateFlagsOptions::default(), +).await.unwrap(); + +match flags.get_flag("flag-key") { + Some(FlagValue::String(variant)) if variant == "variant-key" => { + // Do something differently for this user + // Optional: fetch the payload + let matched_flag_payload = flags.get_flag_payload("flag-key"); + } + _ => {} +} +``` + +`flags.get_flag()` returns `Some(FlagValue::String(...))` for multivariate flags, `Some(FlagValue::Boolean(true))` for enabled boolean flags, `Some(FlagValue::Boolean(false))` for disabled flags, and `None` when the flag wasn't returned by the evaluation. + +> **Note:** `client.is_feature_enabled()`, `client.get_feature_flag()`, `client.get_feature_flag_payload()`, and `client.get_feature_flags()` still work during the migration period, but they're deprecated. Prefer `evaluate_flags()` for new code. + +### Step 2: Include feature flag information when capturing events + +If you want use your feature flag to breakdown or filter events in your [insights](https://posthog.com/docs/product-analytics/insights.md), you'll need to include feature flag information in those events. This ensures that the feature flag value is attributed correctly to the event. + +> **Note:** This step is only required for events captured using our server-side SDKs or [API](https://posthog.com/docs/api.md). + +There are two methods you can use to include feature flag information in your events: + +#### Method 1: Pass the evaluated flags snapshot to the event + +Pass the same `flags` object that you used for branching. This attaches the exact flag values from that evaluation and doesn't make another `/flags` request. + +```rust +use posthog_rs::{EvaluateFlagsOptions, Event}; + +let flags = client.evaluate_flags( + "distinct_id_of_your_user", + EvaluateFlagsOptions::default(), +).await.unwrap(); + +if flags.is_enabled("flag-key") { + // Do something differently for this user +} + +let mut event = Event::new("event_name", "distinct_id_of_your_user"); +event.with_flags(&flags); +client.capture(event); +``` + +By default, this attaches every flag in the snapshot using `$feature/` properties and `$active_feature_flags`. + +To reduce event property bloat, pass a filtered snapshot: + +```rust +// Attach only flags accessed with is_enabled() or get_flag() before this call +let mut event = Event::new("event_name", "distinct_id_of_your_user"); +event.with_flags(&flags.only_accessed()); +client.capture(event); + +// Attach only specific flags +let mut event = Event::new("event_name", "distinct_id_of_your_user"); +event.with_flags(&flags.only(&["checkout-flow", "new-dashboard"])); +client.capture(event); +``` + +`only_accessed()` is order-dependent. If you call it before accessing any flags with `is_enabled()` or `get_flag()`, no feature flag properties are attached. + +#### Method 2: Include the `$feature/feature_flag_name` property manually + +In the event properties, include `$feature/feature_flag_name: variant_key`: + +```rust +use posthog_rs::Event; + +let mut event = Event::new("event_name", "distinct_id_of_your_user"); +event.insert_prop("$feature/feature-flag-key", "variant-key").unwrap(); +client.capture(event); +``` + +### Evaluating only specific flags + +By default, `evaluate_flags()` evaluates every flag for the user. If you only need a few flags, pass `flag_keys` to request only those flags: + +```rust +use posthog_rs::EvaluateFlagsOptions; + +let flags = client.evaluate_flags( + "distinct_id_of_your_user", + EvaluateFlagsOptions { + flag_keys: Some(vec!["checkout-flow".to_string(), "new-dashboard".to_string()]), + ..Default::default() + }, +).await.unwrap(); +``` + +### Sending `$feature_flag_called` events + +Capturing `$feature_flag_called` events enables PostHog to know when a flag was accessed by a user and provide [analytics and insights](https://posthog.com/docs/product-analytics/insights.md) on the flag. With `evaluate_flags()`, the SDK sends this event when you call `flags.is_enabled()` or `flags.get_flag()` for a flag. + +The SDK deduplicates these events per `(distinct_id, flag, value)` in a local cache. If you reinitialize the PostHog client, the cache resets and `$feature_flag_called` events may be sent again. PostHog handles duplicates, so duplicate `$feature_flag_called` events don't affect your analytics. + +`flags.get_flag_payload()` doesn't send `$feature_flag_called` events and doesn't count as an access for `only_accessed()`. + +### Blocking client + +If you're using the blocking client (with `default-features = false`), the API is the same but without `.await`: + +```rust +use posthog_rs::EvaluateFlagsOptions; + +let flags = client.evaluate_flags( + "distinct_id_of_your_user", + EvaluateFlagsOptions::default(), +).unwrap(); + +if flags.is_enabled("flag-key") { + // Do something differently for this user +} +``` + +## Elixir + +There are two steps to implement feature flags in Elixir: + +### Step 1: Evaluate flags once + +Call `PostHog.FeatureFlags.evaluate_flags/1` once for the user, then read values from the returned snapshot. + +#### Boolean feature flags + +```elixir +{:ok, snapshot} = PostHog.FeatureFlags.evaluate_flags("distinct_id_of_your_user") + +if PostHog.FeatureFlags.Evaluations.enabled?(snapshot, "flag-key") do + # Do something differently for this user + # Optional: fetch the payload + payload = PostHog.FeatureFlags.Evaluations.get_flag_payload(snapshot, "flag-key") +end +``` + +#### Multivariate feature flags + +```elixir +{:ok, snapshot} = PostHog.FeatureFlags.evaluate_flags("distinct_id_of_your_user") + +enabled_variant = PostHog.FeatureFlags.Evaluations.get_flag(snapshot, "flag-key") + +if enabled_variant == "variant-key" do + # Do something differently for this user + # Optional: fetch the payload + payload = PostHog.FeatureFlags.Evaluations.get_flag_payload(snapshot, "flag-key") +end +``` + +`PostHog.FeatureFlags.Evaluations.get_flag/2` returns the variant string for multivariate flags, `true` for enabled boolean flags, `false` for disabled flags, and `nil` when the flag wasn't returned by the evaluation. + +> **Note:** `PostHog.FeatureFlags.check/2`, `PostHog.FeatureFlags.check!/2`, `PostHog.FeatureFlags.get_feature_flag_result/2`, and `PostHog.FeatureFlags.get_feature_flag_result!/2` still work during the migration period, but they're deprecated. Prefer `evaluate_flags/1` for new code. + +### Step 2: Include feature flag information when capturing events + +If you want use your feature flag to breakdown or filter events in your [insights](https://posthog.com/docs/product-analytics/insights.md), you'll need to include feature flag information in those events. This ensures that the feature flag value is attributed correctly to the event. + +> **Note:** This step is only required for events captured using our server-side SDKs or [API](https://posthog.com/docs/api.md). + +There are two methods you can use to include feature flag information in your events: + +#### Method 1: Put the evaluated flags snapshot in context + +Put the same `snapshot` object that you used for branching into context. Subsequent captures from the same process attach the exact flag values from that evaluation and don't make another `/flags` request. + +```elixir +{:ok, snapshot} = PostHog.FeatureFlags.evaluate_flags("distinct_id_of_your_user") + +if PostHog.FeatureFlags.Evaluations.enabled?(snapshot, "flag-key") do + # Do something differently for this user +end + +PostHog.FeatureFlags.set_in_context(snapshot) +PostHog.capture("event_name", %{distinct_id: "distinct_id_of_your_user"}) +``` + +By default, this attaches every flag in the snapshot using `$feature/` properties and `$active_feature_flags`. + +To reduce event property bloat, put a filtered snapshot in context: + +```elixir +{:ok, snapshot} = PostHog.FeatureFlags.evaluate_flags("distinct_id_of_your_user") + +# Attach only flags accessed with enabled?/2 or get_flag/2 before this call +PostHog.FeatureFlags.Evaluations.enabled?(snapshot, "flag-key") +PostHog.FeatureFlags.set_in_context( + PostHog.FeatureFlags.Evaluations.only_accessed(snapshot) +) + +# Or attach only specific flags +PostHog.FeatureFlags.set_in_context( + PostHog.FeatureFlags.Evaluations.only(snapshot, ["checkout-flow", "new-dashboard"]) +) +``` + +`only_accessed/1` is order-dependent. If you call it before accessing any flags with `enabled?/2` or `get_flag/2`, no feature flag properties are attached. + +#### Method 2: Include the `$feature/feature_flag_name` property manually + +In the event properties, include `$feature/feature_flag_name: variant_key`: + +```elixir +PostHog.capture("event_name", %{ + "$feature/feature-flag-key" => "variant-key", + distinct_id: "distinct_id_of_your_user" +}) +``` + +### Evaluating only specific flags + +By default, `evaluate_flags/1` evaluates every flag for the user. If you only need a few flags, pass `flag_keys` to request only those flags: + +```elixir +{:ok, snapshot} = + PostHog.FeatureFlags.evaluate_flags(%{ + distinct_id: "distinct_id_of_your_user", + flag_keys: ["checkout-flow", "new-dashboard"] + }) +``` + +### Sending `$feature_flag_called` events + +Capturing `$feature_flag_called` events enables PostHog to know when a flag was accessed by a user and provide [analytics and insights](https://posthog.com/docs/product-analytics/insights.md) on the flag. With `evaluate_flags/1`, the SDK sends this event when you call `PostHog.FeatureFlags.Evaluations.enabled?/2` or `PostHog.FeatureFlags.Evaluations.get_flag/2` for a flag. + +`PostHog.FeatureFlags.Evaluations.get_flag_payload/2` doesn't send `$feature_flag_called` events. + +## .NET + +There are two steps to implement feature flags in .NET: + +### Step 1: Evaluate flags once + +Call `EvaluateFlagsAsync()` once for the user, then read values from the returned snapshot. + +#### Boolean feature flags + +```csharp +var flags = await posthog.EvaluateFlagsAsync("distinct_id_of_your_user"); + +if (flags.IsEnabled("flag-key")) +{ + // Do something differently for this user + // Optional: fetch the payload + var matchedPayload = flags.GetFlagPayload("flag-key"); +} +``` + +#### Multivariate feature flags + +```csharp +var flags = await posthog.EvaluateFlagsAsync("distinct_id_of_your_user"); + +var enabledVariant = flags.GetFlag("flag-key")?.VariantKey; + +if (enabledVariant == "variant-key") // replace "variant-key" with the key of your variant +{ + // Do something differently for this user + // Optional: fetch the payload + var matchedPayload = flags.GetFlagPayload("flag-key"); +} +``` + +`flags.GetFlag()` returns a nullable `FeatureFlag` object. Check `VariantKey` for multivariate flags and `IsEnabled` for boolean flags. It returns `null` when the flag wasn't returned by the evaluation. + +> **Note:** `posthog.IsFeatureEnabledAsync()`, `posthog.GetFeatureFlagAsync()`, and `Capture(..., sendFeatureFlags: true, ...)` still work during the migration period, but they're deprecated. Prefer `EvaluateFlagsAsync()` for new code. + +### Step 2: Include feature flag information when capturing events + +If you want use your feature flag to breakdown or filter events in your [insights](https://posthog.com/docs/product-analytics/insights.md), you'll need to include feature flag information in those events. This ensures that the feature flag value is attributed correctly to the event. + +> **Note:** This step is only required for events captured using our server-side SDKs or [API](https://posthog.com/docs/api.md). + +There are two methods you can use to include feature flag information in your events: + +#### Method 1: Pass the evaluated flags snapshot to `Capture()` + +Pass the same `flags` object that you used for branching. This attaches the exact flag values from that evaluation and doesn't make another `/flags` request. + +```csharp +var flags = await posthog.EvaluateFlagsAsync("distinct_id_of_your_user"); + +if (flags.IsEnabled("flag-key")) +{ + // Do something differently for this user +} + +posthog.Capture( + "distinct_id_of_your_user", + "event_name", + properties: null, + groups: null, + flags: flags +); +``` + +By default, this attaches every flag in the snapshot using `$feature/` properties and `$active_feature_flags`. + +To reduce event property bloat, pass a filtered snapshot: + +```csharp +// Attach only flags accessed with IsEnabled() or GetFlag() before this call +posthog.Capture( + "distinct_id_of_your_user", + "event_name", + properties: null, + groups: null, + flags: flags.OnlyAccessed() +); + +// Attach only specific flags +posthog.Capture( + "distinct_id_of_your_user", + "event_name", + properties: null, + groups: null, + flags: flags.Only("checkout-flow", "new-dashboard") +); +``` + +#### Method 2: Include the `$feature/feature_flag_name` property manually + +In the event properties, include `$feature/feature_flag_name: variant_key`: + +```csharp +posthog.Capture( + "distinct_id_of_your_user", + "event_name", + properties: new() + { + // Replace feature-flag-key with your flag key and "variant-key" with the key of your variant + ["$feature/feature-flag-key"] = "variant-key", + } +); +``` + +### Evaluating only specific flags + +By default, `EvaluateFlagsAsync()` evaluates every flag for the user. If you only need a few flags, pass `FlagKeysToEvaluate` to request only those flags: + +```csharp +var flags = await posthog.EvaluateFlagsAsync( + "distinct_id_of_your_user", + options: new AllFeatureFlagsOptions + { + FlagKeysToEvaluate = new[] { "checkout-flow", "new-dashboard" }, + } +); +``` + +### Sending `$feature_flag_called` events + +Capturing `$feature_flag_called` events enables PostHog to know when a flag was accessed by a user and provide [analytics and insights](https://posthog.com/docs/product-analytics/insights.md) on the flag. With `EvaluateFlagsAsync()`, the SDK sends this event when you call `flags.IsEnabled()` or `flags.GetFlag()` for a flag. + +The SDK deduplicates these events per `(distinct_id, flag, value)` in a local cache. If you reinitialize the PostHog client, the cache resets and `$feature_flag_called` events may be sent again. PostHog handles duplicates, so duplicate `$feature_flag_called` events don't affect your analytics. + +`flags.GetFlagPayload()` doesn't send `$feature_flag_called` events and doesn't count as an access for `OnlyAccessed()`. + +### Advanced: Overriding server properties + +Sometimes, you may want to evaluate feature flags using [person properties](https://posthog.com/docs/product-analytics/person-properties.md), [groups](https://posthog.com/docs/product-analytics/group-analytics.md), or group properties that haven't been ingested yet, or were set incorrectly earlier. + +You can provide properties to evaluate the flag with by using the `person properties`, `groups`, and `group properties` arguments. PostHog will then use these values to evaluate the flag, instead of any properties currently stored on your PostHog server. + +For example: + +```csharp +var flags = await posthog.EvaluateFlagsAsync( + "distinct_id_of_the_user", + options: new AllFeatureFlagsOptions + { + PersonProperties = new() + { + ["property_name"] = "value", + }, + Groups = new() + { + new Group("your_group_type", "your_group_id") + { + ["group_property_name"] = "value", + }, + new Group("another_group_type", "another_group_id") + { + ["group_property_name"] = "another value", + }, + }, + } +); + +if (flags.IsEnabled("flag-key")) +{ + // Do something differently for this user +} +``` + +### Overriding GeoIP properties + +By default, a user's GeoIP properties are set using the IP address they use to capture events on the frontend. You may want to override the these properties when evaluating feature flags. A common reason to do this is when you're not using PostHog on your frontend, so the user has no GeoIP properties. + +You can override GeoIP properties by including them in the `person_properties` parameter when evaluating feature flags. This is useful when you're evaluating flags on your backend and want to use the client's location instead of your server's location. + +The following GeoIP properties can be overridden: + +- `$geoip_country_code` +- `$geoip_country_name` +- `$geoip_city_name` +- `$geoip_city_confidence` +- `$geoip_continent_code` +- `$geoip_continent_name` +- `$geoip_latitude` +- `$geoip_longitude` +- `$geoip_postal_code` +- `$geoip_subdivision_1_code` +- `$geoip_subdivision_1_name` +- `$geoip_subdivision_2_code` +- `$geoip_subdivision_2_name` +- `$geoip_subdivision_3_code` +- `$geoip_subdivision_3_name` +- `$geoip_time_zone` + +Simply include any of these properties in the `person_properties` parameter alongside your other person properties when calling feature flags. + +## API + +There are 3 steps to implement feature flags using the PostHog API: + +### Step 1: Evaluate the feature flag value using `flags` + +`flags` is the endpoint used to determine if a given flag is enabled for a certain user or not. + +#### Request + +### Terminal + +```shell +# Basic request (flags only) +curl -v -L --header "Content-Type: application/json" -d ' { + "api_key": "", + "distinct_id": "distinct_id_of_your_user", + "groups" : { + "group_type": "group_id" + } +}' "https://us.i.posthog.com/flags?v=2" + +# With configuration (flags + PostHog config) +curl -v -L --header "Content-Type: application/json" -d ' { + "api_key": "", + "distinct_id": "distinct_id_of_your_user", + "groups" : { + "group_type": "group_id" + } +}' "https://us.i.posthog.com/flags?v=2&config=true" +``` + +### Python + +```python +import requests +import json + +# Basic request (flags only) +url = "https://us.i.posthog.com/flags?v=2" +headers = { + "Content-Type": "application/json" +} +payload = { + "api_key": "", + "distinct_id": "user distinct id", + "groups": { + "group_type": "group_id" + } +} +response = requests.post(url, headers=headers, data=json.dumps(payload)) +print(response.json()) + +# With configuration (flags + PostHog config) +url_with_config = "https://us.i.posthog.com/flags?v=2&config=true" +response_with_config = requests.post(url_with_config, headers=headers, data=json.dumps(payload)) +print(response_with_config.json()) +``` + +### Node.js + +```javascript +import fetch from "node-fetch"; + +async function sendFlagsRequest() { + const headers = { + "Content-Type": "application/json", + }; + const payload = { + api_key: "", + distinct_id: "user distinct id", + groups: { + group_type: "group_id", + }, + }; + + // Basic request (flags only) + const url = "https://us.i.posthog.com/flags?v=2"; + const response = await fetch(url, { + method: "POST", + headers: headers, + body: JSON.stringify(payload), + }); + const data = await response.json(); + console.log(data); + + // With configuration (flags + PostHog config) + const urlWithConfig = "https://us.i.posthog.com/flags?v=2&config=true"; + const responseWithConfig = await fetch(urlWithConfig, { + method: "POST", + headers: headers, + body: JSON.stringify(payload), + }); + const dataWithConfig = await responseWithConfig.json(); + console.log(dataWithConfig); +} + +sendFlagsRequest(); +``` + +> **Note:** The `groups` key is only required for group-based feature flags. If you use it, replace `group_type` and `group_id` with the values for your group such as `company: "Twitter"`. + +#### Using evaluation context tags and runtime filtering without SDKs + +When making direct API calls to the `/flags` endpoint, you can control which flags are evaluated using evaluation context tags and runtime filtering. + +##### Evaluation contexts + +To filter flags by evaluation context, include the `evaluation_contexts` field in your request body: + +> **Note:** The legacy parameter `evaluation_environments` is also supported for backward compatibility. + +### Terminal + +```shell +curl -v -L --header "Content-Type: application/json" -d ' { + "api_key": "", + "distinct_id": "distinct_id_of_your_user", + "evaluation_contexts": ["production", "web"] +}' "https://us.i.posthog.com/flags?v=2" +``` + +### Python + +```python +import requests +import json + +url = "https://us.i.posthog.com/flags?v=2" +headers = { + "Content-Type": "application/json" +} +payload = { + "api_key": "", + "distinct_id": "user distinct id", + "evaluation_contexts": ["production", "web"] +} +response = requests.post(url, headers=headers, data=json.dumps(payload)) +print(response.json()) +``` + +### JavaScript + +```javascript +const response = await fetch("https://us.i.posthog.com/flags?v=2", { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + api_key: "", + distinct_id: "user-distinct-id", + evaluation_contexts: ["production", "web"] + }), +}); +const data = await response.json(); +``` + +Only flags where at least one evaluation tag matches (or flags with no tags at all) will be returned. For example: + +- Flag with evaluation context tags `["production", "api", "backend"]` + request with `["production", "web"]` = ✅ Flag evaluates ("production" matches) +- Flag with evaluation context tags `["staging", "api"]` + request with `["production", "web"]` = ❌ Flag doesn't evaluate (no tags match) +- Flag with evaluation context tags `["web", "mobile"]` + request with `["production", "web"]` = ✅ Flag evaluates ("web" matches) +- Flag with no evaluation context tags = ✅ Always evaluates (backward compatibility) + +##### Runtime detection + +Evaluation runtime (server vs. client) is automatically detected based on your request headers and user-agent. This determines which flags are available based on their runtime setting (server-only, client-only, or all). + +**How runtime is detected:** + +1. **User-Agent patterns** - The system analyzes the User-Agent header: + + - **Client-side patterns**: `Mozilla/`, `Chrome/`, `Safari/`, `Firefox/`, `Edge/` (browsers), or mobile SDKs like `posthog-android/`, `posthog-ios/`, `posthog-react-native/`, `posthog-flutter/` + - **Server-side patterns**: `posthog-python/`, `posthog-ruby/`, `posthog-php/`, `posthog-java/`, `posthog-go/`, `posthog-node/`, `posthog-dotnet/`, `posthog-elixir/`, `python-requests/`, `curl/` +2. **Browser-specific headers** - Presence of these headers indicates client-side: + + - `Origin` header + - `Referer` header + - `Sec-Fetch-Mode` header + - `Sec-Fetch-Site` header +3. **Default behavior** - If runtime can't be determined, the system includes flags with no runtime requirement and those set to "all" + +**Examples of runtime detection:** + +```javascript +// Browser fetch - Detected as CLIENT runtime +// Will receive: client-only flags + "all" flags +// Won't receive: server-only flags +const response = await fetch("https://us.i.posthog.com/flags?v=2", { + method: "POST", + headers: { + "Content-Type": "application/json", + // Browser automatically adds Origin, Referer, Sec-Fetch-* headers + }, + body: JSON.stringify({ + api_key: "", + distinct_id: "user-id" + }) +}); +``` + +```python +# Python requests - Detected as SERVER runtime +# Will receive: server-only flags + "all" flags +# Won't receive: client-only flags +import requests + +response = requests.post( + "https://us.i.posthog.com/flags?v=2", + json={ + "api_key": "", + "distinct_id": "user-id" + } + # python-requests/ in User-Agent indicates server-side +) +``` + +```shell +# curl - Detected as SERVER runtime +# Will receive: server-only flags + "all" flags +# Won't receive: client-only flags +curl -v -L --header "Content-Type: application/json" -d '{ + "api_key": "", + "distinct_id": "user-id" +}' "https://us.i.posthog.com/flags?v=2" +# curl/ in User-Agent indicates server-side +``` + +```javascript +// Node.js with custom User-Agent - Control runtime detection +const response = await fetch("https://us.i.posthog.com/flags?v=2", { + method: "POST", + headers: { + "Content-Type": "application/json", + "User-Agent": "posthog-node/3.0.0" // Explicitly indicates server-side + }, + body: JSON.stringify({ + api_key: "", + distinct_id: "user-id" + }) +}); +``` + +##### Combining evaluation context tags and runtime filtering + +Both features work together as sequential filters: + +```javascript +// Example: Production web client +const response = await fetch("https://us.i.posthog.com/flags?v=2", { + method: "POST", + headers: { + "Content-Type": "application/json", + // Browser headers will trigger client runtime detection + }, + body: JSON.stringify({ + api_key: "", + distinct_id: "user-id", + evaluation_contexts: ["production", "web"] + }) +}); + +// This request will only receive flags that: +// 1. Have runtime set to "client" OR "all" (due to browser headers) +// AND +// 2. Have evaluation context tags matching "production" OR "web" (or no tags) +// Note: You can also use the legacy "evaluation_environments" parameter +``` + +This allows precise control over which flags are evaluated in different contexts, helping optimize costs and improve security by ensuring flags only evaluate where intended. + +#### Response + +The response varies depending on whether you include the `config=true` query parameter: + +##### Basic response (`/flags?v=2`) + +Use this endpoint when you only need to evaluate feature flags. It returns a response with just the flag evaluation results. + +> **Note:** If a feature flag is associated with an experiment that has a [holdout group](https://posthog.com/docs/experiments/holdouts.md), users in the holdout receive a variant value in the format `holdout-{holdout_id}` (e.g., `holdout-727`). You can detect holdout users by checking if the variant starts with `holdout-`. + +```json +{ + "flags": { + "my-awesome-flag": { + "key": "my-awesome-flag", + "enabled": true, + "reason": { + "code": "condition_match", + "condition_index": 0, + "description": "Condition set 1 matched" + }, + "metadata": { + "id": 1, + "version": 1, + "payload": "{\"example\": \"json\", \"payload\": \"value\"}" + } + }, + "my-multivariate-flag" :{ + "key":"my-multivariate-flag", + "enabled": true, + "variant": "some-string-value", + "reason": { + "code": "condition_match", + "condition_index": 1, + "description": "Condition set 2 matched" + }, + "metadata": { + "id": 2, + "version": 42, + } + }, + "flag-thats-not-on": { + "key": "flag-thats-not-on", + "enabled": false, + "reason": { + "code": "no_condition_match", + "condition_index": 0, + "description": "No condition sets matched" + }, + "metadata": { + "id": 3, + "version": 1 + } + } + }, + "errorsWhileComputingFlags": false, + "requestId": "550e8400-e29b-41d4-a716-446655440000" +} +``` + +##### Full response with configuration (`/flags?v=2&config=true`) + +Use this endpoint when you need both feature flag evaluation and PostHog configuration information (useful for client-side SDKs that need to initialize PostHog): + +```json +{ + "config": { + "enable_collect_everything": true + }, + "toolbarParams": {}, + "errorsWhileComputingFlags": false, + "isAuthenticated": false, + "requestId": "550e8400-e29b-41d4-a716-446655440000", + "supportedCompression": [ + "gzip", + "lz64" + ], + "flags": { + "my-awesome-flag": { + "key": "my-awesome-flag", + "enabled": true, + "reason": { + "code": "condition_match", + "condition_index": 0, + "description": "Condition set 1 matched" + }, + "metadata": { + "id": 1, + "version": 1, + "payload": "{\"example\": \"json\", \"payload\": \"value\"}" + } + }, + "my-multivariate-flag" :{ + "key":"my-multivariate-flag", + "enabled": true, + "variant": "some-string-value", + "reason": { + "code": "condition_match", + "condition_index": 1, + "description": "Condition set 2 matched" + }, + "metadata": { + "id": 2, + "version": 42, + } + }, + "flag-thats-not-on": { + "key": "flag-thats-not-on", + "enabled": false, + "reason": { + "code": "no_condition_match", + "condition_index": 0, + "description": "No condition sets matched" + }, + "metadata": { + "id": 3, + "version": 1 + } + } + } +} +``` + +> **Note:** `errorsWhileComputingFlags` will return `true` if we didn't manage to compute some flags (for example, if there's an [ongoing incident involving flag evaluation](https://status.posthog.com/)). +> +> This enables partial updates to currently active flags in your clients. + +#### Quota limiting + +If your organization exceeds its feature flag quota, the `/flags` endpoint will return a modified response with `quotaLimited`. + +For basic response (`/flags?v=2`): + +```json +{ + "flags": {}, + "errorsWhileComputingFlags": false, + "quotaLimited": ["feature_flags"], + "requestId": "d4d89b14-9619-4627-adf2-01b761691c2e" +} +``` + +For full response with configuration (`/flags?v=2&config=true`): + +```json +{ + "config": { + "enable_collect_everything": true + }, + "toolbarParams": {}, + "isAuthenticated": false, + "supportedCompression": [ + "gzip", + "lz64" + ], + "flags": {}, + "errorsWhileComputingFlags": false, + "quotaLimited": ["feature_flags"], + "requestId": "d4d89b14-9619-4627-adf2-01b761691c2e" + // ... other fields, not relevant to feature flags +} +``` + +When you receive a response with `quotaLimited` containing `"feature_flags"`, it means: + +1. Your feature flag evaluations have been temporarily paused because you've exceeded your feature flag quota +2. If you want to continue evaluating feature flags, you can increase your quota in [your billing settings](https://us.posthog.com/organization/billing) under **Feature flags & Experiments** or [contact support](https://us.posthog.com/#panel=support%3Asupport%3Abilling%3A%3Atrue) + +### Step 2: Include feature flag information when capturing events + +If you want use your feature flag to breakdown or filter events in your [insights](https://posthog.com/docs/product-analytics/insights.md), you'll need to include feature flag information in those events. This ensures that the feature flag value is attributed correctly to the event. + +> **Note:** This step is only required for events captured using our server-side SDKs or [API](https://posthog.com/docs/api.md). + +To do this, include the `$feature/feature_flag_name` property in your event: + +### Terminal + +```shell +curl -v -L --header "Content-Type: application/json" -d ' { + "api_key": "", + "event": "your_event_name", + "distinct_id": "distinct_id_of_your_user", + "properties": { + "$feature/feature-flag-key": "variant-key" # Replace feature-flag-key with your flag key. Replace 'variant-key' with the key of your variant + } +}' https://us.i.posthog.com/i/v0/e/ +``` + +### Python + +```python +import requests +import json + +url = "https://us.i.posthog.com/i/v0/e/" +headers = { + "Content-Type": "application/json" +} +payload = { + "api_key": "", + "event": "your_event_name", + "distinct_id": "distinct_id_of_your_user", + "properties": { + "$feature/feature-flag-key": "variant-key" # Replace feature-flag-key with your flag key. Replace 'variant-key' with the key of your variant + } +} +response = requests.post(url, headers=headers, data=json.dumps(payload)) +print(response) +``` + +### Step 3: Send a `$feature_flag_called` event + +To track usage of your feature flag and view related analytics in PostHog, submit the `$feature_flag_called` event whenever you check a feature flag value in your code. + +You need to include two properties with this event: + +1. `$feature_flag_response`: This is the name of the variant the user has been assigned to e.g., "control" or "test" +2. `$feature_flag`: This is the key of the feature flag in your experiment. + +### Terminal + +```shell +curl -v -L --header "Content-Type: application/json" -d ' { + "api_key": "", + "event": "$feature_flag_called", + "distinct_id": "distinct_id_of_your_user", + "properties": { + "$feature_flag": "feature-flag-key", + "$feature_flag_response": "variant-name" + } +}' https://us.i.posthog.com/i/v0/e/ +``` + +### Python + +```python +import requests +import json + +url = "https://us.i.posthog.com/i/v0/e/" +headers = { + "Content-Type": "application/json" +} +payload = { + "api_key": "", + "event": "feature_flag_called", + "distinct_id": "distinct_id_of_your_user", + "properties": { + "$feature_flag": "feature-flag-key", + "$feature_flag_response": "variant-name" + } +} +response = requests.post(url, headers=headers, data=json.dumps(payload)) +print(response) +``` + +### Advanced: Overriding server properties + +Sometimes, you may want to evaluate feature flags using [person properties](https://posthog.com/docs/product-analytics/person-properties.md), [groups](https://posthog.com/docs/product-analytics/group-analytics.md), or group properties that haven't been ingested yet, or were set incorrectly earlier. + +You can provide properties to evaluate the flag with by using the `person properties`, `groups`, and `group properties` arguments. PostHog will then use these values to evaluate the flag, instead of any properties currently stored on your PostHog server. + +For example: + +### Terminal + +```shell +curl -v -L --header "Content-Type: application/json" -d ' { + "api_key": "", + "distinct_id": "distinct_id_of_your_user", + "groups" : { # Required only for group-based feature flags + "group_type": "group_id" # Replace "group_type" with the name of your group type. Replace "group_id" with the id of your group. + }, + "person_properties": {"": ""}, # Optional. Include any properties used to calculate the value of the feature flag. + "group_properties": {"group type": {"":""}} # Optional. Include any properties used to calculate the value of the feature flag. +}' https://us.i.posthog.com/flags?v=2 +``` + +### Python + +```python +import requests +import json + +url = "https://us.i.posthog.com/flags?v=2" +headers = { + "Content-Type": "application/json" +} +payload = { + "api_key": "", + "distinct_id": "distinct_id_of_your_user", + "groups" : { # Required only for group-based feature flags + "group_type": "group_id" # Replace "group_type" with the name of your group type. Replace "group_id" with the id of your group. + }, + "person_properties": {"": ""}, # Optional. Include any properties used to calculate the value of the feature flag. + "group_properties": {"group type": {"":""}} # Optional. Include any properties used to calculate the value of the feature flag. +} +response = requests.post(url, headers=headers, data=json.dumps(payload)) +print(response.json()) +``` + +### Overriding GeoIP properties + +By default, a user's GeoIP properties are set using the IP address they use to capture events on the frontend. You may want to override the these properties when evaluating feature flags. A common reason to do this is when you're not using PostHog on your frontend, so the user has no GeoIP properties. + +To override the GeoIP properties used to evaluate a feature flag, provide an IP address in the `HTTP_X_FORWARDED_FOR` when making your `/flags` request: + +### Terminal + +```shell +curl -v -L \ +--header "Content-Type: application/json" \ +--header "HTTP_X_FORWARDED_FOR: the_client_ip_address_to_use " \ +-d ' { + "api_key": "", + "distinct_id": "distinct_id_of_your_user" +}' https://us.i.posthog.com/flags?v=2 +``` + +### Python + +```python +import requests +import json + +url = "https://us.i.posthog.com/flags?v=2" +headers = { + "Content-Type": "application/json", + "HTTP_X_FORWARDED_FOR": "the_client_ip_address_to_use" +} +payload = { + "api_key": "", + "distinct_id": "distinct_id_of_your_user" +} +response = requests.post(url, headers=headers, data=json.dumps(payload)) +print(response.json()) +``` + +The list of properties that this overrides: + +1. `$geoip_city_name` +2. `$geoip_country_name` +3. `$geoip_country_code` +4. `$geoip_continent_name` +5. `$geoip_continent_code` +6. `$geoip_postal_code` +7. `$geoip_time_zone` diff --git a/context/docs-snapshots/legacy/feature-flags/android.md b/context/docs-snapshots/legacy/feature-flags/android.md new file mode 100644 index 000000000..30e03beaf --- /dev/null +++ b/context/docs-snapshots/legacy/feature-flags/android.md @@ -0,0 +1,158 @@ +> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt + +# Android Feature Flags installation + +Canonical URL: https://posthog.com/docs/feature-flags/installation/android + +> **Cloud region:** This page uses US Cloud hosts. For an EU Cloud project, use `https://eu.i.posthog.com` instead of `https://us.i.posthog.com` (ingestion host). + +## On this page + +- [Install with the wizard](#install-with-the-wizard) +- [Install the dependency](#install-the-dependency) +- [Configure PostHog](#configure-posthog) +- [Send events](#send-events) +- [Evaluate boolean feature flags](#evaluate-boolean-feature-flags) +- [Evaluate multivariate feature flags](#evaluate-multivariate-feature-flags) +- [Running experiments](#running-experiments) +- [Next steps](#next-steps) + +## Install with the wizard + +Run this command in your project directory to add PostHog to your Android project. The wizard detects your framework, installs the SDK, and sets up your first events. + +`npx @posthog/wizard` + +Or set it up manually by following the rest of this guide. + +1. 1 + + ## Install the dependency + + Required + + Add the PostHog Android SDK to your `build.gradle` dependencies: + + build.gradle + + ```kotlin + dependencies { + implementation("com.posthog:posthog-android:3.+") + } + ``` + +2. 2 + + ## Configure PostHog + + Required + + Initialize PostHog in your Application class: + + SampleApp.kt + + ```kotlin + class SampleApp : Application() { + + companion object { + const val POSTHOG_PROJECT_TOKEN = "" + const val POSTHOG_HOST = "https://us.i.posthog.com" + } + + override fun onCreate() { + super.onCreate() + + // Create a PostHog Config with the given project token and host + val config = PostHogAndroidConfig( + apiKey = POSTHOG_PROJECT_TOKEN, + host = POSTHOG_HOST + ) + + // Setup PostHog with the given Context and Config + PostHogAndroid.setup(this, config) + } + } + ``` + +3. 3 + + ## Send events + + Recommended + + Once installed, PostHog will automatically start capturing events. You can also manually send events to test your integration: + + Kotlin + + ```kotlin + import com.posthog.PostHog + + PostHog.capture( + event = "button_clicked", + properties = mapOf( + "button_name" to "signup" + ) + ) + ``` + +4. 4 + + ## Evaluate boolean feature flags + + Required + + Check if a feature flag is enabled: + + Kotlin + + ```kotlin + val isMyFlagEnabled = PostHog.isFeatureEnabled("flag-key") + if (isMyFlagEnabled) { + // Do something differently for this user + // Optional: fetch the payload + val matchedFlagPayload = PostHog.getFeatureFlagResult("flag-key")?.payload + } + ``` + +5. 5 + + ## Evaluate multivariate feature flags + + Optional + + For multivariate flags, check which variant the user has been assigned: + + Kotlin + + ```kotlin + val enabledVariant = PostHog.getFeatureFlag("flag-key") + if (enabledVariant == "variant-key") { // replace 'variant-key' with the key of your variant + // Do something differently for this user + // Optional: fetch the payload + val matchedFlagPayload = PostHog.getFeatureFlagResult("flag-key")?.payload + } + ``` + +6. 6 + + ## Running experiments + + Optional + + Experiments run on top of our feature flags. Once you've implemented the flag in your code, you run an experiment by creating a new experiment in the PostHog dashboard. + +7. 7 + + ## Next steps + + Recommended + + Now that you're evaluating flags, continue with the resources below to learn what else Feature Flags enables within the PostHog platform. + + | Resource | Description | + | --- | --- | + | [Creating a feature flag](https://posthog.com/docs/feature-flags/creating-feature-flags.md) | How to create a feature flag in PostHog | + | [Adding feature flag code](https://posthog.com/docs/feature-flags/adding-feature-flag-code.md) | How to check flags in your code for all platforms | + | [Framework-specific guides](https://posthog.com/docs/feature-flags/tutorials.md#framework-guides) | Setup guides for React Native, Next.js, Flutter, and other frameworks | + | [How to do a phased rollout](https://posthog.com/tutorials/phased-rollout.md) | Gradually roll out features to minimize risk | + | [More tutorials](https://posthog.com/docs/feature-flags/tutorials.md) | Other real-world examples and use cases | diff --git a/context/skills/feature-flags/config.yaml b/context/skills/feature-flags/config.yaml index cc0a6704e..173c73eaa 100644 --- a/context/skills/feature-flags/config.yaml +++ b/context/skills/feature-flags/config.yaml @@ -132,7 +132,9 @@ variants: display_name: Android tags: [android, java] docs_urls: - - https://posthog.com/docs/feature-flags/installation/android.md + - context/docs-snapshots/legacy/feature-flags/android.md + shared_docs: + - context/docs-snapshots/legacy/feature-flags/adding-feature-flag-code.md - id: ios display_name: iOS diff --git a/context/skills/integration-v2/feature-flags-step/config.yaml b/context/skills/integration-v2/feature-flags-step/config.yaml index 5526a4245..a76d6d941 100644 --- a/context/skills/integration-v2/feature-flags-step/config.yaml +++ b/context/skills/integration-v2/feature-flags-step/config.yaml @@ -261,7 +261,9 @@ variants: - java - kotlin docs_urls: - - https://posthog.com/docs/feature-flags/installation/android.md + - context/docs-snapshots/legacy/feature-flags/android.md + shared_docs: + - context/docs-snapshots/legacy/feature-flags/adding-feature-flag-code.md - id: sveltekit framework: sveltekit display_name: SvelteKit diff --git a/context/skills/omnibus/instrument-feature-flags/config.yaml b/context/skills/omnibus/instrument-feature-flags/config.yaml index 8bbbb610e..1e8a9142c 100644 --- a/context/skills/omnibus/instrument-feature-flags/config.yaml +++ b/context/skills/omnibus/instrument-feature-flags/config.yaml @@ -29,7 +29,7 @@ variants: - https://posthog.com/docs/feature-flags/installation/dotnet.md - https://posthog.com/docs/libraries/dotnet.md - https://posthog.com/docs/feature-flags/installation/elixir.md - - https://posthog.com/docs/feature-flags/installation/android.md + - context/docs-snapshots/legacy/feature-flags/android.md - https://posthog.com/docs/feature-flags/installation/ios.md - context/docs-snapshots/legacy/usage.md - https://posthog.com/docs/feature-flags/installation/flutter.md diff --git a/scripts/lib/skill-generator.js b/scripts/lib/skill-generator.js index ea24b2fd0..069d2ecf2 100644 --- a/scripts/lib/skill-generator.js +++ b/scripts/lib/skill-generator.js @@ -312,7 +312,7 @@ function expandSkillGroups(config, configDir) { : baseTemplate; // Support per-variation shared_docs (merged with base) - const sharedDocs = [...baseSharedDocs, ...(variation.shared_docs || [])]; + const sharedDocs = mergeSharedDocs(baseSharedDocs, variation.shared_docs || []); // Skill ID: {compositeKey-dashed}-{shortId}, dropping the "-all" suffix const skillId = variation.id === 'all' @@ -518,6 +518,19 @@ async function fetchDoc(url) { throw lastError; } +/** + * A variant's shared doc replaces the group's one that writes the same + * reference file, in place, so a legacy variant can read a snapshot of a page + * the other variants keep reading live. Any other variant doc is appended. + */ +function mergeSharedDocs(baseDocs, variantDocs) { + const nameOf = (entry) => urlToFilename(typeof entry === 'string' ? entry : entry.url); + const byName = new Map(variantDocs.map(entry => [nameOf(entry), entry])); + const merged = baseDocs.map(entry => byName.get(nameOf(entry)) ?? entry); + const baseNames = new Set(baseDocs.map(nameOf)); + return [...merged, ...variantDocs.filter(entry => !baseNames.has(nameOf(entry)))]; +} + /** A `docs_urls` entry without a scheme is a file in this repo (a snapshot), not a page to fetch. */ function isLocalDoc(entry) { return !/^https?:\/\//.test(entry); diff --git a/scripts/lib/tests/doc-snapshots.test.js b/scripts/lib/tests/doc-snapshots.test.js index dd4b24766..0f3fc7cbc 100644 --- a/scripts/lib/tests/doc-snapshots.test.js +++ b/scripts/lib/tests/doc-snapshots.test.js @@ -3,7 +3,7 @@ import fs from 'fs'; import os from 'os'; import path from 'path'; import yaml from 'js-yaml'; -import { loadDoc } from '../skill-generator.js'; +import { loadDoc, expandSkillGroups } from '../skill-generator.js'; const repoRoot = path.resolve(import.meta.dirname, '..', '..', '..'); @@ -75,6 +75,7 @@ describe('the legacy SDK pages are read from the snapshots everywhere', () => { 'https://posthog.com/docs/libraries/flutter.md', 'https://posthog.com/docs/libraries/django.md', 'https://posthog.com/docs/libraries/flask.md', + 'https://posthog.com/docs/feature-flags/installation/android.md', ]; // Those pages move to the capture v1 majors on release day; a skill fetching one live would flip with them. @@ -96,3 +97,35 @@ describe('a snapshot keeps its own file name', async () => { expect(urlToFilename('https://posthog.com/docs/libraries/ios/usage.md')).toBe('usage.md'); }); }); + +describe('a variant shared doc', () => { + const LIVE_FLAGS = 'https://posthog.com/docs/feature-flags/adding-feature-flag-code.md'; + const SNAPSHOT_FLAGS = 'context/docs-snapshots/legacy/feature-flags/adding-feature-flag-code.md'; + const BEST = 'https://posthog.com/docs/feature-flags/best-practices.md'; + + it('replaces the group one with the same file name, in place', () => { + const [legacy, other] = expandSkillGroups({ + flags: { + shared_docs: [LIVE_FLAGS, BEST], + variants: [ + { id: 'legacy', display_name: 'Legacy', shared_docs: [SNAPSHOT_FLAGS, 'context/extra.md'] }, + { id: 'other', display_name: 'Other' }, + ], + }, + }, repoRoot); + expect(legacy._sharedDocs).toEqual([SNAPSHOT_FLAGS, BEST, 'context/extra.md']); + expect(other._sharedDocs).toEqual([LIVE_FLAGS, BEST]); + }); + + // The live page moves to posthog-android 4.0 on release day; the Android variants install 3.x. + it('gives the Android flag variants the 3.x flag code page', () => { + for (const config of ['feature-flags', 'integration-v2/feature-flags-step']) { + const file = path.join(repoRoot, 'context', 'skills', config, 'config.yaml'); + const group = yaml.load(fs.readFileSync(file, 'utf8')); + const skills = expandSkillGroups({ [config]: group }, path.join(repoRoot, 'context')); + const android = skills.find(skill => skill._shortId === 'android'); + expect(android._sharedDocs, config).toContain(SNAPSHOT_FLAGS); + expect(android._sharedDocs, config).not.toContain(LIVE_FLAGS); + } + }); +}); From 851d4eda8e92d42268a82dcb92ddded2a55a8b3b Mon Sep 17 00:00:00 2001 From: Anna Garcia <11654201+turnipdabeets@users.noreply.github.com> Date: Thu, 5 Nov 2026 18:04:19 -0500 Subject: [PATCH 2/3] chore: snapshot the iOS 3.x feature flag, error tracking and logs docs (#478) * chore(skills): snapshot the 3.x iOS flag, error tracking and logs pages posthog-ios 4.0 moves the iOS install snippets to SPM `from: "4.0.0"` and drops CocoaPods (posthog.com#21807, posthog#129618), and changes the iOS section of the flag code page. The iOS variants install 3.x, so they read copies taken while the pages still describe it. Co-Authored-By: Claude Opus 5.5 * docs: name the logs snapshot's 3.59.3 pin in the README --------- Co-authored-by: Claude Opus 5.5 --- context/docs-snapshots/legacy/README.md | 10 + .../legacy/error-tracking/ios.md | 270 +++++++++++++++++ .../legacy/feature-flags/ios.md | 154 ++++++++++ .../legacy/logs-installation/ios.md | 284 ++++++++++++++++++ context/skills/error-tracking/config.yaml | 2 +- context/skills/feature-flags/config.yaml | 5 +- .../error-tracking-step/config.yaml | 2 +- .../feature-flags-step/config.yaml | 4 +- context/skills/logs/config.yaml | 2 +- .../instrument-error-tracking/config.yaml | 2 +- .../instrument-feature-flags/config.yaml | 2 +- .../omnibus/instrument-logs/config.yaml | 2 +- scripts/lib/tests/doc-snapshots.test.js | 18 +- 13 files changed, 743 insertions(+), 14 deletions(-) create mode 100644 context/docs-snapshots/legacy/error-tracking/ios.md create mode 100644 context/docs-snapshots/legacy/feature-flags/ios.md create mode 100644 context/docs-snapshots/legacy/logs-installation/ios.md diff --git a/context/docs-snapshots/legacy/README.md b/context/docs-snapshots/legacy/README.md index 5a839159b..d211c3f25 100644 --- a/context/docs-snapshots/legacy/README.md +++ b/context/docs-snapshots/legacy/README.md @@ -17,6 +17,13 @@ taken on 2026-11-04 while they still described posthog-android 3.x. The variant keeps reading live: a variant's own `shared_docs` entry replaces the group's one with the same file name. +The iOS pages in `feature-flags/`, `error-tracking/` and `logs-installation/` +were taken on 2026-11-05 while they still described posthog-ios 3.x +(CocoaPods, `from: "3.56.0"`, `"3.59.3"` for logs). The iOS flag variants also read the +`adding-feature-flag-code` snapshot, which still has the 3.x +`reloadFeatureFlags` block and the `didReceiveFeatureFlags` fallback. The logs +folder isn't named `logs/` because `.gitignore` ignores that name. + | File | Source | | --- | --- | | `python.md` | https://posthog.com/docs/libraries/python.md | @@ -34,3 +41,6 @@ group's one with the same file name. | `flask.md` | https://posthog.com/docs/libraries/flask.md | | `feature-flags/android.md` | https://posthog.com/docs/feature-flags/installation/android.md | | `feature-flags/adding-feature-flag-code.md` | https://posthog.com/docs/feature-flags/adding-feature-flag-code.md | +| `feature-flags/ios.md` | https://posthog.com/docs/feature-flags/installation/ios.md | +| `error-tracking/ios.md` | https://posthog.com/docs/error-tracking/installation/ios.md | +| `logs-installation/ios.md` | https://posthog.com/docs/logs/installation/ios.md | diff --git a/context/docs-snapshots/legacy/error-tracking/ios.md b/context/docs-snapshots/legacy/error-tracking/ios.md new file mode 100644 index 000000000..ceadcb2bf --- /dev/null +++ b/context/docs-snapshots/legacy/error-tracking/ios.md @@ -0,0 +1,270 @@ +> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt + +# iOS Error Tracking installation + +Canonical URL: https://posthog.com/docs/error-tracking/installation/ios + +> **Cloud region:** This page uses US Cloud hosts. For an EU Cloud project, use `https://eu.i.posthog.com` instead of `https://us.i.posthog.com` (ingestion host), and use `https://eu.posthog.com` instead of `https://app.posthog.com` (app host for links). + +## On this page + +- [Install with the wizard](#install-with-the-wizard) +- [Install dependency](#install-dependency) +- [Configure PostHog](#configure-posthog) +- [Send events](#send-events) +- [Set up exception autocapture](#set-up-exception-autocapture) +- [Manually capture exceptions](#manually-capture-exceptions) +- [Configure in-app frames](#configure-in-app-frames) +- [Verify error tracking](#verify-error-tracking) +- [Upload dSYMs](#upload-dsyms) + +## Install with the wizard + +Run this command in your project directory to add PostHog to your iOS project. The wizard detects your framework, installs the SDK, and sets up your first events. + +`npx @posthog/wizard` + +Or set it up manually by following the rest of this guide. + +1. 1 + + ## Install dependency + + Required + + Install via Swift Package Manager: + + Package.swift + + ```swift + dependencies: [ + .package(url: "https://github.com/PostHog/posthog-ios.git", from: "3.56.0") + ] + ``` + + Or add PostHog to your Podfile: + + Podfile + + ```ruby + pod "PostHog", "~> 3.56" + ``` + +2. 2 + + ## Configure PostHog + + Required + + Initialize PostHog in your AppDelegate: + + AppDelegate.swift + + ```swift + import Foundation + import PostHog + import UIKit + + class AppDelegate: NSObject, UIApplicationDelegate { + func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { + let POSTHOG_PROJECT_TOKEN = "" + let POSTHOG_HOST = "https://us.i.posthog.com" + + let config = PostHogConfig(projectToken: POSTHOG_PROJECT_TOKEN, host: POSTHOG_HOST) + PostHogSDK.shared.setup(config) + + return true + } + } + ``` + +3. 3 + + ## Send events + + Recommended + + Once installed, PostHog will automatically start capturing events. You can also manually send events to test your integration: + + Swift + + ```swift + PostHogSDK.shared.capture("button_clicked", properties: ["button_name": "signup"]) + ``` + +4. 4 + + ## Set up exception autocapture + + Recommended + + **Remote configuration** + + Exception autocapture can also be managed remotely via the [error tracking settings](https://app.posthog.com/settings/project-error-tracking#exception-autocapture). + + **Platform support** + + Exception autocapture is available on **iOS, macOS, and tvOS** only. It is not available on watchOS or visionOS due to platform limitations. + + You can still capture events manually on all platforms, including visionOS. + + You can autocapture exceptions by setting the `errorTrackingConfig.autoCapture` argument to `true` when initializing the PostHog SDK. + + Swift + + ```swift + import PostHog + + let config = PostHogConfig( + projectToken: "", + host: "https://us.i.posthog.com" + ) + config.errorTrackingConfig.autoCapture = true + + PostHogSDK.shared.setup(config) + ``` + + When enabled, this automatically captures `$exception` events for: + + - **Mach exceptions** (e.g., `EXC_BAD_ACCESS`, `EXC_CRASH`) + - **POSIX signals** (e.g., `SIGSEGV`, `SIGABRT`, `SIGBUS`) + - **Uncaught NSExceptions** + + Crashes are persisted to disk and sent as `$exception` events with level "fatal" on the next app launch. + +5. 5 + + ## Manually capture exceptions + + Optional + + ### Swift Error handling + + You can manually capture exceptions using the `captureException` method: + + Swift + + ```swift + import PostHog + + do { + try FileManager.default.removeItem(at: badFileUrl) + } catch { + PostHogSDK.shared.captureException(error) + } + ``` + + ### Objective-C NSException handling + + For Objective-C code that uses NSException: + + Objective-C + + ```objc + @import PostHog; + + @try { + [self riskyOperation]; + } @catch (NSException *exception) { + [[PostHogSDK shared] captureExceptionWithNSException:exception properties:nil]; + } + ``` + + ### Adding custom properties + + You can add custom properties to help with debugging, grouping, and analysis: + + Swift + + ```swift + do { + try performNetworkRequest() + } catch { + PostHogSDK.shared.captureException(error, properties: [ + "endpoint": "/api/users", + "retry_count": 3 + ]) + } + ``` + + This is helpful if you've built your own error handling logic or want to capture exceptions that are handled by your application code. + +6. 6 + + ## Configure in-app frames + + Optional + + By default, PostHog automatically marks your app's code as "in-app" in stack traces to help you focus on your code rather than system frameworks. + + You can customize this behavior with `errorTrackingConfig`: + + Swift + + ```swift + import PostHog + + let config = PostHogConfig( + projectToken: "", + host: "https://us.i.posthog.com" + ) + + // Mark additional packages as in-app + config.errorTrackingConfig.inAppIncludes = [ + "MySharedFramework", + "MyUtilityLib" + ] + + // Exclude specific packages from being marked as in-app + config.errorTrackingConfig.inAppExcludes = [ + "Alamofire", + "SDWebImage" + ] + + // Control default behavior for unknown packages + config.errorTrackingConfig.inAppByDefault = true // default + + PostHogSDK.shared.setup(config) + ``` + + **Configuration options:** + + | Option | Description | + | --- | --- | + | `inAppIncludes` | List of package/bundle identifiers to mark as in-app (takes precedence over excludes) | + | `inAppExcludes` | List of package/bundle identifiers to exclude from in-app | + | `inAppByDefault` | Whether frames are considered in-app by default when origin cannot be determined | + + **Default behavior:** + + - Your app's bundle identifier and executable name are automatically included + - System frameworks (Foundation, UIKit, etc.) are automatically excluded + +7. ## Verify error tracking + + Recommended + + *Confirm events are being sent to PostHog* + + Before proceeding, let's make sure exception events are being captured and sent to PostHog. You should see events appear in the activity feed. + + ![Activity feed with events](https://res.cloudinary.com/dmukukwp6/image/upload/SCR_20250729_ouxl_f788dd8cd2.png) + + [Check for exceptions in PostHog](https://app.posthog.com/activity/explore) + +8. 7 + + ## Upload dSYMs + + Required + + Great, you're capturing exceptions! The next step is to upload dSYM files so PostHog can symbolicate your crash reports and generate accurate stack traces. + + Let's continue to the next section. + + [Upload dSYMs](https://posthog.com/docs/error-tracking/upload-source-maps/ios.md) + +## Limitations: + +- System symbols and frames are not symbolicated (UIKit, Foundation, etc.) ([issue](https://github.com/PostHog/posthog/issues/50614)). +- Swift crashes appear as `SIGTRAP` without the actual error message ([issue](https://github.com/PostHog/posthog-ios/issues/522)). diff --git a/context/docs-snapshots/legacy/feature-flags/ios.md b/context/docs-snapshots/legacy/feature-flags/ios.md new file mode 100644 index 000000000..2c209d023 --- /dev/null +++ b/context/docs-snapshots/legacy/feature-flags/ios.md @@ -0,0 +1,154 @@ +> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt + +# iOS Feature Flags installation + +Canonical URL: https://posthog.com/docs/feature-flags/installation/ios + +> **Cloud region:** This page uses US Cloud hosts. For an EU Cloud project, use `https://eu.i.posthog.com` instead of `https://us.i.posthog.com` (ingestion host). + +## On this page + +- [Install with the wizard](#install-with-the-wizard) +- [Install dependency](#install-dependency) +- [Configure PostHog](#configure-posthog) +- [Send events](#send-events) +- [Evaluate boolean feature flags](#evaluate-boolean-feature-flags) +- [Evaluate multivariate feature flags](#evaluate-multivariate-feature-flags) +- [Running experiments](#running-experiments) +- [Next steps](#next-steps) + +## Install with the wizard + +Run this command in your project directory to add PostHog to your iOS project. The wizard detects your framework, installs the SDK, and sets up your first events. + +`npx @posthog/wizard` + +Or set it up manually by following the rest of this guide. + +1. 1 + + ## Install dependency + + Required + + Install via Swift Package Manager: + + Package.swift + + ```swift + dependencies: [ + .package(url: "https://github.com/PostHog/posthog-ios.git", from: "3.56.0") + ] + ``` + + Or add PostHog to your Podfile: + + Podfile + + ```ruby + pod "PostHog", "~> 3.56" + ``` + +2. 2 + + ## Configure PostHog + + Required + + Initialize PostHog in your AppDelegate: + + AppDelegate.swift + + ```swift + import Foundation + import PostHog + import UIKit + + class AppDelegate: NSObject, UIApplicationDelegate { + func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { + let POSTHOG_PROJECT_TOKEN = "" + let POSTHOG_HOST = "https://us.i.posthog.com" + + let config = PostHogConfig(projectToken: POSTHOG_PROJECT_TOKEN, host: POSTHOG_HOST) + PostHogSDK.shared.setup(config) + + return true + } + } + ``` + +3. 3 + + ## Send events + + Recommended + + Once installed, PostHog will automatically start capturing events. You can also manually send events to test your integration: + + Swift + + ```swift + PostHogSDK.shared.capture("button_clicked", properties: ["button_name": "signup"]) + ``` + +4. 4 + + ## Evaluate boolean feature flags + + Required + + Check if a feature flag is enabled: + + Swift + + ```swift + let isMyFlagEnabled = PostHogSDK.shared.isFeatureEnabled("flag-key") + if isMyFlagEnabled { + // Do something differently for this user + // Optional: fetch the payload + let matchedFlagPayload = PostHogSDK.shared.getFeatureFlagResult("flag-key")?.payload + } + ``` + +5. 5 + + ## Evaluate multivariate feature flags + + Optional + + For multivariate flags, check which variant the user has been assigned: + + Swift + + ```swift + let enabledVariant = PostHogSDK.shared.getFeatureFlag("flag-key") + if enabledVariant == "variant-key" { // replace 'variant-key' with the key of your variant + // Do something differently for this user + // Optional: fetch the payload + let matchedFlagPayload = PostHogSDK.shared.getFeatureFlagResult("flag-key")?.payload + } + ``` + +6. 6 + + ## Running experiments + + Optional + + Experiments run on top of our feature flags. Once you've implemented the flag in your code, you run an experiment by creating a new experiment in the PostHog dashboard. + +7. 7 + + ## Next steps + + Recommended + + Now that you're evaluating flags, continue with the resources below to learn what else Feature Flags enables within the PostHog platform. + + | Resource | Description | + | --- | --- | + | [Creating a feature flag](https://posthog.com/docs/feature-flags/creating-feature-flags.md) | How to create a feature flag in PostHog | + | [Adding feature flag code](https://posthog.com/docs/feature-flags/adding-feature-flag-code.md) | How to check flags in your code for all platforms | + | [Framework-specific guides](https://posthog.com/docs/feature-flags/tutorials.md#framework-guides) | Setup guides for React Native, Next.js, Flutter, and other frameworks | + | [How to do a phased rollout](https://posthog.com/tutorials/phased-rollout.md) | Gradually roll out features to minimize risk | + | [More tutorials](https://posthog.com/docs/feature-flags/tutorials.md) | Other real-world examples and use cases | diff --git a/context/docs-snapshots/legacy/logs-installation/ios.md b/context/docs-snapshots/legacy/logs-installation/ios.md new file mode 100644 index 000000000..0af9c7df8 --- /dev/null +++ b/context/docs-snapshots/legacy/logs-installation/ios.md @@ -0,0 +1,284 @@ +> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt + +# iOS Logs installation + +Canonical URL: https://posthog.com/docs/logs/installation/ios + +> **Cloud region:** This page uses US Cloud hosts. For an EU Cloud project, use `https://eu.posthog.com` instead of `https://app.posthog.com` (app host for links). + +## On this page + +- [Install posthog-ios](#install-posthog-ios) +- [Configure logs in your PostHogConfig](#configure-logs-in-your-posthogconfig) +- [Capture logs](#capture-logs) +- [Test your setup](#test-your-setup) +- [Tune buffering, rate cap, and resource attributes](#tune-buffering-rate-cap-and-resource-attributes) +- [Filter or redact with beforeSend](#filter-or-redact-with-beforesend) +- [Next steps](#next-steps) + +The PostHog iOS SDK has built-in support for capturing structured Logs from iOS, macOS, tvOS, watchOS, and visionOS apps. The SDK handles OTLP encoding, batching, on-disk persistence across app restarts, and lifecycle integration. You just call `PostHogSDK.shared.captureLog(...)` or `PostHogSDK.shared.logger?.{trace,debug,info,warn,error,fatal}(...)`. + +> **Manual capture only.** Logs are emitted by your code. The SDK does not autocapture system log streams (`os_log`, `Logger`, `print`). + +> **Minimum version:** `posthog-ios@3.58.0` or later. Run `pod update PostHog` (CocoaPods) or update the package version in Xcode (Swift Package Manager). + +1. 1 + + ## Install posthog-ios + + Required + + If you haven't installed `posthog-ios` yet, follow the steps below. For full details, see the [iOS SDK guide](https://posthog.com/docs/libraries/ios.md). + + PostHog is available through [CocoaPods](http://cocoapods.org) or you can add it as a Swift Package Manager based dependency. + + ### CocoaPods + + Podfile + + ```ruby + pod "PostHog", "~> 3.59.3" + ``` + + ### Swift Package Manager + + Add PostHog as a dependency in your Xcode project "Package Dependencies" and select the project target for your app, as appropriate. + + For a Swift Package Manager based project, add PostHog as a dependency in your `Package.swift` file's Package dependencies section: + + Package.swift + + ```swift + dependencies: [ + .package(url: "https://github.com/PostHog/posthog-ios.git", from: "3.59.3") + ], + ``` + + and then as a dependency for the Package target utilizing PostHog: + + Package.swift + + ```swift + .target( + name: "myApp", + dependencies: [.product(name: "PostHog", package: "posthog-ios")]), + ``` + + ### Configuration + + Configuration is done through the `PostHogConfig` object. Here's a basic configuration example to get you started. + + You can find more advanced configuration options in the [configuration page](https://posthog.com/docs/libraries/ios/configuration.md). + + ## UIKit + + ```swift + import Foundation + import PostHog + import UIKit + + class AppDelegate: NSObject, UIApplicationDelegate { + func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { + let POSTHOG_PROJECT_TOKEN = "" + // usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com' + let POSTHOG_HOST = "https://us.i.posthog.com" + + let config = PostHogConfig(projectToken: POSTHOG_PROJECT_TOKEN, host: POSTHOG_HOST) + PostHogSDK.shared.setup(config) + + return true + } + } + ``` + + ## SwiftUI + + ```swift + import SwiftUI + import PostHog + + @main + struct YourGreatApp: App { + + // Add PostHog to your app's initializer. + // If using UIApplicationDelegateAdaptor, see the UIKit tab. + + init() { + + let POSTHOG_PROJECT_TOKEN = "" + // usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com' + let POSTHOG_HOST = "https://us.i.posthog.com" + + let config = PostHogConfig(projectToken: POSTHOG_PROJECT_TOKEN, host: POSTHOG_HOST) + PostHogSDK.shared.setup(config) + + } + + var body: some Scene { + WindowGroup { + ContentView() + } + } + } + ``` + +2. 2 + + ## Configure logs in your PostHogConfig + + Required + + Configure Logs through `config.logs` before calling `setup(_:)`. All fields are optional; defaults are tuned for mobile (cellular bandwidth, battery, OS lifecycle). + + ```swift + import PostHog + + let config = PostHogConfig(projectToken: "", host: "https://us.i.posthog.com") + config.logs.serviceName = "my-app" // OTLP service.name – shown in the Logs UI + config.logs.environment = "production" // OTLP deployment.environment + config.logs.serviceVersion = "1.2.3" // OTLP service.version + + PostHogSDK.shared.setup(config) + ``` + + These resource attributes are captured at `setup(_:)` and apply to every batch. Mutating `config.logs` after `setup` has no effect. + +3. 3 + + ## Capture logs + + Required + + Use `PostHogSDK.shared.logger` for the per-level convenience API, or `PostHogSDK.shared.captureLog` for full control over level, attributes, and trace context. + + ```swift + // Per-level convenience methods – Optional, since logger is created at setup + PostHogSDK.shared.logger?.info("checkout completed", attributes: ["order_id": "ord_789", "amount_cents": 4999]) + PostHogSDK.shared.logger?.warn("payment retry", attributes: ["attempt": 2]) + PostHogSDK.shared.logger?.error("payment failed", attributes: ["code": "E001"]) + + // Lower-level API for custom severity / trace context + PostHogSDK.shared.captureLog( + "checkout failed", + level: .error, + attributes: ["order_id": "ord_789", "step": "auth"], + traceId: "4bf92f3577b34da6a3ce929d0e0e4736", // optional W3C trace context (32 hex chars) + spanId: "00f067aa0ba902b7" // optional W3C span (16 hex chars) + ) + ``` + + Available severity levels: `.trace`, `.debug`, `.info`, `.warn`, `.error`, `.fatal`. + + Records are buffered, batched, persisted to disk, and flushed automatically – every 30 seconds, when the buffer hits the threshold, when the app moves to the background, or on `PostHogSDK.shared.flush()`. `flush()` drains events, Session Replay, and Logs together. + + Each record is automatically tagged with the current distinct ID, session ID, current screen, app foreground/background state, and active Feature Flags at the moment of capture. + +4. 4 + + ## Test your setup + + Recommended + + 1. Capture a test log from your app: + + ```swift + PostHogSDK.shared.logger?.info("hello from iOS") + PostHogSDK.shared.flush() + ``` + + 2. Open the [PostHog Logs UI](https://app.posthog.com/logs). + 3. Filter by `service.name = 'my-app'` (or whatever value you set above). + + You should see your record arrive within a few seconds. + + [View your Logs in PostHog](https://app.posthog.com/logs) + +5. 5 + + ## Tune buffering, rate cap, and resource attributes + + Optional + + The `logs` config has knobs for high-volume apps: + + ```swift + let config = PostHogConfig(projectToken: "") + config.logs.serviceName = "my-app" + config.logs.flushIntervalSeconds = 5 // default 30 + config.logs.maxBufferSize = 200 // default 1000 + config.logs.maxBatchSize = 50 // default 50 + config.logs.flushAt = 20 // default 20 + config.logs.rateCapMaxLogs = 5000 // default 500 + config.logs.rateCapWindowSeconds = 60 // default 10 + config.logs.resourceAttributes = ["host.name": "device-01"] + PostHogSDK.shared.setup(config) + ``` + + Full configuration reference: + + | Field | Default | What it does | + | --- | --- | --- | + | `serviceName` | bundle identifier | OTLP `service.name` resource attribute | + | `serviceVersion` | `CFBundleShortVersionString` | OTLP `service.version` resource attribute | + | `environment` | `nil` | OTLP `deployment.environment` resource attribute | + | `resourceAttributes` | `[:]` | Extra OTLP resource attributes (SDK keys win on collision) | + | `flushIntervalSeconds` | `30` | Periodic flush interval | + | `flushAt` | `20` | Buffer threshold that triggers an automatic flush | + | `maxBatchSize` | `50` | Max records per outbound POST (halved on 413) | + | `maxBufferSize` | `1000` | Max records held on disk before FIFO eviction | + | `rateCapMaxLogs` | `500` | Max records per `rateCapWindowSeconds` window. Set to `0` to disable. | + | `rateCapWindowSeconds` | `10` | Rate-cap tumbling window length | + + All of the above are captured at `setup(_:)`; mutating them later has no effect. Defaults are tuned for cellular-aware mobile apps. Raise `rateCapMaxLogs` and `maxBufferSize` for high-volume scenarios. + +6. 6 + + ## Filter or redact with beforeSend + + Optional + + `beforeSend` runs synchronously before the rate cap, so dropped records don't consume the per-window budget. Use it for redaction, sampling, or filtering by level. Each block receives a mutable `PostHogLogRecord` and returns either the (possibly mutated) record or `nil` to drop it. + + ```swift + config.logs.setBeforeSend({ record in + // Drop debug logs in production + if record.level == .debug { return nil } + + // Redact secrets in the body + record.body = record.body.replacingOccurrences( + of: #"api_key=\S+"#, + with: "api_key=[REDACTED]", + options: .regularExpression + ) + return record + }) + ``` + + Pass an array (or a comma-separated list) of blocks to compose a chain – evaluated left-to-right. Returning `nil` from any block short-circuits and drops the record. Setting `record.body` to an empty string also drops the record. + + From Objective-C, wrap each closure in a `BoxedBeforeSendLogBlock`: + + ```objc + [posthogConfig.logs setBeforeSend:@[ + [[BoxedBeforeSendLogBlock alloc] initWithBlock:^PostHogLogRecord * _Nullable(PostHogLogRecord * record) { + return [record.body containsString:@"secret"] ? nil : record; + }] + ]]; + ``` + +8. ## Next steps + + Checkpoint + + *What you can do with your logs* + + | Action | Description | + | --- | --- | + | **[Why you need logs](https://posthog.com/docs/logs/basics.md)** | What logs show you that nothing else does | + | **[Search logs](https://posthog.com/docs/logs/search.md)** | Use the search interface to find specific log entries | + | **Filter by level** | Filter by `INFO`, `WARN`, `ERROR`, etc. | + | **[Link session replay](https://posthog.com/docs/logs/link-session-replay.md)** | Connect logs to users and session replays by passing `posthogDistinctId` and `sessionId` | + | **[Link logs to a person](https://posthog.com/docs/logs/link-person.md)** | Surface every log emitted on behalf of a user on their PostHog person profile | + | **[Logging best practices](https://posthog.com/docs/logs/best-practices.md)** | Learn what to log, how to structure logs, and patterns that make logs useful in production | + + [Troubleshoot common issues](https://posthog.com/docs/logs/troubleshooting.md) diff --git a/context/skills/error-tracking/config.yaml b/context/skills/error-tracking/config.yaml index 881973cec..094062c42 100644 --- a/context/skills/error-tracking/config.yaml +++ b/context/skills/error-tracking/config.yaml @@ -145,7 +145,7 @@ variants: display_name: iOS tags: [ios, swift] docs_urls: - - https://posthog.com/docs/error-tracking/installation/ios.md + - context/docs-snapshots/legacy/error-tracking/ios.md - id: android display_name: Android diff --git a/context/skills/feature-flags/config.yaml b/context/skills/feature-flags/config.yaml index 173c73eaa..ccac1dcb8 100644 --- a/context/skills/feature-flags/config.yaml +++ b/context/skills/feature-flags/config.yaml @@ -140,8 +140,11 @@ variants: display_name: iOS tags: [ios, swift] docs_urls: - - https://posthog.com/docs/feature-flags/installation/ios.md + - context/docs-snapshots/legacy/feature-flags/ios.md - context/docs-snapshots/legacy/usage.md + shared_docs: + - context/docs-snapshots/legacy/feature-flags/adding-feature-flag-code.md + - id: flutter display_name: Flutter tags: [flutter, dart] diff --git a/context/skills/integration-v2/error-tracking-step/config.yaml b/context/skills/integration-v2/error-tracking-step/config.yaml index dcda153ba..b13e7ae82 100644 --- a/context/skills/integration-v2/error-tracking-step/config.yaml +++ b/context/skills/integration-v2/error-tracking-step/config.yaml @@ -327,7 +327,7 @@ variants: - swiftui - xcodegen docs_urls: - - https://posthog.com/docs/error-tracking/installation/ios.md + - context/docs-snapshots/legacy/error-tracking/ios.md - context/docs-snapshots/legacy/ios.md - context/docs-snapshots/legacy/usage.md - context/docs-snapshots/legacy/configuration.md diff --git a/context/skills/integration-v2/feature-flags-step/config.yaml b/context/skills/integration-v2/feature-flags-step/config.yaml index a76d6d941..f2465281b 100644 --- a/context/skills/integration-v2/feature-flags-step/config.yaml +++ b/context/skills/integration-v2/feature-flags-step/config.yaml @@ -348,8 +348,10 @@ variants: - swiftui - xcodegen docs_urls: - - https://posthog.com/docs/feature-flags/installation/ios.md + - context/docs-snapshots/legacy/feature-flags/ios.md - context/docs-snapshots/legacy/usage.md + shared_docs: + - context/docs-snapshots/legacy/feature-flags/adding-feature-flag-code.md - id: flutter framework: flutter display_name: Flutter diff --git a/context/skills/logs/config.yaml b/context/skills/logs/config.yaml index 6b7178995..024246833 100644 --- a/context/skills/logs/config.yaml +++ b/context/skills/logs/config.yaml @@ -69,7 +69,7 @@ variants: display_name: iOS tags: [ios, swift] docs_urls: - - https://posthog.com/docs/logs/installation/ios.md + - context/docs-snapshots/legacy/logs-installation/ios.md - id: flutter display_name: Flutter diff --git a/context/skills/omnibus/instrument-error-tracking/config.yaml b/context/skills/omnibus/instrument-error-tracking/config.yaml index 2ce58cc41..23316c60b 100644 --- a/context/skills/omnibus/instrument-error-tracking/config.yaml +++ b/context/skills/omnibus/instrument-error-tracking/config.yaml @@ -36,6 +36,6 @@ variants: - https://posthog.com/docs/error-tracking/installation/nuxt-3-6.md - https://posthog.com/docs/error-tracking/installation/react-native.md - https://posthog.com/docs/error-tracking/installation/flutter.md - - https://posthog.com/docs/error-tracking/installation/ios.md + - context/docs-snapshots/legacy/error-tracking/ios.md - https://posthog.com/docs/error-tracking/installation/android.md - https://posthog.com/docs/error-tracking/installation/hono.md diff --git a/context/skills/omnibus/instrument-feature-flags/config.yaml b/context/skills/omnibus/instrument-feature-flags/config.yaml index 1e8a9142c..c9f5706c5 100644 --- a/context/skills/omnibus/instrument-feature-flags/config.yaml +++ b/context/skills/omnibus/instrument-feature-flags/config.yaml @@ -30,7 +30,7 @@ variants: - https://posthog.com/docs/libraries/dotnet.md - https://posthog.com/docs/feature-flags/installation/elixir.md - context/docs-snapshots/legacy/feature-flags/android.md - - https://posthog.com/docs/feature-flags/installation/ios.md + - context/docs-snapshots/legacy/feature-flags/ios.md - context/docs-snapshots/legacy/usage.md - https://posthog.com/docs/feature-flags/installation/flutter.md - https://posthog.com/docs/feature-flags/installation/api.md diff --git a/context/skills/omnibus/instrument-logs/config.yaml b/context/skills/omnibus/instrument-logs/config.yaml index 8bf61e0ff..1120976fd 100644 --- a/context/skills/omnibus/instrument-logs/config.yaml +++ b/context/skills/omnibus/instrument-logs/config.yaml @@ -24,6 +24,6 @@ variants: - https://posthog.com/docs/logs/installation/datadog.md - https://posthog.com/docs/logs/installation/android.md - https://posthog.com/docs/logs/installation/react-native.md - - https://posthog.com/docs/logs/installation/ios.md + - context/docs-snapshots/legacy/logs-installation/ios.md - https://posthog.com/docs/logs/installation/flutter.md - https://posthog.com/docs/logs/installation/other.md diff --git a/scripts/lib/tests/doc-snapshots.test.js b/scripts/lib/tests/doc-snapshots.test.js index 0f3fc7cbc..543a56922 100644 --- a/scripts/lib/tests/doc-snapshots.test.js +++ b/scripts/lib/tests/doc-snapshots.test.js @@ -76,6 +76,9 @@ describe('the legacy SDK pages are read from the snapshots everywhere', () => { 'https://posthog.com/docs/libraries/django.md', 'https://posthog.com/docs/libraries/flask.md', 'https://posthog.com/docs/feature-flags/installation/android.md', + 'https://posthog.com/docs/feature-flags/installation/ios.md', + 'https://posthog.com/docs/error-tracking/installation/ios.md', + 'https://posthog.com/docs/logs/installation/ios.md', ]; // Those pages move to the capture v1 majors on release day; a skill fetching one live would flip with them. @@ -117,15 +120,18 @@ describe('a variant shared doc', () => { expect(other._sharedDocs).toEqual([LIVE_FLAGS, BEST]); }); - // The live page moves to posthog-android 4.0 on release day; the Android variants install 3.x. - it('gives the Android flag variants the 3.x flag code page', () => { - for (const config of ['feature-flags', 'integration-v2/feature-flags-step']) { + // The live page moves to posthog-android 4.0 and posthog-ios 4.0 on release day; these variants install 3.x. + it.each([ + ['android', 'android'], + ['ios', 'swift'], + ])('gives the %s flag variants the 3.x flag code page', (standalone, step) => { + for (const [config, id] of [['feature-flags', standalone], ['integration-v2/feature-flags-step', step]]) { const file = path.join(repoRoot, 'context', 'skills', config, 'config.yaml'); const group = yaml.load(fs.readFileSync(file, 'utf8')); const skills = expandSkillGroups({ [config]: group }, path.join(repoRoot, 'context')); - const android = skills.find(skill => skill._shortId === 'android'); - expect(android._sharedDocs, config).toContain(SNAPSHOT_FLAGS); - expect(android._sharedDocs, config).not.toContain(LIVE_FLAGS); + const variant = skills.find(skill => skill._shortId === id); + expect(variant._sharedDocs, config).toContain(SNAPSHOT_FLAGS); + expect(variant._sharedDocs, config).not.toContain(LIVE_FLAGS); } }); }); From 6350639cf8049bdb2e52ce9525553911a11101cf Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Fri, 6 Nov 2026 14:00:48 -0500 Subject: [PATCH 3/3] chore(skills): snapshot the 3.x Android and 5.x Flutter error tracking, logs and flag pages The Android error tracking, logs and upload mappings pages and the Flutter feature flag, error tracking and logs install pages reuse the product analytics onboarding steps that the posthog-android 4.0 and posthog_flutter 6.0 onboarding changes rewrite. The variants install 3.x/5.x, so they read copies taken while the pages still describe those majors. --- context/docs-snapshots/legacy/README.md | 12 + .../legacy/error-tracking/android.md | 173 +++++++ .../legacy/error-tracking/flutter.md | 357 ++++++++++++++ .../legacy/feature-flags/flutter.md | 221 +++++++++ .../legacy/logs-installation/android.md | 213 ++++++++ .../legacy/logs-installation/flutter.md | 461 ++++++++++++++++++ .../legacy/upload-mappings/android.md | 159 ++++++ .../config.yaml | 4 +- context/skills/error-tracking/config.yaml | 4 +- context/skills/feature-flags/config.yaml | 2 +- .../error-tracking-step/config.yaml | 4 +- .../feature-flags-step/config.yaml | 2 +- context/skills/logs/config.yaml | 4 +- .../instrument-error-tracking/config.yaml | 4 +- .../instrument-feature-flags/config.yaml | 2 +- .../omnibus/instrument-logs/config.yaml | 4 +- scripts/lib/tests/doc-snapshots.test.js | 6 + .../error-tracking-upload-source-maps.test.js | 2 +- 18 files changed, 1618 insertions(+), 16 deletions(-) create mode 100644 context/docs-snapshots/legacy/error-tracking/android.md create mode 100644 context/docs-snapshots/legacy/error-tracking/flutter.md create mode 100644 context/docs-snapshots/legacy/feature-flags/flutter.md create mode 100644 context/docs-snapshots/legacy/logs-installation/android.md create mode 100644 context/docs-snapshots/legacy/logs-installation/flutter.md create mode 100644 context/docs-snapshots/legacy/upload-mappings/android.md diff --git a/context/docs-snapshots/legacy/README.md b/context/docs-snapshots/legacy/README.md index d211c3f25..7fa1b1616 100644 --- a/context/docs-snapshots/legacy/README.md +++ b/context/docs-snapshots/legacy/README.md @@ -24,6 +24,12 @@ were taken on 2026-11-05 while they still described posthog-ios 3.x `reloadFeatureFlags` block and the `didReceiveFeatureFlags` fallback. The logs folder isn't named `logs/` because `.gitignore` ignores that name. +The Android error tracking, logs and upload mappings pages and the Flutter +feature flag, error tracking and logs install pages were taken on 2026-11-06 +while they still described posthog-android 3.x (`posthog-android:3.+`, `apiKey`) +and posthog_flutter 5.x (`^5.x`). They reuse the product analytics onboarding +steps that the 4.0 and 6.0 onboarding changes rewrite. + | File | Source | | --- | --- | | `python.md` | https://posthog.com/docs/libraries/python.md | @@ -44,3 +50,9 @@ folder isn't named `logs/` because `.gitignore` ignores that name. | `feature-flags/ios.md` | https://posthog.com/docs/feature-flags/installation/ios.md | | `error-tracking/ios.md` | https://posthog.com/docs/error-tracking/installation/ios.md | | `logs-installation/ios.md` | https://posthog.com/docs/logs/installation/ios.md | +| `error-tracking/android.md` | https://posthog.com/docs/error-tracking/installation/android.md | +| `logs-installation/android.md` | https://posthog.com/docs/logs/installation/android.md | +| `upload-mappings/android.md` | https://posthog.com/docs/error-tracking/upload-mappings/android.md | +| `feature-flags/flutter.md` | https://posthog.com/docs/feature-flags/installation/flutter.md | +| `error-tracking/flutter.md` | https://posthog.com/docs/error-tracking/installation/flutter.md | +| `logs-installation/flutter.md` | https://posthog.com/docs/logs/installation/flutter.md | diff --git a/context/docs-snapshots/legacy/error-tracking/android.md b/context/docs-snapshots/legacy/error-tracking/android.md new file mode 100644 index 000000000..f3a05e6ed --- /dev/null +++ b/context/docs-snapshots/legacy/error-tracking/android.md @@ -0,0 +1,173 @@ +> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt + +# Android Error Tracking installation + +Canonical URL: https://posthog.com/docs/error-tracking/installation/android + +> **Cloud region:** This page uses US Cloud hosts. For an EU Cloud project, use `https://eu.i.posthog.com` instead of `https://us.i.posthog.com` (ingestion host), and use `https://eu.posthog.com` instead of `https://app.posthog.com` (app host for links). + +## On this page + +- [Install with the wizard](#install-with-the-wizard) +- [Install the dependency](#install-the-dependency) +- [Configure PostHog](#configure-posthog) +- [Send events](#send-events) +- [Set up exception autocapture](#set-up-exception-autocapture) +- [Manually capture exceptions](#manually-capture-exceptions) +- [Verify error tracking](#verify-error-tracking) +- [Upload mapping files](#upload-mapping-files) + +## Install with the wizard + +Run this command in your project directory to add PostHog to your Android project. The wizard detects your framework, installs the SDK, and sets up your first events. + +`npx @posthog/wizard` + +Or set it up manually by following the rest of this guide. + +1. 1 + + ## Install the dependency + + Required + + Add the PostHog Android SDK to your `build.gradle` dependencies: + + build.gradle + + ```kotlin + dependencies { + implementation("com.posthog:posthog-android:3.+") + } + ``` + +2. 2 + + ## Configure PostHog + + Required + + Initialize PostHog in your Application class: + + SampleApp.kt + + ```kotlin + class SampleApp : Application() { + + companion object { + const val POSTHOG_PROJECT_TOKEN = "" + const val POSTHOG_HOST = "https://us.i.posthog.com" + } + + override fun onCreate() { + super.onCreate() + + // Create a PostHog Config with the given project token and host + val config = PostHogAndroidConfig( + apiKey = POSTHOG_PROJECT_TOKEN, + host = POSTHOG_HOST + ) + + // Setup PostHog with the given Context and Config + PostHogAndroid.setup(this, config) + } + } + ``` + +3. 3 + + ## Send events + + Recommended + + Once installed, PostHog will automatically start capturing events. You can also manually send events to test your integration: + + Kotlin + + ```kotlin + import com.posthog.PostHog + + PostHog.capture( + event = "button_clicked", + properties = mapOf( + "button_name" to "signup" + ) + ) + ``` + +4. 4 + + ## Set up exception autocapture + + Recommended + + **Client-side configuration only** + + Support for remote configuration in the [error tracking settings](https://app.posthog.com/settings/project-error-tracking#exception-autocapture) requires SDK version 3.32.0 or higher. + + You can autocapture exceptions by setting the `errorTrackingConfig.autoCapture` argument to `true` when initializing the PostHog SDK. + + Kotlin + + ```kotlin + import com.posthog.android.PostHogAndroidConfig + val config = PostHogAndroidConfig( + apiKey = POSTHOG_PROJECT_TOKEN, + host = POSTHOG_HOST + ).apply { + ... + errorTrackingConfig.autoCapture = true + } + ... + ``` + + When enabled, this automatically captures `$exception` events when errors are thrown by wrapping the `Thread.UncaughtExceptionHandler` listener. + + **Planned features** + + We currently don't support [source code context](https://posthog.com/docs/error-tracking/stack-traces.md) associated with an exception. + + These features will be added in a future release. + +5. 5 + + ## Manually capture exceptions + + Optional + + It is also possible to manually capture exceptions using the `captureException` method: + + Kotlin + + ```kotlin + PostHog.captureException( + exception, + properties = additionalProperties + ) + ``` + + This is helpful if you've built your own error handling logic or want to capture exceptions that are handled by your application code. + +6. ## Verify error tracking + + Recommended + + *Confirm events are being sent to PostHog* + + Before proceeding, let's make sure exception events are being captured and sent to PostHog. You should see events appear in the activity feed. + + ![Activity feed with events](https://res.cloudinary.com/dmukukwp6/image/upload/SCR_20250729_ouxl_f788dd8cd2.png) + + [Check for exceptions in PostHog](https://app.posthog.com/activity/explore) + +7. 6 + + ## Upload mapping files + + Required + + Great, you're capturing exceptions! The next step is to upload ProGuard/R8 mapping files so PostHog can deobfuscate your stack traces. + + Let's continue to the next section. + + [Upload mapping files](https://posthog.com/docs/error-tracking/upload-mappings/android.md) diff --git a/context/docs-snapshots/legacy/error-tracking/flutter.md b/context/docs-snapshots/legacy/error-tracking/flutter.md new file mode 100644 index 000000000..5e83609aa --- /dev/null +++ b/context/docs-snapshots/legacy/error-tracking/flutter.md @@ -0,0 +1,357 @@ +> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt + +# Flutter Error Tracking installation + +Canonical URL: https://posthog.com/docs/error-tracking/installation/flutter + +> **Cloud region:** This page uses US Cloud hosts. For an EU Cloud project, use `https://eu.i.posthog.com` instead of `https://us.i.posthog.com` (ingestion host), and use `https://eu.posthog.com` instead of `https://app.posthog.com` (app host for links). + +## On this page + +- [Install with the wizard](#install-with-the-wizard) +- [Install the package](#install-the-package) +- [Platform setup](#platform-setup) +- [Send events](#send-events) +- [Set up exception autocapture](#set-up-exception-autocapture) +- [Manually capture exceptions](#manually-capture-exceptions) +- [Upload Dart debug symbols](#upload-dart-debug-symbols) +- [Future features](#future-features) +- [Verify error tracking](#verify-error-tracking) +- [Upload source maps](#upload-source-maps) +- [iOS and macOS dependency resolution](#ios-and-macos-dependency-resolution) + +## Install with the wizard + +Run this command in your project directory to add PostHog to your Flutter project. The wizard detects your framework, installs the SDK, and sets up your first events. + +`npx @posthog/wizard` + +Or set it up manually by following the rest of this guide. + +1. 1 + + ## Install the package + + Required + + Add the PostHog Flutter SDK to your `pubspec.yaml`: + + pubspec.yaml + + ```yaml + posthog_flutter: ^5.58.0 + ``` + +2. 2 + + ## Platform setup + + Required + + ## Tab + + Add these values to your `AndroidManifest.xml`: + + android/app/src/main/AndroidManifest.xml + + ```xml + + + [...] + + + + + + + ``` + + Update the minimum Android SDK version to **21** in `android/app/build.gradle`: + + android/app/build.gradle + + ```groovy + defaultConfig { + minSdkVersion 23 + // rest of your config + } + ``` + + ## Tab + + Add these values to your `Info.plist`: + + ios/Runner/Info.plist + + ```xml + + [...] + com.posthog.posthog.PROJECT_TOKEN + + com.posthog.posthog.POSTHOG_HOST + https://us.i.posthog.com + com.posthog.posthog.CAPTURE_APPLICATION_LIFECYCLE_EVENTS + + com.posthog.posthog.DEBUG + + + ``` + + Update the minimum platform version to iOS 13.0 in your `Podfile`: + + Podfile + + ```ruby + platform :ios, '13.0' + # rest of your config + ``` + + ## Tab + + Add these values in `index.html`: + + web/index.html + + ```html + + + + ... + + + + ... + + + ``` + +3. 3 + + ## Send events + + Recommended + + Once installed, PostHog will automatically start capturing events. You can also manually send events to test your integration: + + Dart + + ```dart + import 'package:posthog_flutter/posthog_flutter.dart'; + + await Posthog().capture( + eventName: 'button_clicked', + properties: { + 'button_name': 'signup' + } + ); + ``` + +4. 4 + + ## Set up exception autocapture + + Recommended + + **Client-side configuration only** + + This configuration is client-side only. Support for remote configuration in the [error tracking settings](https://app.posthog.com/settings/project-error-tracking#exception-autocapture) will be added in a future release. + + Dart AOT symbolication and background isolate listeners require `posthog_flutter` 5.58.0 or later. If your project uses an earlier version, set `posthog_flutter: ^5.58.0` in `pubspec.yaml` and run `flutter pub get`. + + You can autocapture exceptions by configuring the `errorTrackingConfig` when setting up PostHog: + + Dart + + ```dart + final config = PostHogConfig(''); + // Enable exception autocapture + config.errorTrackingConfig.captureFlutterErrors = true; + config.errorTrackingConfig.capturePlatformDispatcherErrors = true; + config.errorTrackingConfig.captureIsolateErrors = true; + // Requires SDK version 5.22.0 or higher + config.errorTrackingConfig.captureNativeExceptions = true; + config.errorTrackingConfig.captureSilentFlutterErrors = false; + await Posthog().setup(config); + ``` + + **Configuration options:** + + | Option | Description | + | --- | --- | + | `captureFlutterErrors` | Captures Flutter framework errors (`FlutterError.onError`) | + | `capturePlatformDispatcherErrors` | Captures Dart runtime errors (`PlatformDispatcher.onError`). Web not supported. | + | `captureIsolateErrors` | Captures errors from the isolate where PostHog is set up. Spawn background isolates paused and call `isolate.addPostHogErrorListener()` before resuming them to capture their errors. Web not supported. | + | `captureNativeExceptions` | Captures native exceptions. Android (Java/Kotlin) and Apple platforms (iOS, macOS, tvOS). | + | `captureSilentFlutterErrors` | Captures Flutter errors that are marked as silent. Default: false. | + +5. 5 + + ## Manually capture exceptions + + Optional + + ### Basic usage + + You can manually capture exceptions using the `captureException` method: + + Dart + + ```dart + try { + // Your awesome code that may throw + await someRiskyOperation(); + } catch (exception, stackTrace) { + // Capture the exception with PostHog + await Posthog().captureException( + error: exception, + stackTrace: stackTrace, + properties: { + 'user_action': 'button_press', + 'feature_name': 'data_sync', + }, + ); + } + ``` + + This is helpful if you've built your own error handling logic or want to capture exceptions that are handled by your application code. + + ### Error tracking configuration + + You can configure error tracking behavior when setting up PostHog: + + **Flutter web apps use minified stack trace frames** + + Flutter web apps generate minified stack trace frames by default, which may cause the configurations below to behave differently or not work as expected. + + Dart + + ```dart + final config = PostHogConfig(''); + // Configure error tracking + config.errorTrackingConfig.inAppIncludes.add('package:your_app'); + config.errorTrackingConfig.inAppExcludes.add('package:third_party_lib'); + config.errorTrackingConfig.inAppByDefault = true; + await Posthog().setup(config); + ``` + + **Configuration options:** + + | Option | Description | + | --- | --- | + | `inAppIncludes` | List of package names to be considered inApp frames (takes precedence over excludes) | + | `inAppExcludes` | List of package names to be excluded from inApp frames | + | `inAppByDefault` | Whether frames are considered inApp by default when their origin cannot be determined | + + `inApp` frames are stack trace frames that belong to your application code (as opposed to third-party libraries or system code). These are highlighted in the PostHog error tracking interface to help you focus on the relevant parts of the stack trace. + +6. 6 + + ## Upload Dart debug symbols + + Optional + + Flutter writes Dart debug symbols for release builds when you pass `--split-debug-info`. Upload the symbols for each build you ship so PostHog can show Dart function names and line numbers for Android and iOS exceptions. Add `--obfuscate` to the build command if you obfuscate your app. + + ### Android + + ```bash + flutter build apk --release \ + --split-debug-info=build/posthog-symbols/android + ``` + + ### iOS + + ```bash + flutter build ipa --release \ + --split-debug-info=build/posthog-symbols/ios + ``` + + Run these commands from your app's root directory to upload each build's `.symbols` files. Sign in with `posthog-cli login`, or set `POSTHOG_CLI_API_KEY` and `POSTHOG_CLI_PROJECT_ID` in CI. Keep each build's symbols in its own directory. + + ### Android + + ```bash + posthog-cli symbol-sets upload \ + --directory build/posthog-symbols/android + ``` + + ### iOS + + ```bash + posthog-cli symbol-sets upload \ + --directory build/posthog-symbols/ios + ``` + + To show [source code context](https://posthog.com/docs/error-tracking/stack-traces.md), use this command instead of the symbol-only upload. It includes your app's source files: + + ### Android + + ```bash + posthog-cli symbol-sets upload \ + --directory build/posthog-symbols/android \ + --include-source --source-root ./lib + ``` + + ### iOS + + ```bash + posthog-cli symbol-sets upload \ + --directory build/posthog-symbols/ios \ + --include-source --source-root ./lib + ``` + + `--source-root ./lib` limits source files, not symbol files. Run the upload on the build machine while your app source is available. Review your source files before uploading them. See the [CLI debug symbol guide](https://github.com/PostHog/posthog/blob/master/cli/README.md#uploading-native-debug-symbols) for more options. + +7. 7 + + ## Future features + + Optional + + We currently don't support the following features: + + - Restoring obfuscated Dart exception class names + - Capturing native C/C++ exceptions on Android (Java/Kotlin only) + + For symbolicated native Android and iOS stack traces, see the [Flutter debug symbols guide](https://posthog.com/docs/error-tracking/upload-source-maps/flutter.md). + +8. ## Verify error tracking + + Recommended + + *Confirm events are being sent to PostHog* + + Before proceeding, let's make sure exception events are being captured and sent to PostHog. You should see events appear in the activity feed. + + ![Activity feed with events](https://res.cloudinary.com/dmukukwp6/image/upload/SCR_20250729_ouxl_f788dd8cd2.png) + + [Check for exceptions in PostHog](https://app.posthog.com/activity/explore) + +9. 8 + + ## Upload source maps + + Required + + Great, you're capturing exceptions! If you serve minified bundles, the next step is to upload source maps to generate accurate stack traces. + + Let's continue to the next section. + + [Upload source maps](https://posthog.com/docs/error-tracking/upload-source-maps/flutter.md) + +## iOS and macOS dependency resolution + +> **CocoaPods is becoming read-only.** [CocoaPods has announced](https://blog.cocoapods.org/CocoaPods-Specs-Repo/) the following schedule for its public specs repository: +> +> - November 2–6, 2026: A read-only dry run will prevent us from publishing new PostHog iOS SDK versions to CocoaPods. +> - December 2, 2026 onward: The repository will be permanently read-only. New PostHog iOS SDK versions will only be available through Swift Package Manager (SPM). +> +> Existing native SDK versions will remain available through CocoaPods. To keep receiving native SDK updates on iOS and macOS, migrate your Flutter app to SPM. The `posthog_flutter` package supports SPM, and Flutter 3.44 and later enable it by default. On earlier Flutter versions that support SPM, or if you disabled it, run `flutter config --enable-swift-package-manager`, then rebuild your app. Follow [Flutter's SPM migration guide](https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-app-developers) for project setup and troubleshooting. +> +> This change does not affect `posthog_flutter` releases on pub.dev, Android, or web. diff --git a/context/docs-snapshots/legacy/feature-flags/flutter.md b/context/docs-snapshots/legacy/feature-flags/flutter.md new file mode 100644 index 000000000..3d7e6b7c1 --- /dev/null +++ b/context/docs-snapshots/legacy/feature-flags/flutter.md @@ -0,0 +1,221 @@ +> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt + +# Flutter Feature Flags installation + +Canonical URL: https://posthog.com/docs/feature-flags/installation/flutter + +> **Cloud region:** This page uses US Cloud hosts. For an EU Cloud project, use `https://eu.i.posthog.com` instead of `https://us.i.posthog.com` (ingestion host). + +## On this page + +- [Install with the wizard](#install-with-the-wizard) +- [Install the package](#install-the-package) +- [Platform setup](#platform-setup) +- [Send events](#send-events) +- [Evaluate boolean feature flags](#evaluate-boolean-feature-flags) +- [Evaluate multivariate feature flags](#evaluate-multivariate-feature-flags) +- [Running experiments](#running-experiments) +- [Next steps](#next-steps) + +## Install with the wizard + +Run this command in your project directory to add PostHog to your Flutter project. The wizard detects your framework, installs the SDK, and sets up your first events. + +`npx @posthog/wizard` + +Or set it up manually by following the rest of this guide. + +> **CocoaPods is becoming read-only.** [CocoaPods has announced](https://blog.cocoapods.org/CocoaPods-Specs-Repo/) the following schedule for its public specs repository: +> +> - November 2–6, 2026: A read-only dry run will prevent us from publishing new PostHog iOS SDK versions to CocoaPods. +> - December 2, 2026 onward: The repository will be permanently read-only. New PostHog iOS SDK versions will only be available through Swift Package Manager (SPM). +> +> Existing native SDK versions will remain available through CocoaPods. To keep receiving native SDK updates on iOS and macOS, migrate your Flutter app to SPM. The `posthog_flutter` package supports SPM, and Flutter 3.44 and later enable it by default. On earlier Flutter versions that support SPM, or if you disabled it, run `flutter config --enable-swift-package-manager`, then rebuild your app. Follow [Flutter's SPM migration guide](https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-app-developers) for project setup and troubleshooting. +> +> This change does not affect `posthog_flutter` releases on pub.dev, Android, or web. + +1. 1 + + ## Install the package + + Required + + Add the PostHog Flutter SDK to your `pubspec.yaml`: + + pubspec.yaml + + ```yaml + posthog_flutter: ^5.24.0 + ``` + +2. 2 + + ## Platform setup + + Required + + ## Tab + + Add these values to your `AndroidManifest.xml`: + + android/app/src/main/AndroidManifest.xml + + ```xml + + + [...] + + + + + + + ``` + + Update the minimum Android SDK version to **21** in `android/app/build.gradle`: + + android/app/build.gradle + + ```groovy + defaultConfig { + minSdkVersion 23 + // rest of your config + } + ``` + + ## Tab + + Add these values to your `Info.plist`: + + ios/Runner/Info.plist + + ```xml + + [...] + com.posthog.posthog.PROJECT_TOKEN + + com.posthog.posthog.POSTHOG_HOST + https://us.i.posthog.com + com.posthog.posthog.CAPTURE_APPLICATION_LIFECYCLE_EVENTS + + com.posthog.posthog.DEBUG + + + ``` + + Update the minimum platform version to iOS 13.0 in your `Podfile`: + + Podfile + + ```ruby + platform :ios, '13.0' + # rest of your config + ``` + + ## Tab + + Add these values in `index.html`: + + web/index.html + + ```html + + + + ... + + + + ... + + + ``` + +3. 3 + + ## Send events + + Recommended + + Once installed, PostHog will automatically start capturing events. You can also manually send events to test your integration: + + Dart + + ```dart + import 'package:posthog_flutter/posthog_flutter.dart'; + + await Posthog().capture( + eventName: 'button_clicked', + properties: { + 'button_name': 'signup' + } + ); + ``` + +4. 4 + + ## Evaluate boolean feature flags + + Required + + Check if a feature flag is enabled: + + Dart + + ```dart + final isMyFlagEnabled = await Posthog().isFeatureEnabled('flag-key'); + if (isMyFlagEnabled) { + // Do something differently for this user + // Optional: fetch the payload + final matchedFlagPayload = (await Posthog().getFeatureFlagResult('flag-key'))?.payload; + } + ``` + +5. 5 + + ## Evaluate multivariate feature flags + + Optional + + For multivariate flags, check which variant the user has been assigned: + + Dart + + ```dart + final enabledVariant = await Posthog().getFeatureFlag('flag-key'); + if (enabledVariant == 'variant-key') { // replace 'variant-key' with the key of your variant + // Do something differently for this user + // Optional: fetch the payload + final matchedFlagPayload = (await Posthog().getFeatureFlagResult('flag-key'))?.payload; + } + ``` + +6. 6 + + ## Running experiments + + Optional + + Experiments run on top of our feature flags. Once you've implemented the flag in your code, you run an experiment by creating a new experiment in the PostHog dashboard. + +7. 7 + + ## Next steps + + Recommended + + Now that you're evaluating flags, continue with the resources below to learn what else Feature Flags enables within the PostHog platform. + + | Resource | Description | + | --- | --- | + | [Creating a feature flag](https://posthog.com/docs/feature-flags/creating-feature-flags.md) | How to create a feature flag in PostHog | + | [Adding feature flag code](https://posthog.com/docs/feature-flags/adding-feature-flag-code.md) | How to check flags in your code for all platforms | + | [Framework-specific guides](https://posthog.com/docs/feature-flags/tutorials.md#framework-guides) | Setup guides for React Native, Next.js, Flutter, and other frameworks | + | [How to do a phased rollout](https://posthog.com/tutorials/phased-rollout.md) | Gradually roll out features to minimize risk | + | [More tutorials](https://posthog.com/docs/feature-flags/tutorials.md) | Other real-world examples and use cases | diff --git a/context/docs-snapshots/legacy/logs-installation/android.md b/context/docs-snapshots/legacy/logs-installation/android.md new file mode 100644 index 000000000..7db4eebbb --- /dev/null +++ b/context/docs-snapshots/legacy/logs-installation/android.md @@ -0,0 +1,213 @@ +> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt + +# Android Logs installation + +Canonical URL: https://posthog.com/docs/logs/installation/android + +> **Cloud region:** This page uses US Cloud hosts. For an EU Cloud project, use `https://eu.i.posthog.com` instead of `https://us.i.posthog.com` (ingestion host), and use `https://eu.posthog.com` instead of `https://app.posthog.com` (app host for links). + +## On this page + +- [Install posthog-android](#install-posthog-android) +- [Configure logs in your PostHogAndroidConfig](#configure-logs-in-your-posthogandroidconfig) +- [Capture logs](#capture-logs) +- [Test your setup](#test-your-setup) +- [Tune buffering, rate cap, and resource attributes](#tune-buffering-rate-cap-and-resource-attributes) +- [Filter or redact with beforeSend](#filter-or-redact-with-beforesend) +- [Next steps](#next-steps) + +The PostHog Android SDK has built-in support for capturing structured Logs from Android apps. The SDK handles the OTLP encoding, batching, on-disk persistence across app restarts, and lifecycle integration. You just call `PostHog.logger.{trace,debug,info,warn,error,fatal}(...)`. + +> **Manual capture only.** Logs are emitted by your code. The SDK does not autocapture system log streams (`Log.d`, `Logcat`, `Timber`). + +> **Minimum version:** `com.posthog:posthog-android@3.46.0` or later. Bump the dependency in your `build.gradle` (or `build.gradle.kts`) and re-sync. + +1. 1 + + ## Install posthog-android + + Required + + If you haven't installed `posthog-android` yet, follow the [Android SDK installation guide](https://posthog.com/docs/libraries/android.md#installation). + +2. 2 + + ## Configure logs in your PostHogAndroidConfig + + Required + + Configure Logs through `config.logs` before calling `PostHogAndroid.setup(...)`. All fields are optional; defaults are tuned for mobile (cellular bandwidth, battery, app lifecycle). + + ```kotlin + val config = PostHogAndroidConfig( + apiKey = "", + host = "https://us.i.posthog.com", + ).apply { + logs.serviceName = "my-app" // OTLP service.name – shown in the Logs UI + logs.environment = "production" // OTLP deployment.environment + logs.serviceVersion = "1.2.3" // OTLP service.version + } + ``` + + These resource attributes are captured at `setup(...)` and apply to every batch. Mutating `config.logs.serviceName`, `environment`, `serviceVersion`, or `resourceAttributes` after setup has no effect. + +3. 3 + + ## Capture logs + + Required + + Use `PostHog.logger` for the per-level convenience API. + + ```kotlin + import com.posthog.PostHog + import com.posthog.logs.PostHogLogSeverity + + // Per-level convenience methods + PostHog.logger.info("checkout completed", mapOf("order_id" to "ord_789", "amount_cents" to 4999)) + PostHog.logger.warn("payment retry", mapOf("attempt" to 2)) + PostHog.logger.error("payment failed", mapOf("code" to "E001")) + + // Generic entry point for a runtime severity (e.g. mapping a Timber priority) + PostHog.logger.log("rendered cart", severity = PostHogLogSeverity.DEBUG) + ``` + + Available severity levels: `TRACE`, `DEBUG`, `INFO`, `WARN`, `ERROR`, `FATAL`. + + If you need W3C trace correlation, call `PostHog.captureLog(...)` directly and pass `traceId`, `spanId`, and `traceFlags`. + + ```kotlin + PostHog.captureLog( + "payment failed", + severity = PostHogLogSeverity.ERROR, + attributes = mapOf("code" to "PAY_3001"), + traceId = "4bf92f3577b34da6a3ce929d0e0e4736", + spanId = "00f067aa0ba902b7", + traceFlags = 0x01, + ) + ``` + + Records are buffered, batched, persisted to disk, and flushed automatically – every 30 seconds, when the buffer hits the threshold, when the app moves to the background, or on `PostHog.flush()`. `flush()` drains events, Session Replay, and Logs together. + + Each record is automatically tagged with the current distinct ID, session ID, current screen, app foreground/background state, and active Feature Flags at the moment of capture. + + From Java: + + ```java + import com.posthog.PostHog; + import com.posthog.logs.PostHogLogSeverity; + + import java.util.Map; + + PostHog.Companion.getLogger().info("checkout opened", null); + PostHog.Companion.getLogger().error( + "payment failed", + Map.of("amount_cents", 1999, "currency", "USD") + ); + ``` + +4. 4 + + ## Test your setup + + Recommended + + 1. Capture a test log from your app: + + ```kotlin + PostHog.logger.info("hello from Android") + PostHog.flush() + ``` + + 2. Open the [PostHog Logs UI](https://app.posthog.com/logs). + 3. Filter by `service.name = 'my-app'` (or whatever value you set above). + + You should see your record arrive within a few seconds. + + [View your Logs in PostHog](https://app.posthog.com/logs) + +5. 5 + + ## Tune buffering, rate cap, and resource attributes + + Optional + + The `logs` config has knobs for high-volume apps: + + ```kotlin + val config = PostHogAndroidConfig(apiKey = "").apply { + logs.serviceName = "my-app" + logs.flushIntervalSeconds = 5 // default 30 + logs.maxBufferSize = 200 // default 1000 + logs.maxBatchSize = 50 // default 50 + logs.flushAt = 20 // default 20 + logs.rateCapMaxLogs = 5000 // default 500 + logs.rateCapWindowSeconds = 60 // default 10 + logs.resourceAttributes = mapOf("host.name" to "device-01") + } + PostHogAndroid.setup(this, config) + ``` + + Full configuration reference: + + | Field | Default | What it does | + | --- | --- | --- | + | `serviceName` | app package id | OTLP `service.name` resource attribute | + | `serviceVersion` | `BuildConfig.VERSION_NAME` | OTLP `service.version` resource attribute | + | `environment` | `null` | OTLP `deployment.environment` resource attribute | + | `resourceAttributes` | `{}` | Extra OTLP resource attributes (SDK keys win on collision) | + | `flushIntervalSeconds` | `30` | Periodic flush interval | + | `flushAt` | `20` | Buffer threshold that triggers an automatic flush | + | `maxBatchSize` | `50` | Max records per outbound POST (halved on 413) | + | `maxBufferSize` | `1000` | Max records held on disk before FIFO eviction | + | `rateCapMaxLogs` | `500` | Max records per `rateCapWindowSeconds` window. Set to `0` to disable. | + | `rateCapWindowSeconds` | `10` | Rate-cap tumbling window length | + + `serviceName`, `serviceVersion`, `environment`, `resourceAttributes`, `flushAt`, and `maxBatchSize` are captured at `setup(...)`; mutating them later has no effect. `flushIntervalSeconds`, `maxBufferSize`, and rate-cap fields are re-read at runtime. Defaults are tuned for cellular-aware mobile apps. Raise `rateCapMaxLogs` and `maxBufferSize` for high-volume scenarios. + +6. 6 + + ## Filter or redact with beforeSend + + Optional + + `beforeSend` runs synchronously before the rate cap, so dropped records don't consume the per-window budget. Use it for redaction, sampling, or filtering by level. Each hook receives an immutable `PostHogLogRecord` and returns either a (possibly modified) record or `null` to drop it. + + ```kotlin + config.logs.addBeforeSend { record -> + // Drop debug logs in production + if (record.level == PostHogLogSeverity.DEBUG) return@addBeforeSend null + + // Redact secrets in the body + record.copy(body = record.body.replace(Regex("api_key=\\S+"), "api_key=[REDACTED]")) + } + ``` + + Call `addBeforeSend` multiple times to compose a chain – hooks are evaluated left-to-right (registration order). Returning `null` from any hook short-circuits and drops the record. A hook that throws is treated the same as returning `null` (the record is dropped, the exception is logged via the SDK's internal debug logger). Returning a record with a blank body also drops the record. + + `addBeforeSend` and `removeBeforeSend` are live – added or removed hooks take effect on the next `captureLog` call. + + From Java, register a `PostHogBeforeSendLog` SAM: + + ```java + config.getLogs().addBeforeSend(record -> + record.getBody().contains("secret") ? null : record + ); + ``` + +8. ## Next steps + + Checkpoint + + *What you can do with your logs* + + | Action | Description | + | --- | --- | + | **[Why you need logs](https://posthog.com/docs/logs/basics.md)** | What logs show you that nothing else does | + | **[Search logs](https://posthog.com/docs/logs/search.md)** | Use the search interface to find specific log entries | + | **Filter by level** | Filter by `INFO`, `WARN`, `ERROR`, etc. | + | **[Link session replay](https://posthog.com/docs/logs/link-session-replay.md)** | Connect logs to users and session replays by passing `posthogDistinctId` and `sessionId` | + | **[Link logs to a person](https://posthog.com/docs/logs/link-person.md)** | Surface every log emitted on behalf of a user on their PostHog person profile | + | **[Logging best practices](https://posthog.com/docs/logs/best-practices.md)** | Learn what to log, how to structure logs, and patterns that make logs useful in production | + + [Troubleshoot common issues](https://posthog.com/docs/logs/troubleshooting.md) diff --git a/context/docs-snapshots/legacy/logs-installation/flutter.md b/context/docs-snapshots/legacy/logs-installation/flutter.md new file mode 100644 index 000000000..d3f4a82f0 --- /dev/null +++ b/context/docs-snapshots/legacy/logs-installation/flutter.md @@ -0,0 +1,461 @@ +> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt + +# Flutter Logs installation + +Canonical URL: https://posthog.com/docs/logs/installation/flutter + +> **Cloud region:** This page uses US Cloud hosts. For an EU Cloud project, use `https://eu.posthog.com` instead of `https://us.posthog.com` or `https://app.posthog.com` (app host for links). + +## On this page + +- [Install posthog_flutter](#install-posthog_flutter) +- [Configure logs in your PostHogConfig](#configure-logs-in-your-posthogconfig) +- [Capture logs](#capture-logs) +- [Test your setup](#test-your-setup) +- [Tune buffering, rate cap, and resource attributes](#tune-buffering-rate-cap-and-resource-attributes) +- [Filter or redact with beforeSend](#filter-or-redact-with-beforesend) +- [Next steps](#next-steps) + +The PostHog Flutter SDK has built-in support for capturing structured Logs from your Flutter app across mobile and web. The SDK handles the OTLP encoding, batching, and flushing — and on mobile, on-disk persistence across app restarts and app-lifecycle integration (web buffers in memory via `posthog-js`). You just call `Posthog().captureLog(...)` or `Posthog().logger.{trace,debug,info,warn,error,fatal}(...)`. + +> **Manual capture only.** Logs are emitted by your code. The SDK does not autocapture system log streams (`print`, `debugPrint`, or `dart:developer`'s `log`). + +> **Minimum version:** `posthog_flutter` `5.27.0` or later (the release that adds Logs support). On mobile it pulls in `posthog-android` `3.48.0` or later automatically. + +1. 1 + + ## Install posthog\_flutter + + Required + + If you haven't installed `posthog_flutter` yet, follow the steps below. For full details, see the [Flutter SDK guide](https://posthog.com/docs/libraries/flutter.md). + + > **CocoaPods is becoming read-only.** [CocoaPods has announced](https://blog.cocoapods.org/CocoaPods-Specs-Repo/) the following schedule for its public specs repository: + > + > - November 2–6, 2026: A read-only dry run will prevent us from publishing new PostHog iOS SDK versions to CocoaPods. + > - December 2, 2026 onward: The repository will be permanently read-only. New PostHog iOS SDK versions will only be available through Swift Package Manager (SPM). + > + > Existing native SDK versions will remain available through CocoaPods. To keep receiving native SDK updates on iOS and macOS, migrate your Flutter app to SPM. The `posthog_flutter` package supports SPM, and Flutter 3.44 and later enable it by default. On earlier Flutter versions that support SPM, or if you disabled it, run `flutter config --enable-swift-package-manager`, then rebuild your app. Follow [Flutter's SPM migration guide](https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-app-developers) for project setup and troubleshooting. + > + > This change does not affect `posthog_flutter` releases on pub.dev, Android, or web. + + PostHog is available for install via [Pub](https://pub.dev/packages/posthog_flutter). + + ### Configuration + + Set your PostHog project token and enable automatic event tracking if you want the library to capture lifecycle events for you. + + Remember that the application lifecycle events won't have any special context set for you by the time it is initialized. If you are using a self-hosted instance of PostHog you will need to have the public hostname or IP for your instance as well. + + To start, add `posthog_flutter` to your `pubspec.yaml`: + + pubspec.yaml + + ```yaml + # rest of your code + + dependencies: + flutter: + sdk: flutter + posthog_flutter: ^5.26.0 + + # rest of your code + ``` + + Then complete the setup for each platform: + + > For Session Replay and Surveys, you must set up the SDK manually by disabling the `com.posthog.posthog.AUTO_INIT` mode. + + #### Android setup + + There are 2 ways of initializing the SDK, automatically and manually. + + Automatically: + + Add your PostHog configuration to your `AndroidManifest.xml` file located in the `android/app/src/main`: + + android/app/src/main/AndroidManifest.xml + + ```xml + + + + + + + + + + ``` + + Or manually (more control and more configurations available): + + Add your PostHog configuration to your `AndroidManifest.xml` file located in the `android/app/src/main`: + + android/app/src/main/AndroidManifest.xml + + ```xml + + + + + + + ``` + + In both cases, you'll also need to update the minimum Android SDK version to `23` in `android/app/build.gradle`: + + android/app/build.gradle + + ```kotlin + // rest of your config + + defaultConfig { + minSdkVersion 23 + // rest of your config + } + + // rest of your config + ``` + + #### iOS setup + + There are 2 ways of initializing the SDK, automatically and manually. + + The SDK supports both [CocoaPods](https://guides.cocoapods.org/using/getting-started.html) and [Swift Package Manager (SPM)](https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-app-developers). Flutter 3.44 and later enable SPM by default. On earlier versions, or if you disabled SPM, enable it with `flutter config --enable-swift-package-manager`. + + Automatically: + + Add your PostHog configuration to the `Info.plist` file located in the `ios/Runner` directory: + + ios/Runner/Info.plist + + ```xml + + + + + + com.posthog.posthog.PROJECT_TOKEN + + com.posthog.posthog.POSTHOG_HOST + https://us.i.posthog.com + + com.posthog.posthog.DEBUG + + + + ``` + + Or manually (more control and more configurations available): + + Add your PostHog configuration to the `Info.plist` file located in the `ios/Runner` directory: + + ios/Runner/Info.plist + + ```xml + + + + + + com.posthog.posthog.AUTO_INIT + + + + ``` + + In both cases, you'll need to set the minimum platform version to iOS 13.0. + + For CocoaPods projects, set it in your `Podfile`: + + ios/Podfile + + ```yaml + platform :ios, '13.0' + # rest of your config + ``` + + For Swift Package Manager projects without a `Podfile`, set the **Minimum Deployments** version to iOS 13.0 for the `Runner` target in Xcode (**Runner > General > Minimum Deployments**). After you change **Minimum Deployments**, regenerate the iOS project's configuration files: + + ```bash + flutter build ios --config-only + ``` + + #### Dart setup (For manual step only) + + If you followed the automatic SDK setup, then there's no more configuration needed in Dart. + + If you followed the manual SDK setup: + + ```dart + import 'package:flutter/material.dart'; + + import 'package:posthog_flutter/posthog_flutter.dart'; + + Future main() async { + // init WidgetsFlutterBinding if not yet + WidgetsFlutterBinding.ensureInitialized(); + final config = PostHogConfig(''); + config.debug = true; + // captureApplicationLifecycleEvents is enabled by default since version 5.23.0 + config.host = 'https://us.i.posthog.com'; + await Posthog().setup(config); + runApp(MyApp()); + } + ``` + + #### Web setup + + If your project has a `web/` directory, this step is required. `Posthog().setup()` is a no-op on web, so a web build without the snippet below captures nothing. + + Add your `Web snippet` (which you can find in [your project settings](https://us.posthog.com/settings/project#snippet)) in the `
` of your `web/index.html` file. Write your project token into the snippet as a literal string. It's public, the same token ships to every visitor, and it needs no build-time or deploy-time injection: + + web/index.html + + ```html + + + + + + + + + + + ``` + + For more information please check: /docs/libraries/js + +2. 2 + + ## Configure logs in your PostHogConfig + + Required + + Configure Logs through `config.logsConfig` before calling `Posthog().setup(...)`. All fields are optional; unset fields fall back to the native defaults, which are tuned for mobile (cellular bandwidth, battery, app lifecycle). + + ```dart + final config = PostHogConfig(''); + config.host = 'https://us.i.posthog.com'; + config.logsConfig.serviceName = 'my-app'; // OTLP service.name – shown in the Logs UI + config.logsConfig.environment = 'production'; // OTLP deployment.environment + config.logsConfig.serviceVersion = '1.2.3'; // OTLP service.version + await Posthog().setup(config); + ``` + + These resource attributes are captured at `setup(...)` and apply to every batch. + + > **Web behavior.** On Flutter Web, the SDK attaches to an already-initialized [`posthog-js`](https://posthog.com/docs/libraries/js.md) instance, so `config.logsConfig` is **not** applied on web. Configure your log options in the `posthog.init({...})` call in your `web/index.html` instead. `captureLog` and `logger` still work on web (they are forwarded to `posthog-js`), and `beforeSend` still runs (in Dart) on web. Web also requires a recent `posthog-js` build that exposes `captureLog`. + + For example, set the same service identity on the `posthog-js` snippet in `web/index.html`: + + ```html + + ``` + + See the [JavaScript Logs installation guide](https://posthog.com/docs/logs/installation/javascript.md) for the full `posthog-js` logs config. + +3. 3 + + ## Capture logs + + Required + + Use `Posthog().logger` for the per-level convenience API, or `Posthog().captureLog` for full control over level, attributes, and trace context. + + ```dart + import 'package:posthog_flutter/posthog_flutter.dart'; + + // Per-level convenience methods + Posthog().logger.info('checkout completed', {'order_id': 'ord_789', 'amount_cents': 4999}); + Posthog().logger.warn('payment retry', {'attempt': 2}); + Posthog().logger.error('payment failed', {'code': 'E001'}); + + // Lower-level API for custom severity / trace context + Posthog().captureLog( + body: 'checkout failed', + level: PostHogLogSeverity.error, + attributes: {'order_id': 'ord_789', 'step': 'auth'}, + traceId: '4bf92f3577b34da6a3ce929d0e0e4736', // optional W3C trace context (32 hex chars) + spanId: '00f067aa0ba902b7', // optional W3C span (16 hex chars) + traceFlags: 1, + ); + ``` + + The per-level facade methods are `trace`, `debug`, `info`, `warn`, `error`, and `fatal`, each taking a `String body` and an optional `Map` of attributes. Available severity levels for `captureLog` are `PostHogLogSeverity.trace`, `.debug`, `.info`, `.warn`, `.error`, and `.fatal`. + + The optional W3C trace fields (`traceId`, `spanId`, `traceFlags`) are available on `captureLog` only, not on the `logger` facade. + + Records are buffered, batched, persisted to disk, and flushed automatically – every 30 seconds, when the buffer hits the threshold, when the app moves to the background, or on `Posthog().flush()`. `flush()` drains events, Session Replay, and Logs together. + + Each record is automatically tagged with the current distinct ID, session ID, active feature flags, and (on mobile) the current screen and app foreground/background state at the moment of capture. On web, `url.full` is tagged instead of screen name and app state. + +4. 4 + + ## Test your setup + + Recommended + + 1. Capture a test log from your app: + + ```dart + Posthog().logger.info('hello from Flutter'); + Posthog().flush(); + ``` + + 2. Open the [PostHog Logs UI](https://app.posthog.com/logs). + 3. Filter by `service.name = 'my-app'` (or whatever value you set above). + + You should see your record arrive within a few seconds. + + [View your Logs in PostHog](https://app.posthog.com/logs) + +5. 5 + + ## Tune buffering, rate cap, and resource attributes + + Optional + + The `logsConfig` has knobs for high-volume apps: + + ```dart + final config = PostHogConfig(''); + config.logsConfig.serviceName = 'my-app'; + config.logsConfig.flushInterval = Duration(seconds: 5); // default 30s + config.logsConfig.maxBufferSize = 200; // default 1000 + config.logsConfig.maxBatchSize = 50; // default 50 + config.logsConfig.flushAt = 20; // default 20 + config.logsConfig.rateCapMaxLogs = 5000; // default 500 + config.logsConfig.rateCapWindow = Duration(seconds: 60); // default 10s + config.logsConfig.resourceAttributes = {'host.name': 'device-01'}; + await Posthog().setup(config); + ``` + + Full configuration reference: + + | Field | Default | What it does | + | --- | --- | --- | + | `serviceName` | app bundle id (iOS) / app namespace (Android) | OTLP `service.name` resource attribute | + | `serviceVersion` | app version | OTLP `service.version` resource attribute | + | `environment` | none | OTLP `deployment.environment` resource attribute | + | `resourceAttributes` | `{}` | Extra OTLP resource attributes | + | `flushInterval` | `30s` | Periodic flush interval | + | `flushAt` | `20` | Buffer threshold that triggers an automatic flush | + | `maxBatchSize` | `50` | Max records per outbound POST | + | `maxBufferSize` | `1000` | Max records held on disk before FIFO eviction | + | `rateCapMaxLogs` | `500` | Max records per `rateCapWindow`. Set to `0` to disable. | + | `rateCapWindow` | `10s` | Rate-cap window length | + + Defaults are tuned for cellular-aware mobile apps. Raise `rateCapMaxLogs` and `maxBufferSize` for high-volume scenarios. + + > On web, these fields are not applied – configure them in your `posthog.init({...})` call in `web/index.html` instead. + +6. 6 + + ## Filter or redact with beforeSend + + Optional + + Use `config.logsConfig.beforeSend` for redaction, sampling, or filtering by level. It is a `List`, where each callback is a `FutureOr Function(PostHogLogRecord)`. Callbacks run **in Dart on all platforms (including web)**, evaluated left-to-right. Each callback receives a mutable `PostHogLogRecord` (with mutable `body`, `level`, and `attributes`) and returns either the (possibly mutated) record or `null` to drop it. Callbacks can be synchronous or asynchronous. + + ```dart + config.logsConfig.beforeSend = [ + (record) { + // Drop debug logs in production + if (record.level == PostHogLogSeverity.debug) return null; + + // Redact a sensitive attribute + record.attributes?.remove('password'); + return record; + }, + // Compose a chain – callbacks run left-to-right + (record) => record.body.contains('secret') ? null : record, + ]; + ``` + + Returning `null` from any callback short-circuits and drops the record. Setting `record.body` to an empty or whitespace-only string also drops the record. A callback that throws is logged and the record is dropped (fail-closed). + +8. ## Next steps + + Checkpoint + + *What you can do with your logs* + + | Action | Description | + | --- | --- | + | **[Why you need logs](https://posthog.com/docs/logs/basics.md)** | What logs show you that nothing else does | + | **[Search logs](https://posthog.com/docs/logs/search.md)** | Use the search interface to find specific log entries | + | **Filter by level** | Filter by `INFO`, `WARN`, `ERROR`, etc. | + | **[Link session replay](https://posthog.com/docs/logs/link-session-replay.md)** | Connect logs to users and session replays by passing `posthogDistinctId` and `sessionId` | + | **[Link logs to a person](https://posthog.com/docs/logs/link-person.md)** | Surface every log emitted on behalf of a user on their PostHog person profile | + | **[Logging best practices](https://posthog.com/docs/logs/best-practices.md)** | Learn what to log, how to structure logs, and patterns that make logs useful in production | + + [Troubleshoot common issues](https://posthog.com/docs/logs/troubleshooting.md) diff --git a/context/docs-snapshots/legacy/upload-mappings/android.md b/context/docs-snapshots/legacy/upload-mappings/android.md new file mode 100644 index 000000000..8d63ebb3b --- /dev/null +++ b/context/docs-snapshots/legacy/upload-mappings/android.md @@ -0,0 +1,159 @@ +> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt + +# Upload mappings for Android + +Canonical URL: https://posthog.com/docs/error-tracking/upload-mappings/android + +## On this page + +- [Download CLI](#download-cli) +- [Authenticate](#authenticate) +- [Inject and upload](#inject-and-upload) +- [Upload native debug symbols (NDK)](#upload-native-debug-symbols-ndk) +- [Verify mappings upload](#verify-mappings-upload) + +1. 1 + + ## Download CLI + + Required + + > [CLI v0.7.4](https://github.com/PostHog/posthog/releases/tag/posthog-cli%2Fv0.7.4) or later + + Install `posthog-cli`: + + ### Npm + + ```bash + npm install -g @posthog/cli + ``` + + ### Curl + + ```bash + curl -LsSf https://download.posthog.com/cli | sh + ``` + + ### Homebrew + + ```bash + brew install posthog/tap/posthog-cli + ``` + + ### Cargo + + ```bash + cargo install posthog-cli + ``` + +2. 2 + + ## Authenticate + + Required + + To authenticate the CLI, call the `login` command. This opens your browser where you select your organization, project, and API scopes to grant: + + ```bash + posthog-cli login + ``` + + If you are using the CLI in a CI/CD environment such as GitHub Actions, you can set environment variables to authenticate: + + | Environment Variable | Description | Source | + | --- | --- | --- | + | `POSTHOG_CLI_HOST` | The PostHog host to connect to \[default: https://us.posthog.com\] | [Project settings](https://app.posthog.com/settings/project#variables) | + | `POSTHOG_CLI_PROJECT_ID` | PostHog project ID | [Project settings](https://app.posthog.com/settings/project#variables) | + | `POSTHOG_CLI_API_KEY` | **Personal API key** with `error tracking write` and `organization read` scopes | [API key settings](https://app.posthog.com/settings/user-api-keys#variables) | + + You can also use the `--host` option instead of the `POSTHOG_CLI_HOST` environment variable to target a different PostHog instance or region. For EU users: + + ```bash + posthog-cli --host https://eu.posthog.com [CMD] + ``` + +3. 3 + + ## Inject and upload + + Required + + > [AGP v8](https://developer.android.com/build/releases/gradle-plugin) or later + + Automatic mappings uploading is handled through the Gradle build process on Android. + + Install the [PostHog Android Gradle Plugin](https://github.com/PostHog/posthog-android/blob/main/posthog-android-gradle-plugin/CHANGELOG.md) on your app's `build.gradle.kts` file. + + ```kotlin + // Available through mavenCentral() + plugins { + id("com.android.application") + id("com.posthog.android") version "$version" + ... + } + ``` + + If you are running this in CI/CD, you can configure the CLI directly on the Gradle task instead of relying on `POSTHOG_CLI_HOST`, `POSTHOG_CLI_PROJECT_ID`, and `POSTHOG_CLI_API_KEY` environment variables: + + ```kotlin + import com.posthog.android.PostHogCliExecTask + + tasks.withType { + postHogHost = "https://eu.posthog.com" + postHogProjectId = "my-project-id" + postHogApiKey = "my-personal-api-key" + } + ``` + + You can also set `postHogExecutable` if you want to use a custom `posthog-cli` path. + +4. 4 + + ## Upload native debug symbols (NDK) + + Optional + + > Requires [PostHog Android SDK 3.60.0](https://github.com/PostHog/posthog-android/releases/tag/android-v3.60.0) or later with `errorTrackingConfig.captureNativeCrashes` enabled, [Gradle plugin 1.5.0](https://github.com/PostHog/posthog-android/releases/tag/androidPlugin-v1.5.0) or later, and [CLI 0.7.32](https://github.com/PostHog/posthog/releases/tag/posthog-cli%2Fv0.7.32) or later. + + If your app includes native C or C++ code built with the NDK, upload the `.so` debug symbols so native crash stack traces resolve to function names, files, and line numbers. + + Enable the upload in your app's `build.gradle.kts`: + + ```kotlin + posthog { + uploadNativeSymbols.set(true) + } + ``` + + When enabled, the Gradle plugin's `uploadPostHogNativeSymbols` task reads the variant's unstripped native libraries and uploads every one carrying debug info and a build ID, automatically after `assemble`, `install`, or `bundle`. This covers native code you build with the NDK as well as `.so` files bundled from `jniLibs` or dependencies, for minified and non-minified builds alike. Debuggable variants are skipped, so day-to-day debug builds don't upload symbols. + + To include source context around resolved crash frames, also bundle the project sources referenced by the debug info: + + ```kotlin + posthog { + uploadNativeSymbols.set(true) + includeNativeSymbolSources.set(true) + } + ``` + + You can also run the upload task explicitly, for any variant, without enabling the automatic upload: + + ```bash + ./gradlew uploadPostHogNativeSymbolsRelease + ``` + + You can also upload a directory of `.so` files directly, without the Gradle plugin: + + ```bash + posthog-cli symbol-sets upload --directory app/build/intermediates/merged_native_libs/release + ``` + + PostHog matches crash frames to uploaded symbols by each library's GNU build ID, which the NDK emits by default. Each build has its own build ID, so symbols must be re-uploaded for every build you ship. + + Native crash events are captured on the next app launch, so event properties like `$app_version` reflect the app at capture time, not at crash time. If the app updated in between, check the crash's release (matched by build ID) rather than the event's version properties when investigating. + +6. ## Verify mappings upload + + Checkpoint + + Confirm that mappings are successfully uploaded to PostHog.[Check symbol sets in PostHog](https://app.posthog.com/error_tracking/configuration#selectedSetting=error-tracking-symbol-sets) diff --git a/context/skills/error-tracking-upload-source-maps/config.yaml b/context/skills/error-tracking-upload-source-maps/config.yaml index f6f41cd09..3037a3e23 100644 --- a/context/skills/error-tracking-upload-source-maps/config.yaml +++ b/context/skills/error-tracking-upload-source-maps/config.yaml @@ -55,7 +55,7 @@ variants: description: Upload ProGuard / R8 mapping files to PostHog Error Tracking for Android tags: [android, java, kotlin] docs_urls: - - https://posthog.com/docs/error-tracking/upload-mappings/android.md + - context/docs-snapshots/legacy/upload-mappings/android.md - id: flutter display_name: Flutter @@ -64,7 +64,7 @@ variants: docs_urls: - https://posthog.com/docs/error-tracking/upload-source-maps/flutter.md - https://posthog.com/docs/error-tracking/upload-source-maps/web.md - - https://posthog.com/docs/error-tracking/upload-mappings/android.md + - context/docs-snapshots/legacy/upload-mappings/android.md - https://posthog.com/docs/error-tracking/upload-source-maps/ios.md - id: ios diff --git a/context/skills/error-tracking/config.yaml b/context/skills/error-tracking/config.yaml index 094062c42..5045db0ed 100644 --- a/context/skills/error-tracking/config.yaml +++ b/context/skills/error-tracking/config.yaml @@ -139,7 +139,7 @@ variants: display_name: Flutter tags: [flutter, dart] docs_urls: - - https://posthog.com/docs/error-tracking/installation/flutter.md + - context/docs-snapshots/legacy/error-tracking/flutter.md - id: ios display_name: iOS @@ -151,7 +151,7 @@ variants: display_name: Android tags: [android, java, kotlin] docs_urls: - - https://posthog.com/docs/error-tracking/installation/android.md + - context/docs-snapshots/legacy/error-tracking/android.md - id: hono display_name: Hono diff --git a/context/skills/feature-flags/config.yaml b/context/skills/feature-flags/config.yaml index ccac1dcb8..a42d8e782 100644 --- a/context/skills/feature-flags/config.yaml +++ b/context/skills/feature-flags/config.yaml @@ -149,7 +149,7 @@ variants: display_name: Flutter tags: [flutter, dart] docs_urls: - - https://posthog.com/docs/feature-flags/installation/flutter.md + - context/docs-snapshots/legacy/feature-flags/flutter.md - id: api display_name: API diff --git a/context/skills/integration-v2/error-tracking-step/config.yaml b/context/skills/integration-v2/error-tracking-step/config.yaml index b13e7ae82..0acb2548c 100644 --- a/context/skills/integration-v2/error-tracking-step/config.yaml +++ b/context/skills/integration-v2/error-tracking-step/config.yaml @@ -243,7 +243,7 @@ variants: - java - kotlin docs_urls: - - https://posthog.com/docs/error-tracking/installation/android.md + - context/docs-snapshots/legacy/error-tracking/android.md - id: sveltekit framework: sveltekit display_name: SvelteKit @@ -339,7 +339,7 @@ variants: - dart - mobile docs_urls: - - https://posthog.com/docs/error-tracking/installation/flutter.md + - context/docs-snapshots/legacy/error-tracking/flutter.md - id: kmp framework: kmp display_name: Kotlin Multiplatform diff --git a/context/skills/integration-v2/feature-flags-step/config.yaml b/context/skills/integration-v2/feature-flags-step/config.yaml index f2465281b..84dad6622 100644 --- a/context/skills/integration-v2/feature-flags-step/config.yaml +++ b/context/skills/integration-v2/feature-flags-step/config.yaml @@ -360,7 +360,7 @@ variants: - dart - mobile docs_urls: - - https://posthog.com/docs/feature-flags/installation/flutter.md + - context/docs-snapshots/legacy/feature-flags/flutter.md - id: kmp framework: kmp display_name: Kotlin Multiplatform diff --git a/context/skills/logs/config.yaml b/context/skills/logs/config.yaml index 024246833..a9c0dd726 100644 --- a/context/skills/logs/config.yaml +++ b/context/skills/logs/config.yaml @@ -63,7 +63,7 @@ variants: display_name: Android tags: [android, kotlin, java] docs_urls: - - https://posthog.com/docs/logs/installation/android.md + - context/docs-snapshots/legacy/logs-installation/android.md - id: ios display_name: iOS @@ -75,7 +75,7 @@ variants: display_name: Flutter tags: [flutter, dart] docs_urls: - - https://posthog.com/docs/logs/installation/flutter.md + - context/docs-snapshots/legacy/logs-installation/flutter.md - id: other display_name: Other Languages diff --git a/context/skills/omnibus/instrument-error-tracking/config.yaml b/context/skills/omnibus/instrument-error-tracking/config.yaml index 23316c60b..9b4ed3c1c 100644 --- a/context/skills/omnibus/instrument-error-tracking/config.yaml +++ b/context/skills/omnibus/instrument-error-tracking/config.yaml @@ -35,7 +35,7 @@ variants: - https://posthog.com/docs/error-tracking/installation/nuxt-3-7.md - https://posthog.com/docs/error-tracking/installation/nuxt-3-6.md - https://posthog.com/docs/error-tracking/installation/react-native.md - - https://posthog.com/docs/error-tracking/installation/flutter.md + - context/docs-snapshots/legacy/error-tracking/flutter.md - context/docs-snapshots/legacy/error-tracking/ios.md - - https://posthog.com/docs/error-tracking/installation/android.md + - context/docs-snapshots/legacy/error-tracking/android.md - https://posthog.com/docs/error-tracking/installation/hono.md diff --git a/context/skills/omnibus/instrument-feature-flags/config.yaml b/context/skills/omnibus/instrument-feature-flags/config.yaml index c9f5706c5..a36fb8797 100644 --- a/context/skills/omnibus/instrument-feature-flags/config.yaml +++ b/context/skills/omnibus/instrument-feature-flags/config.yaml @@ -32,6 +32,6 @@ variants: - context/docs-snapshots/legacy/feature-flags/android.md - context/docs-snapshots/legacy/feature-flags/ios.md - context/docs-snapshots/legacy/usage.md - - https://posthog.com/docs/feature-flags/installation/flutter.md + - context/docs-snapshots/legacy/feature-flags/flutter.md - https://posthog.com/docs/feature-flags/installation/api.md - https://posthog.com/docs/libraries/next-js.md diff --git a/context/skills/omnibus/instrument-logs/config.yaml b/context/skills/omnibus/instrument-logs/config.yaml index 1120976fd..4951c6b85 100644 --- a/context/skills/omnibus/instrument-logs/config.yaml +++ b/context/skills/omnibus/instrument-logs/config.yaml @@ -22,8 +22,8 @@ variants: - https://posthog.com/docs/logs/installation/go.md - https://posthog.com/docs/logs/installation/java.md - https://posthog.com/docs/logs/installation/datadog.md - - https://posthog.com/docs/logs/installation/android.md + - context/docs-snapshots/legacy/logs-installation/android.md - https://posthog.com/docs/logs/installation/react-native.md - context/docs-snapshots/legacy/logs-installation/ios.md - - https://posthog.com/docs/logs/installation/flutter.md + - context/docs-snapshots/legacy/logs-installation/flutter.md - https://posthog.com/docs/logs/installation/other.md diff --git a/scripts/lib/tests/doc-snapshots.test.js b/scripts/lib/tests/doc-snapshots.test.js index 543a56922..4ffbc4794 100644 --- a/scripts/lib/tests/doc-snapshots.test.js +++ b/scripts/lib/tests/doc-snapshots.test.js @@ -79,6 +79,12 @@ describe('the legacy SDK pages are read from the snapshots everywhere', () => { 'https://posthog.com/docs/feature-flags/installation/ios.md', 'https://posthog.com/docs/error-tracking/installation/ios.md', 'https://posthog.com/docs/logs/installation/ios.md', + 'https://posthog.com/docs/error-tracking/installation/android.md', + 'https://posthog.com/docs/logs/installation/android.md', + 'https://posthog.com/docs/error-tracking/upload-mappings/android.md', + 'https://posthog.com/docs/feature-flags/installation/flutter.md', + 'https://posthog.com/docs/error-tracking/installation/flutter.md', + 'https://posthog.com/docs/logs/installation/flutter.md', ]; // Those pages move to the capture v1 majors on release day; a skill fetching one live would flip with them. diff --git a/scripts/lib/tests/error-tracking-upload-source-maps.test.js b/scripts/lib/tests/error-tracking-upload-source-maps.test.js index 324bbdbd3..d68f7d390 100644 --- a/scripts/lib/tests/error-tracking-upload-source-maps.test.js +++ b/scripts/lib/tests/error-tracking-upload-source-maps.test.js @@ -93,7 +93,7 @@ describe('error-tracking-upload-source-maps Android variant', () => { display_name: 'Android', description: 'Upload ProGuard / R8 mapping files to PostHog Error Tracking for Android', tags: ['error-tracking', 'source-maps', 'android', 'java', 'kotlin'], - docs_urls: ['https://posthog.com/docs/error-tracking/upload-mappings/android.md'], + docs_urls: ['context/docs-snapshots/legacy/upload-mappings/android.md'], _sharedDocs: [ 'https://posthog.com/docs/error-tracking/upload-source-maps.md', 'https://posthog.com/docs/error-tracking/upload-source-maps/cli.md',