> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt # PostHog React Native SDK 5.x Canonical URL: https://posthog.com/docs/libraries/react-native/5.x.x > **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 - [Getting started](#getting-started) - [Setup](#setup) - [Capture](#capture) - [Identify](#identify) - [Logs](#logs) - [Alias](#alias) - [Capture AI](#capture-ai) - [Capture exception](#capture-exception) - [Create person profile](#create-person-profile) - [Debug](#debug) - [Exception steps](#exception-steps) - [Flush](#flush) - [Get anonymous ID](#get-anonymous-id) - [Get distinct ID](#get-distinct-id) - [Get feature flag](#get-feature-flag) - [Get feature flag payload](#get-feature-flag-payload) - [Get feature flag result](#get-feature-flag-result) - [Get feature flags](#get-feature-flags) - [Get session ID](#get-session-id) - [Group](#group) - [Group identify](#group-identify) - [Is feature enabled](#is-feature-enabled) - [Is opt out](#is-opt-out) - [Is session replay active](#is-session-replay-active) - [On feature flags](#on-feature-flags) - [Opt in](#opt-in) - [Register](#register) - [Reload feature flags](#reload-feature-flags) - [Reset](#reset) - [Reset group properties for flags](#reset-group-properties-for-flags) - [Reset person properties for flags](#reset-person-properties-for-flags) - [Screen](#screen) - [Set group properties for flags](#set-group-properties-for-flags) - [Set person properties](#set-person-properties) - [Set person properties for flags](#set-person-properties-for-flags) - [Shutdown](#shutdown) - [Start session recording](#start-session-recording) - [Stop session recording](#stop-session-recording) - [Unregister](#unregister) - [Autocapture](#autocapture) - [Remote config](#remote-config) - [Session replay privacy](#session-replay-privacy) - [Surveys](#surveys) - [SDK utils](#sdk-utils) - [Types](#types) ## Getting started The React Native SDK runs in iOS and Android apps, including Expo apps. To send your first event, install `posthog-react-native` and the peer dependencies that the [install guide](https://posthog.com/docs/product-analytics/installation/react-native) lists for Expo or the React Native CLI. Then wrap your app in `PostHogProvider` with your project token and host from your [project settings](https://app.posthog.com/project/settings), and call `capture` on the client that `usePostHog` returns. ### Install ```bash npm install posthog-react-native ``` ### Initialize Wrap your app in `PostHogProvider`. ```jsx import { PostHogProvider } from 'posthog-react-native' export default function App() { return ( ) } ``` ### Capture an event ```jsx import { usePostHog } from 'posthog-react-native' const posthog = usePostHog() posthog.capture('signed_up', { plan: 'pro' }) ``` ### Identify a user ```jsx posthog.identify('user_123', { email: 'user@example.com' }) ``` ### Offline behavior The SDK keeps capturing events while the device is offline. With the default `persistence: 'file'`, events stay queued in device file storage across app restarts and flush once the device is online. - `maxQueueSize` sets the maximum number of queued events. - When the queue is full, the oldest event is evicted first. ### Disable for local development Pass `disabled: __DEV__` in `PostHogProvider` options to turn off tracking during development. Calls through `usePostHog()` still work as safe no-ops. ```jsx import { PostHogProvider } from 'posthog-react-native' export function App() { return ( ) } ``` ### Proxy, projects, and allowlists - Set up a [reverse proxy](https://posthog.com/docs/advanced/proxy) so tracking blockers don't drop events. - If you run a website and mobile app together, [group them in one project](https://posthog.com/docs/settings/projects) to track users across platforms. - If a firewall or WAF blocks PostHog requests, allowlist PostHog's public IPs listed in the [webhook IP allowlist](https://posthog.com/docs/data-pipelines/destinations/webhook). ### Choose an iOS dependency path for the native plugin The optional `@posthog/react-native-plugin` package needs `posthog-ios`. Choose one path to resolve it. | Path | Requirements | Setup | | --- | --- | --- | | CocoaPods | React Native 0.75 or later and Xcode 26 or later | Run `pod install` in `ios`. The plugin podspec resolves `posthog-ios` 4.0 through Swift Package Manager. This is the default. | | Full Swift Package Manager | `@posthog/react-native-plugin` 3.0 or later, Xcode 26 or later, and an iOS 15 or later deployment target | Run `npx react-native spm add --deintegrate --yes` in `ios`. Don't run `pod install`. | The full path uses React Native's experimental integration without CocoaPods. Every native dependency in your app must support it. `--deintegrate` removes CocoaPods from the iOS project, so commit or back up the project first. PostHog verifies this path with an iOS-only React Native 0.87.1 app and React Native Community CLI 20.2.0. It is not verified with Expo. Both paths need an iOS 15 or later deployment target. ### Minimum versions - `disableRemoteFeatureFlags` needs 4.49.0 or later. ### Upgrade from an older major | From | Change | | --- | --- | | 1.x.x | Replace `PostHog.setup(...)` with `new PostHog(token, options)` or `PostHogProvider`. `PostHogProvider` replaces `captureApplicationLifecycleEvents` and `recordScreenViews`. Remove `captureDeepLinks`, `android`, and `iOS`. | | 2.x.x | Replace `await PostHog.initAsync(...)` with `new PostHog(token, options)`. | | 3.x.x | Rename `captureNativeAppLifecycleEvents` and `autocapture={{ captureLifecycleEvents: true }}` to `captureAppLifecycleEvents`. Remove `captureMode` and `maskPhotoLibraryImages`. Call `setPersonPropertiesForFlags` and `setGroupPropertiesForFlags` in place of `personProperties` and `groupProperties`. | | 4.x.x | See the [migration guide](https://github.com/PostHog/posthog-js/blob/main/packages/react-native/MIGRATION.md). | 1.x.x wrapped the native iOS and Android SDKs. Later majors are written in JavaScript. On iOS, the SDK migrates the persisted distinct ID and anonymous ID. On Android, it can't load them, so call `identify` when the app loads. Anonymous Android users appear as new users. The SDK can't detect a real install. It stores a marker the first time it loads and sends `Application Installed` then. Expect more `Application Installed` events after you upgrade from 1.x.x. ## Setup ### `new PostHog(...)` > **new PostHog**(`projectToken`, `options?`): `PostHog` Creates a new PostHog instance for React Native. See [`PostHogOptions`](#posthogoptions) for all configuration options. If you prefer not to use the PostHogProvider, you can initialize PostHog in its own file and import the instance from there. #### Parameters | Parameter | Type | Description | | --- | --- | --- | | `projectToken` | `string` | Your PostHog project token, which starts with `phc_`. Find it in your project settings: [https://us.posthog.com/settings/project-details#variables](https://us.posthog.com/settings/project-details#variables) | | `options?` | `PostHogOptions` | PostHog configuration options | #### Returns `PostHog` #### Example ```typescript // posthog.ts import PostHog from 'posthog-react-native' export const posthog = new PostHog('', { host: 'https://us.i.posthog.com' }) // Then you can access PostHog by importing your instance // Another file: import { posthog } from './posthog' export function MyApp1() { useEffect(async () => { posthog.capture('event_name') }, [posthog]) return Your app code } ``` ### `PostHogProvider` > **PostHogProvider**(`props`): `Element` | `null` PostHogProvider is a React component that provides PostHog functionality to your React Native app. See [`PostHogOptions`](#posthogoptions) for all configuration options. Autocapturing navigation requires further configuration. See [`PostHogAutocaptureOptions`](#posthogautocaptureoptions) for more information about autocapturing navigation. This is the recommended way to set up PostHog for React Native. This utilizes the Context API to pass the PostHog client around, enable autocapture. #### Parameters | Parameter | Type | Description | | --- | --- | --- | | `props` | `PostHogProviderProps` | The PostHogProvider props | #### Returns `Element` | `null` #### Examples ```jsx // Add to App.(js|ts) import { usePostHog, PostHogProvider } from 'posthog-react-native' export function MyApp() { return ( ) } // And access the PostHog client via the usePostHog hook import { usePostHog } from 'posthog-react-native' const MyComponent = () => { const posthog = usePostHog() useEffect(() => { posthog.capture("event_name") }, [posthog]) } ``` ```jsx // Using with existing client import { PostHog } from 'posthog-react-native' const posthog = new PostHog('', { host: 'https://us.i.posthog.com' }) export function MyApp() { return ( ) } ``` ### `usePostHog` > **usePostHog**(): `PostHog` #### Returns `PostHog` ## Capture ### `PostHog.capture` > **capture**(`event`, `properties?`, `options?`): `void` Captures an event. #### Parameters | Parameter | Type | Description | | --- | --- | --- | | `event` | `string` | The name of the event | | `properties?` | `PostHogEventProperties` | Optional properties to include with the event | | `options?` | `PostHogCaptureOptions` | Optional capture options | #### Returns `void` #### Examples ```javascript posthog.capture('signed_up', { plan: 'pro' }) ``` ```javascript // Tell PostHog not to create or update a person profile for this event posthog.capture('signed_up', { plan: 'pro' }, { options: { process_person_profile: false } }) ``` ### `CaptureError` Surfaced on the client error channel whenever a capture batch did not fully deliver: some events were `drop`ped, some `retry` events outlived the attempt budget, or the batch hit a terminal transport/HTTP/parse failure. A 2xx with drops is still a partial failure and is reported here — a successful HTTP status does not mean every event was accepted. #### Extends - `Error` #### Constructors ##### Constructor > **new CaptureError**(`options`): `CaptureError` ###### Parameters | Parameter | Type | | --- | --- | | `options` | `CaptureErrorParams` | ###### Returns `CaptureError` #### Properties | Property | Modifier | Type | Overrides | | --- | --- | --- | --- | | `cause?` | `public` | `unknown` | `Error.cause` | | `drops` | `readonly` | `CaptureDroppedEvent`\[\] | \- | | `endpoint` | `readonly` | `CaptureEndpoint` | \- | | `name` | `public` | `string` | `Error.name` | | `requestId` | `readonly` | `string` | \- | | `retryExhausted` | `readonly` | `string`\[\] | \- | ## Identify ### `PostHog.identify` > **identify**(`distinctId`, `properties?`, `options?`): `void` Associates events with a specific user. Learn more about [identifying users](https://posthog.com/docs/product-analytics/identify) #### Parameters | Parameter | Type | Description | | --- | --- | --- | | `distinctId` | `string` | A unique identifier for your user. Typically either their email or database ID. | | `properties?` | `PostHogEventProperties` | Optional dictionary with key:value pairs to set the person properties | | `options?` | `PostHogCaptureOptions` | Optional capture options | #### Returns `void` #### Examples ```javascript // Basic identify posthog.identify('distinctID', { email: 'user@posthog.com', name: 'My Name' }) ``` ```javascript // Using $set and $set_once posthog.identify('distinctID', { $set: { email: 'user@posthog.com', name: 'My Name' }, $set_once: { date_of_first_log_in: '2024-03-01' } }) ``` ## Logs ### `PostHog.logger` > **get** **logger**(): `Logger` Convenience per-level logger. Each method is shorthand for `posthog.captureLog({ body, level, attributes })`. Lazily constructed on first access, then reused. ##### Example ```typescript posthog.logger.info('checkout completed', { order_id: 'ord_789' }) posthog.logger.error('payment failed', { code: 'E001' }) ``` ##### Returns `Logger` ### `PostHog.captureLog` > **captureLog**(`options`): `void` Captures a structured log record and sends it to PostHog's logs product (`/i/v1/logs`). Low-level primitive — most callers will prefer `posthog.logger.info(...)` / `.warn(...)` / `.error(...)` etc., which wrap this with a level pre-set. Records are buffered per-session, rate-limited, batched into OTLP payloads, and flushed on a timer, on AppState change, or when the buffer reaches capacity. Configure flush cadence, rate cap, and a `beforeSend` filter via the `logs` option on `new PostHog(...)`. Note — naming collision: `posthog.captureLog()` (this method) is the **logs product** API. There is also a separate, pre-existing `sessionReplayConfig.captureLog` boolean that controls whether **session replay** records the device's `console.*` output. The two are unrelated: this method emits structured records to the logs pipeline regardless of whether session replay is on. #### Parameters | Parameter | Type | Description | | --- | --- | --- | | `options` | `CaptureLogOptions` | Log record. `body` is required; `level` defaults to `'info'`. `attributes` are attached as OTLP key-value attributes and will override auto-populated ones (distinctId, sessionId) on key conflict. | #### Returns `void` #### Example ```typescript posthog.captureLog({ body: 'checkout completed', level: 'info', attributes: { order_id: 'ord_789', amount_cents: 4999 }, }) ``` ### `PostHog.flushLogs` > **flushLogs**(): `Promise`<`void`\> Manually flushes the logs queue. Logs flush automatically on a timer, when the buffer fills, or on AppState change — most apps never need to call this. Use it when you want a synchronous-style hand-off (e.g. before navigating away from a critical screen, in a custom crash handler, or while testing locally). If a flush is already in progress, both callers join the same in-flight promise — no double-send. Note: this drains the **logs** pipeline only. Events are flushed via flush, and shutdown drains both before terminating. #### Returns `Promise`<`void`\> Promise that resolves when the flush is complete. #### Example ```typescript await posthog.flushLogs() ``` #### See flush ## Alias ### `PostHog.alias` > **alias**(`alias`, `options?`): `void` Assigns an alias to the current user. Sometimes, you want to assign multiple distinct IDs to a single user. This is helpful when your primary distinct ID is inaccessible. For example, if a distinct ID used on the frontend is not available in your backend. #### Parameters | Parameter | Type | Description | | --- | --- | --- | | `alias` | `string` | The alias to assign to the current user | | `options?` | `PostHogCaptureOptions` | Optional capture options for the `$create_alias` event | #### Returns `void` #### Example ```javascript // set alias for current user posthog.alias('distinct_id') ``` ## Capture AI ### `PostHog.captureAi` > **captureAi**(`event`, `properties?`, `options?`): `string` | `undefined` Captures an AI observability event, such as `$ai_generation`, `$ai_span`, `$ai_trace` or `$ai_embedding`, and sends it to PostHog's AI endpoint (`/i/v1/ai/events`), which accepts much larger events than PostHog.capture. Takes the same arguments as `capture()` and goes through the same `before_send`. The event is queued separately from other events. The SDK doesn't redact or truncate prompts, outputs or media, but an event over `captureAiMaxEventBytes` (8 MiB plus 64 KiB by default) is sent without `$ai_input`, `$ai_output`, `$ai_output_choices`, `$ai_input_state`, `$ai_output_state` and `$ai_tools`, and one still over it is dropped. PostHog drops an event sent here whose name doesn't start with `$ai_`. `capture()` never sends events here, even ones named `$ai_*`. AI events use `flushAt`, `maxBatchSize` and `flushInterval` like other events, and `captureAiCompression`, `captureAiMaxQueueSize` and `captureAiRequestTimeoutMs` instead of the analytics settings. Requests carry up to about 5 MiB of events, and the SDK sends as soon as that much is queued. Up to 50 MiB of AI events are kept; beyond that, the oldest are dropped. #### Parameters | Parameter | Type | Description | | --- | --- | --- | | `event` | `string` | The AI event name, such as `$ai_generation` | | `properties?` | `PostHogEventProperties` | Properties attached only to this event | | `options?` | `PostHogCaptureOptions` | Same options as `capture()` | #### Returns `string` | `undefined` The event's UUID, or `undefined` if it wasn't queued: the SDK is disabled, opted out or shut down, the name is empty, `before_send` dropped it, or it's over `captureAiMaxEventBytes` even without its AI content. Before the SDK finishes initializing it returns the UUID, and those checks run once initialization completes. #### Example ```javascript posthog.captureAi('$ai_generation', { $ai_trace_id: traceId, $ai_model: 'gpt-4o', $ai_provider: 'openai', }) ``` ### `PostHog.captureTraceFeedback` > **captureTraceFeedback**(`traceId`, `userFeedback`): `void` Capture written user feedback for a LLM trace, as an `$ai_feedback` event sent with PostHog.captureAi. Numeric values are converted to strings. #### Parameters | Parameter | Type | Description | | --- | --- | --- | | `traceId` | `string` \| `number` | The trace ID to capture feedback for. | | `userFeedback` | `string` | The feedback to capture. | #### Returns `void` ### `PostHog.captureTraceMetric` > **captureTraceMetric**(`traceId`, `metricName`, `metricValue`): `void` Capture a metric for a LLM trace, as an `$ai_metric` event sent with PostHog.captureAi. Numeric values are converted to strings. #### Parameters | Parameter | Type | Description | | --- | --- | --- | | `traceId` | `string` \| `number` | The trace ID to capture the metric for. | | `metricName` | `string` | The name of the metric to capture. | | `metricValue` | `string` \| `number` \| `boolean` | The value of the metric to capture. | #### Returns `void` ## Capture exception ### `PostHog.captureException` > **captureException**(`error`, `additionalProperties?`, `hint?`, `options?`): `void` Capture a caught exception manually Exceptions also include capture-time `$app_state` (active, background, inactive or extension) on any platform where React Native AppState provides a known value. On iOS and Android, optional `expo-updates` (0.25.0 or newer) adds `$expo_update_id`, `$expo_runtime_version`, `$expo_channel` and `$expo_is_embedded_launch` for enabled updates outside development mode. Unknown values are omitted. These exception-only fields are separate from the static app metadata controlled by `customAppProperties`, including the existing `$app_version` and `$app_build`. Override these fields with `additionalProperties`, or remove them using `before_send`. #### Parameters | Parameter | Type | Description | | --- | --- | --- | | `error` | `unknown` | The error to capture | | `additionalProperties?` | `PostHogEventProperties` | Any additional properties to add to the error event | | `hint?` | `EventHint` | Optional details about how the error was caught | | `options?` | `PostHogCaptureOptions` | Optional capture options for the `$exception` event | #### Returns `void` #### Examples ```javascript // Capture a caught exception try { // something that might throw } catch (error) { posthog.captureException(error) } ``` ```javascript // With additional properties posthog.captureException(error, { customProperty: 'value', anotherProperty: ['I', 'can be a list'], ... }) ``` ### `PostHogErrorBoundary` Captures errors thrown while rendering its children and shows `fallback` in their place. React also logs render errors to the console, so with console capture enabled each render error is captured twice. Set `errorTracking: { autocapture: { console: [] } }` to avoid this. #### Extends - `Component`<`PostHogErrorBoundaryProps`, `PostHogErrorBoundaryState`\> #### Constructors ##### Constructor > **new PostHogErrorBoundary**(`props`): `PostHogErrorBoundary` ###### Parameters | Parameter | Type | | --- | --- | | `props` | `PostHogErrorBoundaryProps` | ###### Returns `PostHogErrorBoundary` #### Properties | Property | Modifier | Type | Default value | Description | Overrides | | --- | --- | --- | --- | --- | --- | | `context` | `public` | `object` | `undefined` | If using the new style context, re-declare this in your class to be the `React.ContextType` of your `static contextType`. Should be used with type annotation or static contextType. `static contextType = MyContext // For TS pre-3.7: context!: React.ContextType // For TS 3.7 and above: declare context: React.ContextType` **See** [https://react.dev/reference/react/Component#context](https://react.dev/reference/react/Component#context) | `React.Component.context` | | `context.client` | `public` | `PostHog` | `undefined` | \- | \- | | `contextType` | `static` | `Context`<{ `client`: `PostHog`; }> | `PostHogContext` | If set, `this.context` will be set at runtime to the current value of the given Context. Usage: `type MyContext = number const Ctx = React.createContext(0) class Foo extends React.Component { static contextType = Ctx context!: React.ContextType render () { return <>My context's value: {this.context}; } }` **See** [https://react.dev/reference/react/Component#static-contexttype](https://react.dev/reference/react/Component#static-contexttype) | `React.Component.contextType` | #### Methods ##### componentDidCatch() > **componentDidCatch**(`error`, `errorInfo`): `void` Catches exceptions generated in descendant components. Unhandled exceptions will cause the entire component tree to unmount. ###### Parameters | Parameter | Type | | --- | --- | | `error` | `unknown` | | `errorInfo` | `ErrorInfo` | ###### Returns `void` ##### render() > **render**(): `ReactNode` ###### Returns `ReactNode` ##### getDerivedStateFromError() > `static` **getDerivedStateFromError**(`error`): `Partial`<`PostHogErrorBoundaryState`\> ###### Parameters | Parameter | Type | | --- | --- | | `error` | `unknown` | ###### Returns `Partial`<`PostHogErrorBoundaryState`\> ## Create person profile ### `PostHog.createPersonProfile` > **createPersonProfile**(): `void` Creates a person profile for the current user, if they don't already have one. This is useful when using `personProfiles: 'identified_only'` mode and you want to explicitly create a profile for an anonymous user before they identify. If `personProfiles` is 'identified\_only' and no profile exists, this will create one. If `personProfiles` is 'never', this will log an error and do nothing. If `personProfiles` is 'always' or a profile already exists, this is a no-op. #### Returns `void` #### Example ```javascript // Create a person profile for an anonymous user posthog.createPersonProfile() ``` ## Debug ### `PostHog.isDebug` > **get** **isDebug**(): `boolean` ##### Returns `boolean` ### `PostHog.debug` > **debug**(`enabled?`): `void` Enables or disables debug mode for detailed logging. #### Parameters | Parameter | Type | Default value | | --- | --- | --- | | `enabled?` | `boolean` | `true` | #### Returns `void` #### Remarks Debug mode logs all PostHog calls to the console for troubleshooting. This is useful during development to understand what data is being sent. #### Examples ```javascript // enable debug mode posthog.debug(true) ``` ```javascript // disable debug mode posthog.debug(false) ``` ## Exception steps ### `PostHog.addExceptionStep` > **addExceptionStep**(`message`, `properties?`): `void` Records a breadcrumb-style exception step. Steps accumulate in a rolling, byte-bounded buffer and are attached to every captured `$exception` as `$exception_steps`, giving the error tracking UI a timeline of recent activity before each error. The `$timestamp` is captured at call time. The reserved keys `$message` and `$timestamp` are stripped from `properties` — the SDK sets the canonical values. This method never throws. #### Parameters | Parameter | Type | Description | | --- | --- | --- | | `message` | `string` | A non-empty description of the step | | `properties?` | `Properties` | Optional additional context to attach to the step | #### Returns `void` #### Example ```javascript posthog.addExceptionStep('User tapped Checkout', { screen: 'cart' }) ``` ## Flush ### `PostHog.flush` > **flush**(): `Promise`<`void`\> Manually flushes the event queue. You can set the number of events in the configuration that should queue before flushing. Setting this to 1 will send events immediately and will use more battery. This is set to 20 by default. You can also manually flush the queue. If a flush is already in progress it returns a promise for the existing flush. Note: this drains the **events** pipeline only. Logs are flushed via flushLogs, and shutdown drains both before terminating. #### Returns `Promise`<`void`\> Promise that resolves when the flush is complete. Events PostHog didn't accept for now, such as after a network error or a `503`, stay queued and are sent again after a wait; a flush during that wait resolves without sending. Events PostHog dropped, such as after a `400` or `401`, are reported on `posthog.on('error')`. The promise resolves in all these cases. #### Example ```javascript // manually flush the queue await posthog.flush() ``` #### See flushLogs ### `PostHog.flushWithPendingPromises` > **flushWithPendingPromises**(): `Promise`<`void`\> Flushes the queue of pending events. This function will return a promise that will resolve when the flush is complete, or reject if there was an error (for example if the server or network is down). If there is already a flush in progress, this function will wait for that flush to complete. It's recommended to do error handling in the callback of the promise. #### Returns `Promise`<`void`\> #### Example ```javascript // flush with error handling posthog.flush().then(() => { console.log('Flush complete') }).catch((err) => { console.error('Flush failed', err) }) ``` #### Throws PostHogFetchHttpError #### Throws PostHogFetchNetworkError #### Throws Error ## Get anonymous ID ### `PostHog.getAnonymousId` > **getAnonymousId**(): `string` Returns the current anonymous ID. This is the ID assigned to users before they are identified. It's used to track anonymous users and link them to identified users when they sign up. #### Returns `string` The stored anonymous ID. This may be an empty string if the client is not yet fully initialized. #### Example ```javascript // get the anonymous ID const anonId = posthog.getAnonymousId() console.log('Anonymous ID:', anonId) ``` ## Get distinct ID ### `PostHog.getDistinctId` > **getDistinctId**(): `string` Gets the current user's distinct ID. You may find it helpful to get the current user's distinct ID. For example, to check whether you've already called identify for a user or not. This returns either the ID automatically generated by PostHog or the ID that has been passed by a call to identify(). #### Returns `string` The current user's distinct ID #### Example ```javascript // get current distinct ID const distinctId = posthog.getDistinctId() ``` ## Get feature flag ### `PostHog.getFeatureFlag` > **getFeatureFlag**(`key`, `options?`): `string` | `boolean` | `undefined` Gets the value of a feature flag for the current user. Returns `true` or `false` for an evaluated boolean flag and a string for a multivariate flag. Returns `undefined` when no evaluation is available, such as before flags load, after a failed first load, or for a key that isn't in the loaded flags. Globally inactive flags are omitted from remote responses, so they read as `undefined` rather than `false`. #### Parameters | Parameter | Type | Description | | --- | --- | --- | | `key` | `string` | The feature flag key | | `options?` | `PostHogFeatureFlagOptions` | Optional per-call settings | #### Returns `string` | `boolean` | `undefined` The current feature flag value, or undefined if no evaluation is available #### Example ```javascript // get feature flag value const value = posthog.getFeatureFlag('key-for-your-boolean-flag') ``` ### `useFeatureFlagVariantKey` > **useFeatureFlagVariantKey**(`flag`, `client?`): `string` | `boolean` | `undefined` A feature flag's value for the current user, updated when flags load: the variant key for a multivariate flag, or `true`/`false` for a boolean flag. `undefined` while flags are loading or when the flag doesn't exist. #### Parameters | Parameter | Type | Description | | --- | --- | --- | | `flag` | `string` | Key of the feature flag | | `client?` | `PostHog` | A PostHog client to use instead of the one from `PostHogProvider` | #### Returns `string` | `boolean` | `undefined` ## Get feature flag payload ### `useFeatureFlagPayload` > **useFeatureFlagPayload**(`flag`, `client?`): `JsonType` | `undefined` A feature flag's payload for the current user, updated when flags load. Reading it doesn't send a `$feature_flag_called` event. #### Parameters | Parameter | Type | Description | | --- | --- | --- | | `flag` | `string` | Key of the feature flag | | `client?` | `PostHog` | A PostHog client to use instead of the one from `PostHogProvider` | #### Returns `JsonType` | `undefined` ## Get feature flag result ### `PostHog.getFeatureFlagResult` > **getFeatureFlagResult**(`key`, `options?`): `FeatureFlagResult` | `undefined` Gets the evaluation result for a feature flag: whether it's enabled, its variant, and its payload. `enabled: false` is a conclusive off result; `undefined` means no evaluation is available for the key. #### Parameters | Parameter | Type | Description | | --- | --- | --- | | `key` | `string` | The feature flag key | | `options?` | `PostHogFeatureFlagOptions` | Optional per-call settings | #### Returns `FeatureFlagResult` | `undefined` The flag's evaluation result, or undefined if none is available #### Example ```javascript const result = posthog.getFeatureFlagResult('key-for-your-multivariate-flag') const payload = result?.payload ``` ### `useFeatureFlagResult` > **useFeatureFlagResult**(`flag`, `client?`): `FeatureFlagResult` | `undefined` #### Parameters | Parameter | Type | | --- | --- | | `flag` | `string` | | `client?` | `PostHog` | #### Returns `FeatureFlagResult` | `undefined` ## Get feature flags ### `PostHog.getAllFeatureFlags` > **getAllFeatureFlags**(): `FeatureFlagResult`\[\] | `undefined` Returns all currently cached feature flags as `FeatureFlagResult`s. This is a synchronous read of the flags from the last load (no network request) and does not send a `$feature_flag_called` event. Returns `undefined` while no flags are cached, such as before the first successful load or when no flags were bootstrapped, and a list, empty when no flags apply, once they are. #### Returns `FeatureFlagResult`\[\] | `undefined` ### `useActiveFeatureFlags` > **useActiveFeatureFlags**(`client?`): `string`\[\] The keys of the feature flags enabled for the current user, updated when flags load. #### Parameters | Parameter | Type | Description | | --- | --- | --- | | `client?` | `PostHog` | A PostHog client to use instead of the one from `PostHogProvider` | #### Returns `string`\[\] ## Get session ID ### `PostHog.getSessionId` > **getSessionId**(): `string` Returns the current session\_id. #### Returns `string` The stored session ID for the current session. This may be an empty string if the client is not yet fully initialized. #### Remarks This should only be used for informative purposes. Any actual internal use case for the session\_id should be handled by the sessionManager. ## Group ### `PostHog.group` > **group**(`groupType`, `groupKey`, `properties?`, `options?`): `void` Associates the current user with a group. Group analytics allows you to associate the events for that person's session with a group (e.g. teams, organizations, etc.). This is a paid feature and is not available on the open-source or free cloud plan. #### Parameters | Parameter | Type | Description | | --- | --- | --- | | `groupType` | `string` | The type of group (e.g. 'company', 'team') | | `groupKey` | `string` | The unique identifier for the group | | `properties?` | `PostHogEventProperties` | Optional properties to set for the group | | `options?` | `PostHogCaptureOptions` | Optional capture options for the `$groupidentify` event | #### Returns `void` #### Examples ```javascript // associate with a group posthog.group('company', 'company_id_in_your_db') ``` ```javascript // associate with a group and update properties posthog.group('company', 'company_id_in_your_db', { name: 'Awesome Inc.', employees: 11, }) ``` ### `PostHog.groups` > **groups**(`groups`): `void` \*\* GROUPS \* #### Parameters | Parameter | Type | | --- | --- | | `groups` | `PostHogGroupProperties` | #### Returns `void` ## Group identify ### `PostHog.groupIdentify` > **groupIdentify**(`groupType`, `groupKey`, `groupProperties?`, `options?`): `void` Sends a `$groupidentify` event that sets properties on a group, without associating the current user's events with it. Use `group()` to do both. #### Parameters | Parameter | Type | Description | | --- | --- | --- | | `groupType` | `string` | The type of group (e.g. 'company', 'team') | | `groupKey` | `string` \| `number` | The unique identifier for the group | | `groupProperties?` | `PostHogEventProperties` | Optional properties to set for the group | | `options?` | `PostHogCaptureOptions` | Optional capture options for the `$groupidentify` event | #### Returns `void` ## Is feature enabled ### `PostHog.isFeatureEnabled` > **isFeatureEnabled**(`key`, `options?`): `boolean` Checks if a feature flag is enabled for the current user. Returns `true` when the flag evaluates on and `false` when it evaluates off. When no evaluation is available, such as before flags load, after a failed first load, or for a key that isn't in the loaded flags, it returns `defaultValue`, or `false` when you don't pass one. Use `getFeatureFlagResult()` to tell an unavailable key from a conclusive off result. #### Parameters | Parameter | Type | Description | | --- | --- | --- | | `key` | `string` | The feature flag key | | `options?` | `PostHogIsFeatureEnabledOptions` | Optional per-call settings | #### Returns `boolean` True if the flag evaluates on, false if it evaluates off, or `defaultValue` (`false` unless given) if no evaluation is available #### Examples ```javascript // check if feature flag is enabled const isEnabled = posthog.isFeatureEnabled('key-for-your-boolean-flag') ``` ```javascript // fall back to true while flags are not loaded const isEnabled = posthog.isFeatureEnabled('key-for-your-boolean-flag', { defaultValue: true }) ``` ### `useFeatureFlagEnabled` > **useFeatureFlagEnabled**(`flag`): `boolean` | `undefined` Whether a feature flag is enabled for the current user, updated when flags load. Returns `false` when the flag evaluates off, and `undefined` while flags are loading or when the flag doesn't exist, so a conclusive "off" can be told apart from "no value yet". ##### Parameters | Parameter | Type | Description | | --- | --- | --- | | `flag` | `string` | Key of the feature flag | ##### Returns `boolean` | `undefined` #### Call Signature > **useFeatureFlagEnabled**(`flag`, `defaultValue`, `client?`): `boolean` Whether a feature flag is enabled for the current user, updated when flags load. Returns `false` when the flag evaluates off, and `undefined` while flags are loading or when the flag doesn't exist, so a conclusive "off" can be told apart from "no value yet". ##### Parameters | Parameter | Type | Description | | --- | --- | --- | | `flag` | `string` | Key of the feature flag | | `defaultValue` | `boolean` | Returned instead of `undefined` while the value is unknown | | `client?` | `PostHog` | A PostHog client to use instead of the one from `PostHogProvider` | ##### Returns `boolean` #### Call Signature > **useFeatureFlagEnabled**(`flag`, `defaultValue?`, `client?`): `boolean` | `undefined` Whether a feature flag is enabled for the current user, updated when flags load. Returns `false` when the flag evaluates off, and `undefined` while flags are loading or when the flag doesn't exist, so a conclusive "off" can be told apart from "no value yet". ##### Parameters | Parameter | Type | Description | | --- | --- | --- | | `flag` | `string` | Key of the feature flag | | `defaultValue?` | `boolean` | Returned instead of `undefined` while the value is unknown | | `client?` | `PostHog` | A PostHog client to use instead of the one from `PostHogProvider` | ##### Returns `boolean` | `undefined` ## Is opt out ### `PostHog.isDisabled` > **get** **isDisabled**(): `boolean` ##### Returns `boolean` ### `PostHog.optedOut` > **get** **optedOut**(): `boolean` ##### Returns `boolean` ## Is session replay active ### `PostHog.isSessionReplayActive` > **isSessionReplayActive**(): `Promise`<`boolean`\> Returns whether session replay is currently active. Note: This is only available on iOS and Android. On web/macOS, this always returns false. #### Returns `Promise`<`boolean`\> Whether session replay is currently active #### Example ```javascript const isActive = await posthog.isSessionReplayActive() ``` ## On feature flags ### `PostHog.onFeatureFlags` > **onFeatureFlags**(`callback`): () => `void` Calls `callback` whenever feature flags load, including when a load fails. The callback receives the enabled flags, their values, and whether the latest load failed. After a failed load the values are the last known ones, which can be empty. If flags have already loaded when you register, it's also called with the current values shortly afterwards. #### Parameters | Parameter | Type | Description | | --- | --- | --- | | `callback` | (`loaded`) => `void` | Called with the enabled flags, their values, and whether the latest load failed | #### Returns A function that stops further calls () => `void` #### Example ```javascript const unsubscribe = posthog.onFeatureFlags(({ flags, variants, errorsLoading }) => { if (errorsLoading) { // flags and variants hold the last known values } if (variants['new-checkout'] === 'test') { // show the test variant } }) ``` ## Opt in ### `PostHog.optIn` > **optIn**(): `Promise`<`void`\> Opts the user in to data capture. By default, PostHog has tracking enabled unless it is forcefully disabled by default using the option { defaultOptIn: false }. Once this has been called it is persisted and will be respected until optOut is called again or the reset function is called. When opting in after an opt-out, session replay restarts in a new session if the app wanted it on at opt-out: `enableSessionReplay` is on, or the app called `startSessionRecording()`, and the app has not called `stopSessionRecording()` since. This holds even if replay was not recording at opt-out, for example while it waited for the linked flag or an event trigger. The linked flag, sampling and event triggers apply to the restart as usual. The promise resolves once session replay has been re-evaluated. A `startSessionRecording()` or `stopSessionRecording()` call made while opted out does not change this; to keep replay stopped, call `stopSessionRecording()` before `optOut()` or after `optIn()`. #### Returns `Promise`<`void`\> #### Example ```javascript // opt in to tracking posthog.optIn() ``` ### `PostHog.optOut` > **optOut**(): `Promise`<`void`\> Opts the user out of data capture. You can completely opt-out users from data capture. Once this has been called it is persisted and will be respected until optIn is called again or the reset function is called. The promise resolves once session replay has stopped. #### Returns `Promise`<`void`\> #### Example ```javascript // opt out of tracking posthog.optOut() ``` ## Register ### `PostHog.register` > **register**(`properties`): `Promise`<`void`\> Registers super properties that are sent with every event. Super properties are properties associated with events that are set once and then sent with every capture call. They persist across sessions and are stored locally. A registered `$process_person_profile` is left off `$identify`, `$create_alias`, `$merge_dangerously`, `$groupidentify`, `$set` and `$set_once` events. #### Parameters | Parameter | Type | Description | | --- | --- | --- | | `properties` | `PostHogEventProperties` | An associative array of properties to store about the user | #### Returns `Promise`<`void`\> #### Example ```javascript // register super properties posthog.register({ 'icecream pref': 'vanilla', team_id: 22, }) ``` ### `PostHog.registerForSession` > **registerForSession**(`properties`): `void` #### Parameters | Parameter | Type | | --- | --- | | `properties` | `PostHogEventProperties` | #### Returns `void` ### `PostHog.setAppLanguage` > **setAppLanguage**(`language`): `void` Sets the `$app_language` property: the language your app displays, sent with every event. Default: not set, so events carry no `$app_language`. React Native apps usually translate in JavaScript (for example with i18next), which the SDK can't see, so call this at startup and whenever the language changes. Compare `$locale`, which is the device language. The value is kept in memory only and survives `reset()`. A `$app_language` you `register()` wins over it. With `@posthog/react-native-plugin` 3.0 or later, events the native SDK captures itself, such as crashes and push opens, carry it too. Call it right after creating the client so a push open that launched the app carries it as well. #### Parameters | Parameter | Type | Description | | --- | --- | --- | | `language` | `string` \| `null` | A BCP 47 language tag, such as `de` or `pt-BR`. `_` is replaced with `-`. Pass `null` or an empty string to stop sending it. | #### Returns `void` #### Example ```javascript // With i18next or react-i18next posthog.setAppLanguage(i18n.resolvedLanguage) i18n.on('languageChanged', (language) => posthog.setAppLanguage(language)) // Your own language setting posthog.setAppLanguage(settings.language) // at startup posthog.setAppLanguage('de') // when the user picks German ``` ## Reload feature flags ### `PostHog.reloadFeatureFlags` > **reloadFeatureFlags**(): `void` Reloads feature flags from the server. PostHog loads feature flags when instantiated and refreshes whenever methods are called that affect the flag. If you want to manually trigger a refresh, you can call this method. #### Returns `void` #### Remarks When the `disableRemoteFeatureFlags` option is set, this method is a no-op; supply flag values via `updateFlags()` instead. #### Example ```javascript // reload feature flags posthog.reloadFeatureFlags() ``` ### `PostHog.reloadFeatureFlagsAsync` > **reloadFeatureFlagsAsync**(): `Promise`<`PostHogFeatureFlagsLoaded`\> Reloads feature flags from the server asynchronously. PostHog loads feature flags when instantiated and refreshes whenever methods are called that affect the flag. If you want to manually trigger a refresh and get the result, you can call this method. #### Returns `Promise`<`PostHogFeatureFlagsLoaded`\> Promise that resolves with the enabled flags, their values, and whether the reload failed, as `onFeatureFlags` callbacks receive them. After a failed reload the values are the last known ones. #### Example ```javascript const { flags, variants, errorsLoading } = await posthog.reloadFeatureFlagsAsync() ``` #### Remarks When the `disableRemoteFeatureFlags` option is set, no request is made and the promise resolves with the currently stored flags (from `bootstrap` or `updateFlags()`). ## Reset ### `PostHog.reset` > **reset**(`propertiesToKeep?`): `void` Resets the user's ID and anonymous ID after logout. To reset the user's ID and anonymous ID, call reset. Usually you would do this right after the user logs out. This also clears all stored super properties and more. By default (when `propertiesToKeep` is not provided), the app lifecycle properties (`InstalledAppBuild` and `InstalledAppVersion`) are automatically preserved to prevent duplicate "Application Installed" events on the next app launch. If you pass `propertiesToKeep` explicitly, only the properties you specify will be preserved. To keep the default app lifecycle behavior, include `PostHogPersistedProperty.InstalledAppBuild` and `PostHogPersistedProperty.InstalledAppVersion` in your array. Note: The event queue (`PostHogPersistedProperty.Queue`) and logs queue (`PostHogPersistedProperty.LogsQueue`) are always preserved regardless of what is passed in `propertiesToKeep`, to ensure in-flight data is not lost. A start that trigger groups hold, one still waiting for the first remote config, and a recording the app started that the groups paused are kept and re-gated for the new session. The project-level remote config (`PostHogPersistedProperty.RemoteConfig`, `PostHogPersistedProperty.SessionReplay`, `PostHogPersistedProperty.Surveys`) is also always preserved — it is not user data — so session replay and surveys keep working after an identity change. The user-specific survey state (`SurveysSeen`, `SurveyLastSeenDate`) is still cleared. #### Parameters | Parameter | Type | Description | | --- | --- | --- | | `propertiesToKeep?` | `PostHogPersistedProperty`\[\] | Optional array of persisted properties to preserve during reset. When not provided, app lifecycle and device bucketing properties are automatically preserved. When provided, only the specified properties are preserved. The event queue and logs queue are always preserved regardless. | #### Returns `void` #### Examples ```javascript // reset after logout (preserves app lifecycle properties by default) posthog.reset() ``` ```javascript // reset but keep app lifecycle properties posthog.reset([ PostHogPersistedProperty.InstalledAppBuild, PostHogPersistedProperty.InstalledAppVersion, ]) ``` ## Reset group properties for flags ### `PostHog.resetGroupPropertiesForFlags` > **resetGroupPropertiesForFlags**(`reloadFeatureFlags?`): `void` Resets group properties for feature flag evaluation. ##### Parameters | Parameter | Type | Description | | --- | --- | --- | | `reloadFeatureFlags?` | `boolean` | Whether to reload feature flags after setting the properties. Defaults to true. | ##### Returns `void` ##### Example ```javascript // reset group properties for flags posthog.resetGroupPropertiesForFlags() ``` #### Call Signature > **resetGroupPropertiesForFlags**(`groupType`, `reloadFeatureFlags?`): `void` Resets the group properties of one group type for feature flag evaluation, keeping other group types. ##### Parameters | Parameter | Type | Description | | --- | --- | --- | | `groupType` | `string` | The group type whose properties to reset | | `reloadFeatureFlags?` | `boolean` | Whether to reload feature flags after resetting the properties. Defaults to true. | ##### Returns `void` ##### Example ```javascript // reset the company group's properties for flags posthog.resetGroupPropertiesForFlags('company') ``` ## Reset person properties for flags ### `PostHog.resetPersonPropertiesForFlags` > **resetPersonPropertiesForFlags**(`reloadFeatureFlags?`): `void` Resets person properties for feature flag evaluation. #### Parameters | Parameter | Type | Default value | Description | | --- | --- | --- | --- | | `reloadFeatureFlags?` | `boolean` | `true` | Whether to reload feature flags after setting the properties. Defaults to true. | #### Returns `void` #### Example ```javascript // reset person properties for flags posthog.resetPersonPropertiesForFlags() ``` ## Screen ### `PostHog.screen` > **screen**(`name`, `properties?`, `options?`): `Promise`<`void`\> Captures a screen view event. #### Parameters | Parameter | Type | Description | | --- | --- | --- | | `name` | `string` | The name of the screen | | `properties?` | `PostHogEventProperties` | Optional properties to include with the screen event | | `options?` | `PostHogCaptureOptions` | Optional capture options | #### Returns `Promise`<`void`\> #### Remarks This function requires a name. You may also pass in an optional properties object. Once initialized, the screen name is registered immediately for subsequent events, including exceptions. During initialization, screen registration and event capture retain their call order. Exceptions use the last recorded screen, not a destination that has not yet been tracked. #### Examples ```javascript // Basic screen capture posthog.screen('dashboard') ``` ```javascript // Screen capture with properties posthog.screen('dashboard', { background: 'blue', hero: 'superhog', }) ``` ### `useNavigationTracker` > `const` **useNavigationTracker**: (`options?`, `client?`) => `void` #### Parameters | Parameter | Type | | --- | --- | | `options?` | `PostHogAutocaptureNavigationTrackerOptions` | | `client?` | `PostHog` | #### Returns `void` ## Set group properties for flags ### `PostHog.setGroupPropertiesForFlags` > **setGroupPropertiesForFlags**(`properties`, `reloadFeatureFlags?`): `void` Sets group properties for feature flag evaluation. These properties are automatically attached to the current group (set via posthog.group()). When you change the group, these properties are reset. #### Parameters | Parameter | Type | Default value | Description | | --- | --- | --- | --- | | `properties` | `Record`<`string`, `Record`<`string`, `JsonType`\>> | `undefined` | The group properties to set for flag evaluation | | `reloadFeatureFlags?` | `boolean` | `true` | Whether to reload feature flags after setting the properties. Defaults to true. | #### Returns `void` #### Example ```javascript // set group properties for flags posthog.setGroupPropertiesForFlags({'company': {'property1': 'value', property2: 'value2'}}) ``` ## Set person properties ### `PostHog.setPersonProperties` > **setPersonProperties**(`userPropertiesToSet?`, `userPropertiesToSetOnce?`, `reloadFeatureFlags?`, `options?`): `void` Sets properties on the person profile associated with the current `distinct_id`. Learn more about [identifying users](https://posthog.com/docs/product-analytics/identify) #### Parameters | Parameter | Type | Default value | Description | | --- | --- | --- | --- | | `userPropertiesToSet?` | {\[`key`: `string`\]: `JsonType`; } | `undefined` | Optional: An object of properties to store about the user. These properties will overwrite any existing values for the same keys. | | `userPropertiesToSetOnce?` | {\[`key`: `string`\]: `JsonType`; } | `undefined` | Optional: An object of properties to store about the user. If a property is previously set, this does not override that value. | | `reloadFeatureFlags?` | `boolean` | `true` | Whether to reload feature flags after setting the properties. Defaults to true. | | `options?` | `PostHogCaptureOptions` | `undefined` | Optional capture options for the `$set` event | #### Returns `void` #### Remarks Updates user properties that are stored with the person profile in PostHog. If `personProfiles` is set to `identified_only` and no profile exists, this will create one. #### Examples ```javascript // set user properties posthog.setPersonProperties({ email: 'user@example.com', plan: 'premium' }) ``` ```javascript // set properties with $set_once posthog.setPersonProperties( { name: 'Max Hedgehog' }, // $set properties { initial_url: '/blog' } // $set_once properties ) ``` ```javascript // set properties without reloading feature flags posthog.setPersonProperties({ plan: 'premium' }, undefined, false) ``` ### `PostHog.unsetPersonProperties` > **unsetPersonProperties**(`propertyNames`, `reloadFeatureFlags?`, `options?`): `void` Removes properties from the person profile associated with the current `distinct_id`. Learn more about [identifying users](https://posthog.com/docs/product-analytics/identify) #### Parameters | Parameter | Type | Default value | Description | | --- | --- | --- | --- | | `propertyNames` | `string` \| `string`\[\] | `undefined` | The name (or names) of the person properties to remove. | | `reloadFeatureFlags?` | `boolean` | `true` | Whether to reload feature flags after removing the properties. Defaults to true. | | `options?` | `PostHogCaptureOptions` | `undefined` | Optional capture options for the `$set` event | #### Returns `void` ## Set person properties for flags ### `PostHog.setPersonPropertiesForFlags` > **setPersonPropertiesForFlags**(`properties`, `reloadFeatureFlags?`): `void` Sets person properties for feature flag evaluation. 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 this call. These are set for the entire session. Successive calls are additive: all properties you set are combined together and sent for flag evaluation. #### Parameters | Parameter | Type | Default value | Description | | --- | --- | --- | --- | | `properties` | `Record`<`string`, `JsonType`\> | `undefined` | The person properties to set for flag evaluation | | `reloadFeatureFlags?` | `boolean` | `true` | Whether to reload feature flags after setting the properties. Defaults to true. | #### Returns `void` #### Example ```javascript // set person properties for flags posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'}) ``` ## Shutdown ### `PostHog.shutdown` > **shutdown**(`shutdownTimeoutMs?`): `Promise`<`void`\> Shuts down the PostHog instance and ensures all events are sent. Call shutdown() once before the process exits to ensure that all events have been sent and all promises have resolved. Do not use this function if you intend to keep using this PostHog instance after calling it. Use flush() for per-request cleanup instead. #### Parameters | Parameter | Type | Description | | --- | --- | --- | | `shutdownTimeoutMs?` | `number` | Maximum time to wait for shutdown in milliseconds | #### Returns `Promise`<`void`\> A promise that resolves when shutdown is complete #### Example ```javascript // shutdown before process exit process.on('SIGINT', async () => { await posthog.shutdown() process.exit(0) }) ``` ## Start session recording ### `PostHog.startSessionRecording` > **startSessionRecording**(`resumeCurrent?`): `Promise`<`void`\> Starts session recording. This method will have no effect if PostHog is not enabled, or if session replay is disabled in your project settings. A refused manual start is retried with successive delays of 1, 2, 4, 8, and 16 seconds, and on subsequent feature flags loads while pending. This promise resolves after the initial attempt, without waiting for retries or guaranteeing recording is active. A newer start supersedes an unfinished request. Stop, opt-out, and shutdown cancel pending starts, including one trigger groups hold. `reset()` cancels any other pending start, but keeps one trigger groups hold, one still waiting for the first remote config, and a recording the app started that the groups paused: each is re-gated for the new session. A start is only waiting for the config once this call has run, so await it before a `reset()` in the same tick. Use `isSessionReplayActive()` to check the current recording state. Note: This is only available on iOS and Android. On web/macOS, this is a no-op. Requires `@posthog/react-native-plugin`. #### Parameters | Parameter | Type | Default value | Description | | --- | --- | --- | --- | | `resumeCurrent?` | `boolean` | `true` | Whether to resume recording of current session (true) or start a new session (false). Defaults to true. | #### Returns `Promise`<`void`\> #### Examples ```javascript // Resume the current session recording await posthog.startSessionRecording() ``` ```javascript // Start a new session recording await posthog.startSessionRecording(false) ``` ## Stop session recording ### `PostHog.stopSessionRecording` > **stopSessionRecording**(): `Promise`<`void`\> Stops the current session recording if one is in progress. Note: This is only available on iOS and Android. On web/macOS, this is a no-op. Requires `@posthog/react-native-plugin`. It also cancels a start that trigger groups hold. #### Returns `Promise`<`void`\> #### Example ```javascript await posthog.stopSessionRecording() ``` ## Unregister ### `PostHog.unregister` > **unregister**(`property`): `Promise`<`void`\> Removes a super property so it won't be sent with future events. Super Properties are persisted across sessions so you have to explicitly remove them if they are no longer relevant. #### Parameters | Parameter | Type | Description | | --- | --- | --- | | `property` | `string` | The name of the super property to remove | #### Returns `Promise`<`void`\> #### Example ```javascript // remove a super property posthog.unregister('icecream pref') ``` ### `PostHog.unregisterForSession` > **unregisterForSession**(`property`): `void` #### Parameters | Parameter | Type | | --- | --- | | `property` | `string` | #### Returns `void` ## Autocapture ### `PostHog.autocapture` > **autocapture**(`eventType`, `elements`, `properties?`, `options?`): `void` #### Parameters | Parameter | Type | | --- | --- | | `eventType` | `string` | | `elements` | `PostHogAutocaptureElement`\[\] | | `properties?` | `PostHogEventProperties` | | `options?` | `PostHogCaptureOptions` | #### Returns `void` ## Remote config ### `PostHog.reloadRemoteConfigAsync` > **reloadRemoteConfigAsync**(): `Promise`<`PostHogRemoteConfig` | `undefined`\> #### Returns `Promise`<`PostHogRemoteConfig` | `undefined`\> ## Session replay privacy ### `PostHogMaskView` > **PostHogMaskView**(`options`): `Element` PostHogMaskView is a wrapper component that hides its children from PostHog session recordings without compromising accessibility. It works by: - Setting `accessibilityLabel` to `"ph-no-capture"` to hide the content from session recordings - Setting `importantForAccessibility` to `"no"` to prevent the wrapper View from hiding accessible content on Android (since `accessibilityLabel` would otherwise interfere) - Setting `collapsable={false}` so React Native keeps this wrapper in the native view hierarchy (otherwise layout-only view flattening can remove it and masking is not detected on iOS/Android) #### Parameters | Parameter | Type | | --- | --- | | `options` | `PostHogMaskViewProps` | #### Returns `Element` #### Example ```jsx import { PostHogMaskView } from 'posthog-react-native' function SensitiveForm() { return ( ) } ``` ## Surveys ### `PostHog.getSurveys` > **getSurveys**(): `Promise`<`Survey`\[\]> #### Returns `Promise`<`Survey`\[\]> ### `PostHogSurveyProvider` > **PostHogSurveyProvider**(`props`): `Element` Presents the surveys that match the current user. Surveys in React Native don't support URL or CSS selector targeting. Surveys that rely on these conditions don't appear. #### Parameters | Parameter | Type | | --- | --- | | `props` | `PostHogSurveyProviderProps` | #### Returns `Element` ### `Questions` > **Questions**(`options`): `Element` #### Parameters | Parameter | Type | | --- | --- | | `options` | { `appearance`: `SurveyAppearanceTheme`; `client?`: `PostHog`; `initialProgress?`: `SurveyProgress`; `onProgressChange?`: (`progress`, `completed`) => `boolean`; `onResponsesChange?`: (`responses`) => `void`; `onSubmit`: () => `void`; `styleOverrides?`: `StyleProp`<`ViewStyle`\>; `survey`: `Survey`; `surveyLanguage?`: `string` \| `null`; } | | `options.appearance` | `SurveyAppearanceTheme` | | `options.client?` | `PostHog` | | `options.initialProgress?` | `SurveyProgress` | | `options.onProgressChange?` | (`progress`, `completed`) => `boolean` | | `options.onResponsesChange?` | (`responses`) => `void` | | `options.onSubmit` | () => `void` | | `options.styleOverrides?` | `StyleProp`<`ViewStyle`\> | | `options.survey` | `Survey` | | `options.surveyLanguage?` | `string` \| `null` | #### Returns `Element` ### `SurveyModal` > **SurveyModal**(`props`): `Element` | `null` #### Parameters | Parameter | Type | | --- | --- | | `props` | `SurveyModalProps` | #### Returns `Element` | `null` ## SDK utils ### `PostHog.captureFeatureInteraction` > **captureFeatureInteraction**(`flag`, `flagVariant?`): `void` Captures a `$feature_interaction` event when the user interacts with the feature behind a feature flag. The event carries `feature_flag` and, for multivariate flags, `feature_flag_variant`, and sets the person property `$feature_interaction/` to the variant. Without `flagVariant`, the SDK reads the flag's current value without capturing `$feature_flag_called`, and skips the event when the flag has no value. #### Parameters | Parameter | Type | Description | | --- | --- | --- | | `flag` | `string` | The feature flag key | | `flagVariant?` | `string` | The variant the user interacted with. Defaults to the flag's current value. | #### Returns `void` #### Example ```javascript