Migrating from posthog-react-native 4.x to 5.0

posthog-react-native 5.0 sends events through capture v1, aligns the feature flag API with @posthog/react and the native SDKs (posthog-ios 4.0, posthog-android 4.0, posthog_flutter 6.0), and removes deprecated options. Read the checklist first, then the sections that apply to you.

Checklist

You need to change code or configuration if your app does any of these:

  • sends events through a reverse proxy, or to a self-hosted PostHog (see Reverse proxies and self-hosted PostHog)
  • passes a personal API key (phx_...) as the project token (see Personal API keys)
  • uses session replay or another native feature with posthog-react-native-session-replay, or with @posthog/react-native-plugin older than 3.0 (see Session replay and the native plugin)
  • passes apiKey to PostHogProvider, or sets evaluationEnvironments, disableRemoteConfig, disable_capture_url_hashes, sessionReplayConfig.iOSdebouncerDelayMs, sessionReplayConfig.androidDebouncerDelayMs, sessionReplayConfig.screenshotModeBackgroundCapture or autocapture.navigationRef (see Removed options)
  • calls useNavigationTracker() with a navigationRef argument
  • calls onFeatureFlags() or reloadFeatureFlagsAsync() (see onFeatureFlags)
  • calls getFeatureFlagPayload(), getFeatureFlags(), getFeatureFlagPayloads(), getFeatureFlagsAndPayloads(), onFeatureFlag() or overrideFeatureFlag(), or reads getFeatureFlagDetails() (see Removed feature flag methods)
  • uses the useFeatureFlag(), useFeatureFlags() or useFeatureFlagWithPayload() hooks (see Feature flag hooks)
  • passes sendEvent to getFeatureFlag(), getFeatureFlagResult() or isFeatureEnabled()
  • calls getAllFeatureFlags(), which returns undefined until flags are cached (see getAllFeatureFlags)
  • checks getFeatureFlag(key) === false, isFeatureEnabled(key) === undefined or isFeatureEnabled(key) ?? fallback for a flag that isn't in the loaded flags (see Missing flags)
  • reads a feature flag payload that isn't valid JSON, or bootstraps string payloads
  • reads enabled from getFeatureFlagResult() or getAllFeatureFlags() for a flag whose variant is an empty string, or filters on $active_feature_flags
  • sets Authorization, User-Agent, Content-Type, Content-Encoding or a PostHog- header the SDK sets in requestHeaders and expects capture requests to carry it
  • relies on the default flushInterval (10 seconds) or maxBatchSize (100) (see Event delivery)
  • relies on fetchRetryCount or fetchRetryDelay for events, on flush() or shutdown() rejecting when delivery fails, or on posthog.on('error') firing for network errors (see Event delivery)
  • sends $ai_ events, or calls captureTraceFeedback() or captureTraceMetric() (see AI events)
  • registers $is_identified or $process_person_profile, or sends null property values (see Event properties)
  • registers or passes a $window_id that isn't a string, or sets $cookieless_mode, $ignore_sent_at or $product_tour_id to a value PostHog can't read, such as 'maybe' (see Event properties and Per-event options)
  • registers or passes a property the SDK also sets, such as $os_name, $lib, $lib_version, $session_id, $geoip_disable or $recording_status (see Event properties)
  • passes $groups in the properties of capture(), screen(), captureException() or identify() (see Event properties)
  • calls identify() without a distinct ID (see identify())
  • filters insights on $used_bootstrap_value (see Event properties)
  • sends distinct IDs or event names over 200 UTF-8 bytes, such as a JWT as the distinct ID (see Event delivery)
  • uses Application Opened, Application Became Active or Application Backgrounded events in insights, cohorts, actions, survey display conditions, session replay event triggers, before_send or on('capture') (see App lifecycle events)
  • creates clients with more than one project token, or may need to go back to 4.x after releasing 5.0 (see Stored state)

Reverse proxies and self-hosted PostHog

posthog-react-native 5.0 sends events to new paths:

Method4.x5.0
capture, identify, alias, group, screen, captureException and the other event methods/batch//i/v1/analytics/events
captureAi (new)—/i/v1/ai/events
captureTraceFeedback, captureTraceMetric/batch//i/v1/ai/events

Feature flag, remote config, survey and session replay requests are unchanged.

If you send events to a self-hosted PostHog, check that it serves /i/v1/analytics/events, and /i/v1/ai/events if you use captureAi(), captureTraceFeedback() or captureTraceMetric(), before you upgrade. A 404 keeps events queued: the SDK resends them with backoff until the queue is full, then drops the oldest. A 400, 401, 403 or 405 drops them. The first 404 and the first 401 from each endpoint print a warning even without debug: true, naming the path your proxy must serve or the Authorization header it must forward. With debug: true, the SDK also logs why it keeps events, such as HTTP 404.

If you send events through your own reverse proxy, update it before you upgrade:

  • Forward /i/v1/analytics/events and /i/v1/ai/events to PostHog.
  • Pass Authorization through unchanged when it starts with Bearer phc_, or is Bearer <your project token> for a token older than the phc_ prefix. The project token is no longer in the request body, and PostHog answers 401 without it.
  • Pass every PostHog-* header, Content-Type, Content-Encoding and User-Agent through unchanged. PostHog answers 400 without them.
  • On react-native-web, if your proxy answers CORS preflight requests with a fixed Access-Control-Allow-Headers list, add Authorization, PostHog-Sdk-Info, PostHog-Attempt, PostHog-Request-Id and PostHog-Request-Timestamp to it, next to Content-Type, Content-Encoding and any requestHeaders you set. 4.x didn't send these on capture requests. Without them the browser blocks every capture request, and events stay queued.
  • Return PostHog's status code, response body and Retry-After header unchanged. The SDK drops a batch whose 2xx response has no PostHog results body, and waits as long as Retry-After asks, up to 30 seconds, before it resends. On react-native-web, if your proxy sets its own CORS response headers, add Access-Control-Expose-Headers: Retry-After, or the browser hides it from the SDK.
  • Forward the client IP in X-Forwarded-For, or PostHog geolocates every event to your proxy.
  • Accept request bodies up to 20 MB. Analytics requests carry up to 5 MiB of events, and a single AI event can be over 8 MiB.
  • Answer capture requests directly instead of redirecting them. React Native's fetch follows every redirect, including one to another origin, so a redirect can send your requestHeaders to that origin. The native SDKs follow only same-origin 307 and 308 redirects.

PostHog's managed reverse proxy already does all of this. See the proxy guides.

Session replay and the native plugin

5.0 needs @posthog/react-native-plugin 3.0 or later (a peer dependency) for gzip, session replay and other native features. Install it in every iOS and Android app, even without session replay. It no longer falls back to posthog-react-native-session-replay.

sh
npm uninstall posthog-react-native-session-replay
npm install @posthog/react-native-plugin@^3

Then run pod install in ios, or npx expo prebuild --clean. Remove pod 'PostHog' from your Podfile and posthog.useSpm from ios/Podfile.properties.json if you set them.

@posthog/react-native-plugin 3.0 needs React Native 0.75 or later, Xcode 26 or later and iOS 15 or later, and pulls posthog-ios through Swift Package Manager. See its migration guide for its own steps.

Without the plugin, requests are sent uncompressed, and session replay, native crash capture and push notification capture stay off. With posthog.debug(true), the SDK logs this for gzip, session replay and native crash capture. An installed plugin older than 3.0 is ignored the same way, with a warning that asks you to upgrade it. The SDK then doesn't call the native SDK at all, so reset() and optOut() don't unregister a push token that the native SDK registered under 4.x. Upgrade the plugin before you ship 5.0 if you use push notifications.

With the plugin, the SDK gzips its analytics, AI and log requests on iOS and Android, as 4.x already did on react-native-web. Without it, those requests are sent uncompressed, as in 4.x. disableCompression: true turns analytics compression off.

Personal API keys

5.0 disables the client when the project token is a personal API key (phx_...), like posthog-node, posthog-ios and posthog-android, and logs A personal API key ("phx_...") was passed where the project token ("phc_...") belongs. The client will be disabled. 4.x sent the key to PostHog with its requests. Pass your project token (phc_...) from your project settings (US or EU) instead.

Removed options

4.x5.0
<PostHogProvider apiKey="phc_…"><PostHogProvider projectToken="phc_…">. In JavaScript, a leftover apiKey prop is ignored with a warning and the client is disabled.
evaluationEnvironmentsevaluationContexts
disableRemoteConfigRemove it. It had no effect.
disable_capture_url_hashesRemove it. It had no effect: React Native doesn't capture page URLs.
sessionReplayConfig.iOSdebouncerDelayMs, sessionReplayConfig.androidDebouncerDelayMssessionReplayConfig.throttleDelayMs, which applies to both platforms. Without it, 4.x used the larger of the two, so set it to that value to keep the same timing.
sessionReplayConfig.screenshotModeBackgroundCapture: trueRemove it. posthog-ios 4.0 removed background capture. sessionReplayConfig.iOSCaptureMethod takes 'standard' (the default) or experimental 'gpu'.
autocapture.navigationRef, the PostHogNavigationRef typeRemove it. With captureScreens, put PostHogProvider inside the NavigationContainer (@react-navigation/native v6 and below), or capture screens manually with screen(). See capturing screen views.
useNavigationTracker(options, navigationRef, client)useNavigationTracker(options, client). In JavaScript, a leftover navigationRef second argument is read as the client: screens aren't tracked and a [PostHog] useNavigationTracker received a client without screen() error is logged. A third-argument client is ignored, so remove navigationRef.

Feature flags

onFeatureFlags

The callback gets one object, like posthog-ios, posthog-android and posthog_flutter:

TypeScript
// 4.x
posthog.onFeatureFlags((flags) => {
if (flags['new-checkout']) showNewCheckout()
})
// 5.0
posthog.onFeatureFlags(({ flags, variants, errorsLoading }) => {
if (variants['new-checkout']) showNewCheckout()
})
  • flags lists the keys of enabled flags. Disabled flags are left out; read them with getFeatureFlagResult(key).
  • variants maps each enabled flag to true or its variant.
  • errorsLoading is true when the latest load failed. flags and variants then hold the last known values, which are empty if none were cached.

reloadFeatureFlagsAsync() resolves with the same object. In 4.x it resolved with the flag map, or undefined when the load failed.

A callback registered after flags have loaded is also called once with the current values, right after onFeatureFlags() returns. If your 4.x code read flags both in the callback and right after registering it, that work now runs twice, so keep callbacks idempotent.

Removed feature flag methods

4.x5.0
getFeatureFlagPayload(key)getFeatureFlagResult(key, { sendFeatureFlagEvent: false })?.payload
getFeatureFlags(), getFeatureFlagPayloads(), getFeatureFlagsAndPayloads()getAllFeatureFlags(), which returns a list of { key, enabled, variant, payload } (see below)
onFeatureFlag(key, cb)onFeatureFlags(() => { const result = posthog.getFeatureFlagResult(key); if (result) cb(result.variant ?? result.enabled) }). Unlike 4.x, a flag missing from the loaded flags doesn't call cb with false.
overrideFeatureFlag(overrides)updateFlags(...), with disableRemoteFeatureFlags: true so the next load doesn't replace the values. Overrides set with overrideFeatureFlag() in 4.x are cleared on upgrade.
getFeatureFlagDetails()Internal, left out of the docs, and may change in any release. Use getAllFeatureFlags(), or getFeatureFlagResult(key) for one flag.
{ sendEvent: false } on getFeatureFlag(), getFeatureFlagResult(), isFeatureEnabled(){ sendFeatureFlagEvent: false }. TypeScript rejects sendEvent; plain JavaScript still accepts it, but rename it.

getAllFeatureFlags

getAllFeatureFlags() returns undefined until flags are cached: before the first successful load, after a first load that failed or was quota-limited, and after reset() until flags reload. In 4.x it returned an empty list in all of these cases. Flags are cached once a load succeeds or flags are bootstrapped; a list that is empty then means no flags apply to the user.

TypeScript
const results = posthog.getAllFeatureFlags()
if (results === undefined) {
// flags haven't loaded yet; wait for onFeatureFlags() or reloadFeatureFlagsAsync()
} else {
// results lists every loaded flag, and is empty when none apply
}

Where you only iterate, use posthog.getAllFeatureFlags() ?? [].

To build the 4.x maps from getAllFeatureFlags():

TypeScript
const results = posthog.getAllFeatureFlags() ?? []
const flags = Object.fromEntries(results.map((r) => [r.key, r.variant ?? r.enabled]))
const payloads = Object.fromEntries(
results.filter((r) => r.enabled && r.payload !== null).map((r) => [r.key, r.payload])
)

Missing flags

For a flag that isn't in the loaded flags, getFeatureFlag() returns undefined and isFeatureEnabled() returns false, like posthog-ios, posthog-android and posthog_flutter:

Call4.x before flags load4.x after a load that returned flags5.0
getFeatureFlag(key)undefinedfalseundefined
isFeatureEnabled(key)undefinedfalsefalse, or defaultValue if you pass one
getFeatureFlagResult(key)undefinedundefinedundefined

This also covers a failed first load and globally inactive flags, which /flags leaves out. A flag that has a value, including false, reads as before.

To tell a flag that is off from one with no value, use getFeatureFlagResult(key), which returns undefined only when there's no value. Replace getFeatureFlag(key) === false with getFeatureFlagResult(key)?.enabled === false where you mean "off", and isFeatureEnabled(key) === undefined with getFeatureFlagResult(key) === undefined where you mean "no value yet". A 4.x isFeatureEnabled(key) ?? fallback never reaches fallback in 5.0, since the call returns false: pass it as isFeatureEnabled(key, { defaultValue: fallback }).

Payloads

A payload that isn't valid JSON, including an empty one, reads as null. In 4.x it read as its raw string. Valid JSON payloads, including "text" with quotes, false, 0 and null, read as before. A string payload in bootstrap.featureFlagPayloads stays a string: "123" reads as "123", where 4.x read it as 123.

Empty-string variants

A flag whose variant is an empty string reads as disabled everywhere: getFeatureFlagResult() and getAllFeatureFlags() return enabled: false for it, as isFeatureEnabled() already did, and it's left out of $active_feature_flags. Disabled flags are also left out of $active_feature_flags.

Feature flag hooks

The hooks match @posthog/react:

4.x5.0
useFeatureFlag(key) for the valueuseFeatureFlagVariantKey(key)
useFeatureFlag(key) for on/offuseFeatureFlagEnabled(key)
useFeatureFlags()useActiveFeatureFlags() for the enabled flag keys
useFeatureFlagWithPayload(key)useFeatureFlagResult(key), which returns { key, enabled, variant, payload } (or undefined) instead of a [value, payload] tuple, or useFeatureFlagPayload(key) for the payload alone. The FeatureFlagWithPayload type is removed.

For a flag that isn't in the loaded flags, useFeatureFlagVariantKey() and useFeatureFlagEnabled() return undefined, or the default you pass to useFeatureFlagEnabled(), where useFeatureFlag() returned false. Check for a falsy value instead of === false. The hooks follow @posthog/react, so before flags load useFeatureFlagEnabled(key) returns undefined while isFeatureEnabled(key) returns false.

useFeatureFlagEnabled(key, defaultValue?, client?) takes the client third. In JavaScript, useFeatureFlagEnabled(key, client) reads the client as the default, so call useFeatureFlagEnabled(key, undefined, client).

useFeatureFlagResult() keeps its shape, and reads an empty-string variant as disabled (see Empty-string variants).

Event delivery

  • Queued events are sent every 30 seconds instead of every 10, and at most 50 per request instead of 100, like posthog-ios and posthog-android. Pass flushInterval: 10000 and maxBatchSize: 100 to keep the 4.x timing. A queue of flushAt events (20 by default) is still sent right away.

  • Authorization, User-Agent, Content-Type, Content-Encoding and the PostHog- headers the SDK sets no longer reach capture requests from requestHeaders; the SDK sets its own. Other requestHeaders still do, and feature flag requests still get all of them.

  • Events stay queued when a send gets no response, a 404, 408, 429, 500, 502, 503 or 504, or a retry result. They're sent again after a wait of about 1 second doubling to 30 seconds, longer if the server's Retry-After asks (up to 30 seconds), with no attempt limit. fetchRetryCount and fetchRetryDelay no longer apply to events.

  • flush() and shutdown() no longer reject when delivery fails. Events either stay queued for a later send or are dropped and reported through posthog.on('error').

  • posthog.on('error') no longer fires for network errors or retryable statuses while events stay queued. It still fires for dropped events, with a different error that has no response. It carries endpoint, requestId, drops (events rejected one by one, each with its uuid and details), retryExhausted (the uuids of events lost when a whole batch failed, such as on a 400 or 401) and cause (the error behind a whole-batch failure).

    TypeScript
    // 4.x
    posthog.on('error', (err) => report(err.response?.status))
    // 5.0
    posthog.on('error', (err) => report(err.message, (err.drops?.length ?? 0) + (err.retryExhausted?.length ?? 0)))
  • Event uuids are sent in lowercase, and a uuid you pass that isn't a valid UUID is replaced with a new one.

  • PostHog drops an event whose distinct ID or name is over 200 UTF-8 bytes (distinct_id_too_large, event_name_too_long), and posthog.on('error') reports it. 4.x capture shortened the distinct ID and kept the event.

  • Each request carries up to 5 MiB of events. A batch that gets a 413 is split and sent again; a single event that gets a 413 is dropped.

  • The SDK sends as soon as 5 MiB of events is queued, without waiting for flushAt.

  • A batch whose request reaches requestTimeout is sent again in batches half the size, so a slow network still delivers it.

identify()

identify() takes a required distinct ID, like posthog-ios, posthog-android and posthog_flutter. In 4.x the type let you leave it out: identify() did nothing, and identify(undefined, properties) set person properties. Call setPersonProperties() for that instead. An empty or whitespace-only distinct ID (identify(''), identify(' ')) logs a warning and is ignored, where 4.x saved the blank distinct ID or sent $set for the current user.

TypeScript
// 4.x
posthog.identify(undefined, { plan: 'pro' })
// 5.0
posthog.setPersonProperties({ plan: 'pro' })

Event properties

5.0 sets person properties on events the way posthog-ios 4.0, posthog-android 4.0 and posthog_flutter 6.0 do:

  • A registered or caller $is_identified or $process_person_profile replaces the SDK's value on that event. In 4.x the SDK's value always won. A null $process_person_profile counts as unset; a null $is_identified sends the event without $is_identified. A registered $process_person_profile: false now makes every event personless, also after identify(), and true processes anonymous users under personProfiles: 'identified_only'. Neither changes the personProfiles policy.
  • $identify, $create_alias, $groupidentify, $merge_dangerously, $set and $set_once events leave off a registered $process_person_profile. In 4.x, registering false sent it on them, and PostHog dropped them, so identify(), alias() and group() had no effect. A before_send hook can still set it, and so can a value passed on a $set, $set_once or $merge_dangerously call.
  • Person processing is sent as posthog-ios and posthog-android 4.0 send it: an event that doesn't process the person gets the process_person_profile: false capture v1 option, and one that does gets none, since PostHog processes the person by default. In 4.x every event carried a $process_person_profile property of true or false. Now events carry no $process_person_profile property unless you set one, so before_send doesn't see it, and removing or changing $process_person_profile there doesn't make a personless event process the person.
  • $autocapture events carry $is_identified, and get the process_person_profile: false option when the person isn't processed, like other events, so anonymous autocapture follows personProfiles: 'identified_only'. In 4.x they carried neither, and PostHog processed the person.
  • null and undefined property values are left off events, except inside $set, $set_once and $group_set, where a null still clears the property. Array elements keep their positions.
  • A registered property replaces the SDK's own value of the same name, such as $os_name, $app_version, $screen_width, $feature/<key> or $active_feature_flags, and a property passed on the call wins over both. In 4.x the SDK's value replaced a registered one. Unregister a property to send the SDK's value again.
  • $lib and $lib_version are filled as a pair after your properties. A $lib you pass or register without $lib_version is sent without one, so the SDK's version isn't attributed to another library, and a $lib_version without $lib is replaced by the SDK's pair. In 4.x the SDK's pair replaced a registered one, and a caller $lib got the SDK's $lib_version.
  • A $groups passed in the properties of capture(), screen() or captureException() adds to the groups set with group() on that event, the passed key winning per group type. In 4.x it was saved as if passed to group(), reloading feature flags and processing an anonymous user's person under personProfiles: 'identified_only', and the event carried only the passed groups. Now it applies to that event only: call group() for groups that should stay on later events and count for feature flags. A $groups passed to identify() is no longer saved either; in 4.x it was saved as if passed to group().
  • A registered or caller $session_id is sent on that event instead of the SDK's session id. A null, blank or non-string one counts as unset. In 4.x the SDK's session id always won.
  • $session_id and $window_id are sent as the top-level session_id and window_id fields of the event, like posthog-ios and posthog-android 4.0. A $window_id that isn't a string, such as a number, or a $session_id that before_send sets to one, is dropped with a console warning, and the event is sent without it. In 4.x they were sent as properties.
  • A registered or caller $geoip_disable wins over the disableGeoip option. A per-call disableGeoip capture option wins over the disableGeoip option and a registered value, and is sent as $geoip_disable: true or false. A $geoip_disable passed on the call wins over all of them. In 4.x disableGeoip: true always sent $geoip_disable: true, and a per-call disableGeoip: false sent nothing.
  • A registered or caller $recording_status or $sdk_debug_* property wins over the SDK's session replay debug value, except $sdk_debug_pending_queue_size, which the SDK always sets. In 4.x the SDK's values replaced them.
  • $feature_flag_called events carry $used_bootstrap_value only for a flag set in bootstrap.featureFlags, as posthog-ios and posthog-android send it. In 4.x every $feature_flag_called event carried it. Filter on $feature_flag_bootstrapped_response being set to find flag calls for bootstrapped flags.

Per-event options

Settings that tell PostHog how to process an event go in options, like posthog-ios 4.0 and posthog-android 4.0. capture(), screen(), identify(), setPersonProperties(), unsetPersonProperties(), alias(), group(), groupIdentify(), captureException() and captureAi() take them in their options argument:

TypeScript
// 4.x
posthog.capture('signed_up', { $process_person_profile: false })
// 5.0
posthog.capture('signed_up', {}, { options: { process_person_profile: false } })
OptionLegacy property
process_person_profile$process_person_profile
cookieless_mode$cookieless_mode
disable_skew_correction$ignore_sent_at
product_tour_id$product_tour_id

The legacy properties still work and are sent as their options, with their values unchanged, and an option wins over its property. PostHog reads common forms of a value, such as '1', 'false' or 0 for a boolean, and drops an event whose option value it can't read (invalid_options), such as $cookieless_mode: 'maybe' or $product_tour_id: 1.5, where 4.x sent it as a property; posthog.on('error') reports it. Pass true or false for $process_person_profile, $cookieless_mode and $ignore_sent_at, and a string for $product_tour_id. before_send reads and changes options through event.options. A hook that returns a new event keeps them unless it sets options, and options: {} removes the ones passed on the call.

App lifecycle events

5.0 captures app lifecycle events the way posthog-ios and posthog-android do:

  • A return from the background captures Application Opened with from_background: true. In 4.x it captured Application Became Active, which 5.0 no longer sends. The Application Opened captured at launch carries from_background: false, so charts of Application Opened count more events after the upgrade.
  • A launch in the background, such as a background fetch on iOS, captures its Application Opened when the app first comes to the foreground, and none if it never does. In 4.x it was captured at launch on iOS. On Android, 4.x already waited for the first foreground.
  • Application Backgrounded is captured once each time the app goes to the background. In 4.x a repeated background AppState callback captured it again.
  • Returning to active from inactive without going to the background, such as closing Control Center or a system dialog on iOS, captures nothing. In 4.x it captured Application Became Active. On Android, React Native reports an activity pause, such as a permission dialog, as going to the background, so it captures Application Backgrounded and then Application Opened with from_background: true. posthog-android captures neither.

Replace Application Became Active in insights, cohorts and actions with Application Opened where from_background is true. To keep counting launches only, filter Application Opened on from_background is not true; 4.x events have no from_background, so filtering on false drops them. Data captured by 4.x keeps its Application Became Active events, so cover both events for date ranges that span the upgrade.

Survey display conditions and session replay event triggers match these events by name. One on Application Became Active no longer fires, and one on Application Opened also fires on every return from the background. A from_background is not true property filter limits a survey to launches, but add it only once your users have upgraded: survey property filters never match an event that lacks the property, even with is not, so 4.x installs stop showing that survey. During the rollout, use separate surveys for 4.x and 5.0 instead. Session replay event triggers can't filter on properties, so a trigger on Application Opened also starts recording on returns from the background. Update before_send and on('capture') code that checks these event names the same way.

Stored state

5.0 keeps each project token's stored state in its own entry, .posthog-rn-<token>.json and .posthog-rn-logs-<token>.json, like posthog-ios and posthog-android, with Expo's file system, AsyncStorage and customStorage alike. In 4.x every client shared .posthog-rn.json and .posthog-rn-logs.json whatever its token, so clients with different tokens overwrote each other's distinct id, opt-out choice, feature flags and queued events.

On the first launch of 5.0, the first client to load takes over the 4.x state: it's written under that client's token's name, and the 4.x entry is removed once that write lands. Logs that 4.x queued and hadn't sent are dropped. A customStorage without the optional removeItem function gets an empty value instead of a removal. Clients with other tokens start with a new anonymous distinct id. An app with one token keeps its users' state.

With several project tokens, only the first token to load keeps the 4.x opt-out choice, as in posthog-ios, which keeps opt-out per token. Clients of the other tokens start opted in (or at the defaultOptIn default), so call optOut() on each client that should stay opted out.

Going back to 4.x after upgrading resets each user's stored PostHog state, because 4.x reads only the entries 5.0 removed:

  • a new anonymous distinct id, so identified users are anonymous until identify() runs again
  • the opt-out choice: users who opted out are opted in again (or set to the defaultOptIn default) until optOut() runs again
  • unsent events and logs, which are not sent
  • the session and cached feature flags

Upgrading to 5.0 again keeps the state 5.0 stored before the rollback and drops what 4.x stored in between, including an opt-out made then.

If you might roll back, keep the user's consent in your own storage and call optOut() from it at startup.

AI events

5.0 adds captureAi(), which sends $ai_generation, $ai_span, $ai_trace, $ai_embedding and other $ai_ events to PostHog's AI endpoint, which accepts much larger events. capture() still sends $ai_ events to the analytics endpoint; switch them to captureAi(). captureTraceFeedback() and captureTraceMetric() now send their $ai_feedback and $ai_metric events through captureAi(), so a reverse proxy must serve /i/v1/ai/events for them.

TypeScript
// 4.x
posthog.capture('$ai_generation', { $ai_model: 'gpt-4o', $ai_trace_id: traceId })
// 5.0
posthog.captureAi('$ai_generation', { $ai_model: 'gpt-4o', $ai_trace_id: traceId })

AI events have their own queue and options:

OptionDefault
captureAiCompression'gzip' (on iOS and Android, needs @posthog/react-native-plugin 3.0 or newer; without it, bodies go uncompressed)
captureAiMaxQueueSize100 events, and at most 50 MiB; the oldest are dropped first
captureAiRequestTimeoutMs60000, in milliseconds. The native SDKs' captureAiTimeout is in seconds, so don't copy their value.
captureAiMaxEventBytes8 MiB plus 64 KiB; a larger event is sent without its $ai_input, $ai_output, $ai_output_choices, $ai_input_state, $ai_output_state and $ai_tools, marked with $ai_content_removal_reason: 'event_too_large'. An event still too large is dropped and captureAi() returns undefined (before the SDK finishes initializing, it returns the UUID and drops the event later)

flushAt, maxBatchSize and flushInterval apply to both queues. disableCompression doesn't affect AI events.

The SDK doesn't redact or truncate prompts, outputs or media; use before_send to strip them. With Expo's file system as storage (the default where expo-file-system is installed), unsent AI events are stored in the app's cache directory, which isn't backed up, and survive a restart; the OS may clear that directory when the device is low on space. With any customStorage, AsyncStorage included, with @react-native-async-storage/async-storage as storage (the default without Expo's file system), or with persistence: 'memory', they're kept in memory only, so they're lost if the app is killed before they're sent.

Was this page useful?