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-pluginolder than 3.0 (see Session replay and the native plugin) - passes
apiKeytoPostHogProvider, or setsevaluationEnvironments,disableRemoteConfig,disable_capture_url_hashes,sessionReplayConfig.iOSdebouncerDelayMs,sessionReplayConfig.androidDebouncerDelayMs,sessionReplayConfig.screenshotModeBackgroundCaptureorautocapture.navigationRef(see Removed options) - calls
useNavigationTracker()with anavigationRefargument - calls
onFeatureFlags()orreloadFeatureFlagsAsync()(seeonFeatureFlags) - calls
getFeatureFlagPayload(),getFeatureFlags(),getFeatureFlagPayloads(),getFeatureFlagsAndPayloads(),onFeatureFlag()oroverrideFeatureFlag(), or readsgetFeatureFlagDetails()(see Removed feature flag methods) - uses the
useFeatureFlag(),useFeatureFlags()oruseFeatureFlagWithPayload()hooks (see Feature flag hooks) - passes
sendEventtogetFeatureFlag(),getFeatureFlagResult()orisFeatureEnabled() - calls
getAllFeatureFlags(), which returnsundefineduntil flags are cached (seegetAllFeatureFlags) - checks
getFeatureFlag(key) === false,isFeatureEnabled(key) === undefinedorisFeatureEnabled(key) ?? fallbackfor 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
enabledfromgetFeatureFlagResult()orgetAllFeatureFlags()for a flag whose variant is an empty string, or filters on$active_feature_flags - sets
Authorization,User-Agent,Content-Type,Content-Encodingor aPostHog-header the SDK sets inrequestHeadersand expects capture requests to carry it - relies on the default
flushInterval(10 seconds) ormaxBatchSize(100) (see Event delivery) - relies on
fetchRetryCountorfetchRetryDelayfor events, onflush()orshutdown()rejecting when delivery fails, or onposthog.on('error')firing for network errors (see Event delivery) - sends
$ai_events, or callscaptureTraceFeedback()orcaptureTraceMetric()(see AI events) - registers
$is_identifiedor$process_person_profile, or sendsnullproperty values (see Event properties) - registers or passes a
$window_idthat isn't a string, or sets$cookieless_mode,$ignore_sent_ator$product_tour_idto 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_disableor$recording_status(see Event properties) - passes
$groupsin the properties ofcapture(),screen(),captureException()oridentify()(see Event properties) - calls
identify()without a distinct ID (seeidentify()) - 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 ActiveorApplication Backgroundedevents in insights, cohorts, actions, survey display conditions, session replay event triggers,before_sendoron('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:
| Method | 4.x | 5.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/eventsand/i/v1/ai/eventsto PostHog. - Pass
Authorizationthrough unchanged when it starts withBearer phc_, or isBearer <your project token>for a token older than thephc_prefix. The project token is no longer in the request body, and PostHog answers401without it. - Pass every
PostHog-*header,Content-Type,Content-EncodingandUser-Agentthrough unchanged. PostHog answers400without them. - On react-native-web, if your proxy answers CORS preflight requests with a fixed
Access-Control-Allow-Headerslist, addAuthorization,PostHog-Sdk-Info,PostHog-Attempt,PostHog-Request-IdandPostHog-Request-Timestampto it, next toContent-Type,Content-Encodingand anyrequestHeadersyou 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-Afterheader unchanged. The SDK drops a batch whose2xxresponse has no PostHogresultsbody, and waits as long asRetry-Afterasks, up to 30 seconds, before it resends. On react-native-web, if your proxy sets its own CORS response headers, addAccess-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
requestHeadersto that origin. The native SDKs follow only same-origin307and308redirects.
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.
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.x | 5.0 |
|---|---|
<PostHogProvider apiKey="phc_…"> | <PostHogProvider projectToken="phc_…">. In JavaScript, a leftover apiKey prop is ignored with a warning and the client is disabled. |
evaluationEnvironments | evaluationContexts |
disableRemoteConfig | Remove it. It had no effect. |
disable_capture_url_hashes | Remove it. It had no effect: React Native doesn't capture page URLs. |
sessionReplayConfig.iOSdebouncerDelayMs, sessionReplayConfig.androidDebouncerDelayMs | sessionReplayConfig.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: true | Remove it. posthog-ios 4.0 removed background capture. sessionReplayConfig.iOSCaptureMethod takes 'standard' (the default) or experimental 'gpu'. |
autocapture.navigationRef, the PostHogNavigationRef type | Remove 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:
flagslists the keys of enabled flags. Disabled flags are left out; read them withgetFeatureFlagResult(key).variantsmaps each enabled flag totrueor its variant.errorsLoadingistruewhen the latest load failed.flagsandvariantsthen 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.x | 5.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.
Where you only iterate, use posthog.getAllFeatureFlags() ?? [].
To build the 4.x maps from getAllFeatureFlags():
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:
| Call | 4.x before flags load | 4.x after a load that returned flags | 5.0 |
|---|---|---|---|
getFeatureFlag(key) | undefined | false | undefined |
isFeatureEnabled(key) | undefined | false | false, or defaultValue if you pass one |
getFeatureFlagResult(key) | undefined | undefined | undefined |
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.x | 5.0 |
|---|---|
useFeatureFlag(key) for the value | useFeatureFlagVariantKey(key) |
useFeatureFlag(key) for on/off | useFeatureFlagEnabled(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: 10000andmaxBatchSize: 100to keep the 4.x timing. A queue offlushAtevents (20 by default) is still sent right away. -
Authorization,User-Agent,Content-Type,Content-Encodingand thePostHog-headers the SDK sets no longer reach capture requests fromrequestHeaders; the SDK sets its own. OtherrequestHeadersstill 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,503or504, or aretryresult. They're sent again after a wait of about 1 second doubling to 30 seconds, longer if the server'sRetry-Afterasks (up to 30 seconds), with no attempt limit.fetchRetryCountandfetchRetryDelayno longer apply to events. -
flush()andshutdown()no longer reject when delivery fails. Events either stay queued for a later send or are dropped and reported throughposthog.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 noresponse. It carriesendpoint,requestId,drops(events rejected one by one, each with itsuuidanddetails),retryExhausted(the uuids of events lost when a whole batch failed, such as on a400or401) andcause(the error behind a whole-batch failure).TypeScript -
Event uuids are sent in lowercase, and a
uuidyou 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), andposthog.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
413is split and sent again; a single event that gets a413is dropped. -
The SDK sends as soon as 5 MiB of events is queued, without waiting for
flushAt. -
A batch whose request reaches
requestTimeoutis 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.
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_identifiedor$process_person_profilereplaces the SDK's value on that event. In 4.x the SDK's value always won. Anull$process_person_profilecounts as unset; anull$is_identifiedsends the event without$is_identified. A registered$process_person_profile: falsenow makes every event personless, also afteridentify(), andtrueprocesses anonymous users underpersonProfiles: 'identified_only'. Neither changes thepersonProfilespolicy. $identify,$create_alias,$groupidentify,$merge_dangerously,$setand$set_onceevents leave off a registered$process_person_profile. In 4.x, registeringfalsesent it on them, and PostHog dropped them, soidentify(),alias()andgroup()had no effect. Abefore_sendhook can still set it, and so can a value passed on a$set,$set_onceor$merge_dangerouslycall.- 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: falsecapture v1 option, and one that does gets none, since PostHog processes the person by default. In 4.x every event carried a$process_person_profileproperty oftrueorfalse. Now events carry no$process_person_profileproperty unless you set one, sobefore_senddoesn't see it, and removing or changing$process_person_profilethere doesn't make a personless event process the person. $autocaptureevents carry$is_identified, and get theprocess_person_profile: falseoption when the person isn't processed, like other events, so anonymous autocapture followspersonProfiles: 'identified_only'. In 4.x they carried neither, and PostHog processed the person.nullandundefinedproperty values are left off events, except inside$set,$set_onceand$group_set, where anullstill 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. $liband$lib_versionare filled as a pair after your properties. A$libyou pass or register without$lib_versionis sent without one, so the SDK's version isn't attributed to another library, and a$lib_versionwithout$libis replaced by the SDK's pair. In 4.x the SDK's pair replaced a registered one, and a caller$libgot the SDK's$lib_version.- A
$groupspassed in the properties ofcapture(),screen()orcaptureException()adds to the groups set withgroup()on that event, the passed key winning per group type. In 4.x it was saved as if passed togroup(), reloading feature flags and processing an anonymous user's person underpersonProfiles: 'identified_only', and the event carried only the passed groups. Now it applies to that event only: callgroup()for groups that should stay on later events and count for feature flags. A$groupspassed toidentify()is no longer saved either; in 4.x it was saved as if passed togroup(). - A registered or caller
$session_idis sent on that event instead of the SDK's session id. Anull, blank or non-string one counts as unset. In 4.x the SDK's session id always won. $session_idand$window_idare sent as the top-levelsession_idandwindow_idfields of the event, like posthog-ios and posthog-android 4.0. A$window_idthat isn't a string, such as a number, or a$session_idthatbefore_sendsets 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_disablewins over thedisableGeoipoption. A per-calldisableGeoipcapture option wins over thedisableGeoipoption and a registered value, and is sent as$geoip_disable: trueorfalse. A$geoip_disablepassed on the call wins over all of them. In 4.xdisableGeoip: truealways sent$geoip_disable: true, and a per-calldisableGeoip: falsesent nothing. - A registered or caller
$recording_statusor$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_calledevents carry$used_bootstrap_valueonly for a flag set inbootstrap.featureFlags, as posthog-ios and posthog-android send it. In 4.x every$feature_flag_calledevent carried it. Filter on$feature_flag_bootstrapped_responsebeing 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:
| Option | Legacy 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 Openedwithfrom_background: true. In 4.x it capturedApplication Became Active, which 5.0 no longer sends. TheApplication Openedcaptured at launch carriesfrom_background: false, so charts ofApplication Openedcount more events after the upgrade. - A launch in the background, such as a background fetch on iOS, captures its
Application Openedwhen 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 Backgroundedis captured once each time the app goes to the background. In 4.x a repeatedbackgroundAppState callback captured it again.- Returning to
activefrominactivewithout going to the background, such as closing Control Center or a system dialog on iOS, captures nothing. In 4.x it capturedApplication Became Active. On Android, React Native reports an activity pause, such as a permission dialog, as going to the background, so it capturesApplication Backgroundedand thenApplication Openedwithfrom_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
defaultOptIndefault) untiloptOut()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.
AI events have their own queue and options:
| Option | Default |
|---|---|
captureAiCompression | 'gzip' (on iOS and Android, needs @posthog/react-native-plugin 3.0 or newer; without it, bodies go uncompressed) |
captureAiMaxQueueSize | 100 events, and at most 50 MiB; the oldest are dropped first |
captureAiRequestTimeoutMs | 60000, in milliseconds. The native SDKs' captureAiTimeout is in seconds, so don't copy their value. |
captureAiMaxEventBytes | 8 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.





