PostHog React Native SDK
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 lists for Expo or the React Native CLI.
Then wrap your app in PostHogProvider with your project token and host from your project settings, and call capture on the client that usePostHog returns.
Install
Initialize
Wrap your app in PostHogProvider.
Capture an event
Identify a user
Setup
new PostHog(...)
new PostHog(
projectToken,options?):PostHog
Creates a new PostHog instance for React Native. You can find all configuration options in the React Native SDK docs.
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 |
options? | PostHogOptions | PostHog configuration options |
Returns
PostHog
Example
PostHogProvider
PostHogProvider(
props):Element|null
PostHogProvider is a React component that provides PostHog functionality to your React Native app. You can find all configuration options in the React Native SDK docs.
Autocapturing navigation requires further configuration. See the React Native SDK navigation docs 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
usePostHog
usePostHog():
PostHog
Returns
PostHog
Capture
PostHog.capture
capture(
event,properties?,options?):void
Parameters
| Parameter | Type |
|---|---|
event | string |
properties? | PostHogEventProperties |
options? | PostHogCaptureOptions |
Returns
void
Identify
PostHog.identify
identify(
distinctId?,properties?,options?):void
Associates events with a specific user. Learn more about identifying users
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
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
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
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
See
flush
Alias
PostHog.alias
alias(
alias):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 |
Returns
void
Example
Capture AI
PostHog.captureTraceFeedback
captureTraceFeedback(
traceId,userFeedback):void
Capture written user feedback for a LLM trace. 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. 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?):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 | - |
Returns
void
Examples
PostHogErrorBoundary
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<typeof MyContext> // For TS 3.7 and above: declare context: React.ContextType<typeof MyContext> See 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<MyContext>(0) class Foo extends React.Component { static contextType = Ctx context!: React.ContextType<typeof Ctx> render () { return <>My context's value: {this.context}</>; } } See 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()
staticgetDerivedStateFromError(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
Debug
PostHog.isDebug
get isDebug():
boolean
Returns
boolean
PostHog.debug
debug(
enabled?):void
Enables or disables debug mode for detailed logging.
Parameters
| Parameter | Type |
|---|---|
enabled? | boolean |
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
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
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
Example
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
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
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
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 before flags load or when loading fails. For backwards compatibility, a
missing key can resolve to false after a non-empty response is stored; use
getFeatureFlagResult() to distinguish an unavailable key from a conclusive off result.
Globally inactive flags are omitted from remote responses, so they follow this missing-key behavior rather than carrying an explicit off evaluation.
Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | The feature flag key |
options? | FeatureFlagResultOptions | Optional per-call settings |
Returns
string | boolean | undefined
The current feature flag value, or undefined if flags are unavailable
Example
useFeatureFlag
useFeatureFlag(
flag,client?):FeatureFlagValue|undefined
Parameters
| Parameter | Type |
|---|---|
flag | string |
client? | PostHog |
Returns
FeatureFlagValue | undefined
Get feature flag payload
PostHog.getFeatureFlagPayload
getFeatureFlagPayload(
key):JsonType|undefined
Gets the payload of a feature flag for the current user.
Returns JsonType or undefined if not loaded yet or if there was a problem loading.
Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | The feature flag key |
Returns
JsonType | undefined
The feature flag payload or undefined if not loaded
Deprecated
Use getFeatureFlagResult() instead, which returns the flag value and payload from a single evaluation.
Example
useFeatureFlagWithPayload
useFeatureFlagWithPayload(
flag,client?):FeatureFlagWithPayload
Returns a flag's value and payload, and updates when flags reload.
Parameters
| Parameter | Type |
|---|---|
flag | string |
client? | PostHog |
Returns
FeatureFlagWithPayload
Deprecated
Use useFeatureFlagResult() instead, which returns the flag value and payload from a single evaluation.
Get feature flag result
PostHog.getFeatureFlagResult
getFeatureFlagResult(
key,options?):FeatureFlagResult|undefined
Returns the current evaluation result for a feature flag. enabled: false is a conclusive
off result; undefined means no evaluation is available for the key.
Parameters
| Parameter | Type |
|---|---|
key | string |
options? | FeatureFlagResultOptions |
Returns
FeatureFlagResult | undefined
useFeatureFlagResult
useFeatureFlagResult(
flag,client?):FeatureFlagResult|undefined
Parameters
| Parameter | Type |
|---|---|
flag | string |
client? | PostHog |
Returns
FeatureFlagResult | undefined
Get feature flags
PostHog.getAllFeatureFlags
getAllFeatureFlags():
FeatureFlagResult[]
Returns all currently cached feature flags as FeatureFlagResults. 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
FeatureFlagResult[]
PostHog.getFeatureFlags
getFeatureFlags(): {[
key:string]:FeatureFlagValue; } |undefined
Returns the value of every loaded flag, keyed by flag key.
Returns
{[key: string]: FeatureFlagValue; } | undefined
Deprecated
Use getAllFeatureFlags() instead, which returns each flag's value and payload together.
useFeatureFlags
useFeatureFlags(
client?): {[key:string]:FeatureFlagValue; } |undefined
Parameters
| Parameter | Type |
|---|---|
client? | PostHog |
Returns
{[key: string]: FeatureFlagValue; } | undefined
Get feature flags and payloads
PostHog.getFeatureFlagsAndPayloads
getFeatureFlagsAndPayloads():
object
Returns the values and payloads of every loaded flag, as two maps keyed by flag key.
Returns
object
| Name | Type |
|---|---|
flags | {[key: string]: FeatureFlagValue; } | undefined |
payloads | {[key: string]: JsonType; } | undefined |
Deprecated
Use getAllFeatureFlags() instead, which returns each flag's value and payload together.
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?):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 |
Returns
void
Examples
PostHog.groups
groups(
groups):void
** GROUPS *
Parameters
| Parameter | Type |
|---|---|
groups | PostHogGroupProperties |
Returns
void
Group identify
PostHog.groupIdentify
groupIdentify(
groupType,groupKey,groupProperties?,options?):void
Parameters
| Parameter | Type |
|---|---|
groupType | string |
groupKey | string | number |
groupProperties? | PostHogEventProperties |
options? | PostHogCaptureOptions |
Returns
void
Is feature enabled
PostHog.isFeatureEnabled
isFeatureEnabled(
key,options):boolean
Checks if a feature flag is enabled for the current user.
A false return value means the SDK resolved the current value as off. If no evaluation is
available, this method returns defaultValue when provided. Without a default, it returns
undefined before flags load; for backwards compatibility, a missing key can resolve to
false after a non-empty response is stored.
Globally inactive flags are omitted from remote responses, so they follow this missing-key behavior rather than carrying an explicit off evaluation.
Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | The feature flag key |
options | FeatureFlagResultOptions & object & object | Optional per-call settings |
Returns
boolean
True if the flag evaluates on, false if it evaluates off, or the missing-value fallback described above
Examples
Call Signature
isFeatureEnabled(
key,options?):boolean|undefined
Checks if a feature flag is enabled for the current user.
A false return value means the SDK resolved the current value as off. If no evaluation is
available, this method returns defaultValue when provided. Without a default, it returns
undefined before flags load; for backwards compatibility, a missing key can resolve to
false after a non-empty response is stored.
Globally inactive flags are omitted from remote responses, so they follow this missing-key behavior rather than carrying an explicit off evaluation.
Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | The feature flag key |
options? | IsFeatureEnabledOptions | Optional per-call settings |
Returns
boolean | undefined
True if the flag evaluates on, false if it evaluates off, or the missing-value fallback described above
Examples
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
On feature flags
PostHog.onFeatureFlags
onFeatureFlags(
cb): () =>void
Parameters
| Parameter | Type |
|---|---|
cb | (flags) => void |
Returns
() => void
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
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
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.
Parameters
| Parameter | Type | Description |
|---|---|---|
properties | PostHogEventProperties | An associative array of properties to store about the user |
Returns
Promise<void>
Example
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
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
PostHog.reloadFeatureFlagsAsync
reloadFeatureFlagsAsync():
Promise<Record<string,string|boolean> |undefined>
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<Record<string, string | boolean> | undefined>
Promise that resolves with the refreshed flags
Example
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.
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
Reset group properties for flags
PostHog.resetGroupPropertiesForFlags
resetGroupPropertiesForFlags(
reloadFeatureFlags?):void
Resets group 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
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
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
useNavigationTracker
constuseNavigationTracker: (options?,navigationRef?,client?) =>void
Parameters
| Parameter | Type |
|---|---|
options? | PostHogAutocaptureNavigationTrackerOptions |
navigationRef? | PostHogNavigationRef |
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
Set person properties
PostHog.setPersonProperties
setPersonProperties(
userPropertiesToSet?,userPropertiesToSetOnce?,reloadFeatureFlags?):void
Sets properties on the person profile associated with the current distinct_id.
Learn more about identifying users
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. |
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
PostHog.unsetPersonProperties
unsetPersonProperties(
propertyNames,reloadFeatureFlags?):void
Removes properties from the person profile associated with the current distinct_id.
Learn more about identifying users
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. |
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
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
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, reset, opt-out, and shutdown
cancel pending starts. 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-session-replay version 1.3.0 or higher.
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
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-session-replay version 1.3.0 or higher.
Returns
Promise<void>
Example
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
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
accessibilityLabelto"ph-no-capture"to hide the content from session recordings - Setting
importantForAccessibilityto"no"to prevent the wrapper View from hiding accessible content on Android (sinceaccessibilityLabelwould 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
Surveys
PostHog.getSurveys
getSurveys():
Promise<Survey[]>
Returns
Promise<Survey[]>
PostHogSurveyProvider
PostHogSurveyProvider(
props):Element
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.capturePushNotificationOpened
capturePushNotificationOpened(
options):Promise<void>
Captures $push_notification_opened when a user opens a push notification.
Requires @posthog/react-native-plugin.
Only for taps PostHogOptions.capturePushNotificationOpened cannot see itself —
local notifications, plus Android taps while the app is running if
@posthog/react-native-plugin is older than 2.6.0. A notification PostHog sent is still
counted once when both paths report it (same posthog.invocation_id and action within
five minutes); one from another provider is counted twice.
Keys of payload's posthog entry become $notification_<key> properties. Leave
action unset for a plain tap; subtitle is iOS only. The native SDK builds and
sends the event, so JS before_send never sees it — redact anything sensitive first.
Not supported on web.
Parameters
| Parameter | Type |
|---|---|
options | { action?: string; body?: string; payload?: {[key: string]: JsonType; }; subtitle?: string; title?: string; } |
options.action? | string |
options.body? | string |
options.payload? | {[key: string]: JsonType; } |
options.subtitle? | string |
options.title? | string |
Returns
Promise<void>
PostHog.getDeviceId
getDeviceId():
string
Returns the stable device identifier used for device-level feature flag bucketing. This ID persists across identify() and reset() calls, only changing on a fresh app install, manual cache clearing, or OS-initiated storage cleanup.
Returns
string
The device ID, or an empty string if not yet initialized
PostHog.getFeatureFlagDetails
getFeatureFlagDetails():
PostHogFeatureFlagDetails|undefined
Returns
PostHogFeatureFlagDetails | undefined
PostHog.getSurveyDisplayLanguageOverride
getSurveyDisplayLanguageOverride():
string|null
Returns
string | null
PostHog.on
on(
event,cb): () =>void
Parameters
| Parameter | Type |
|---|---|
event | string |
cb | (...args) => void |
Returns
() => void
PostHog.registerPushNotificationToken
registerPushNotificationToken(
deviceToken,options?):Promise<void>
Registers this device's push token so PostHog Workflows can target it.
Requires @posthog/react-native-plugin.
Registration happens at startup on its own when PostHogOptions.capturePushNotificationSubscriptions is on, so call this for token refreshes, which that startup fetch cannot see — on Android only, since a refresh listener yields an FCM token and iOS defaults to APNs. Safe to call before the native SDK is ready; the call queues rather than being dropped.
appId says which provider delivers: the Firebase project_id for an FCM token, the
APNs bundle id for an APNs token. Unset, iOS uses the bundle id and Android the
default FirebaseApp's project id, so pass it if you don't use Firebase or use a
non-default project. Registration fails server-side if your PostHog project has no
matching integration for appId.
To use FCM on iOS too, pass the Firebase project_id as appId and set
PostHogOptions.capturePushNotificationSubscriptions to false first —
otherwise the device registers twice (APNs under the bundle id, FCM under the project
id), a Workflow with both integrations delivers twice, and
unregisterPushNotificationToken clears only the most recent.
Not supported on web or macOS.
Parameters
| Parameter | Type |
|---|---|
deviceToken | string |
options? | { appId?: string; } |
options.appId? | string |
Returns
Promise<void>
PostHog.resetSessionId
resetSessionId():
void
Returns
void
PostHog.unregisterPushNotificationToken
unregisterPushNotificationToken():
Promise<void>
Unregisters this device's push token so Workflows stop targeting it — for example
from your logout flow. Requires @posthog/react-native-plugin.
Durable: a failed or offline request retries on the next flush or launch. reset()
already moves a registered token to the new identity, so this is only needed if you
manage subscriptions yourself.
Not supported on web or macOS.
Returns
Promise<void>
PostHog.updateFlags
updateFlags(
flags,payloads?,options?):void
Replaces (or merges into) the stored feature flags and payloads with locally supplied
values, exactly as if they had been returned by the flags endpoint: the values are
persisted, getFeatureFlag()/getFeatureFlagPayload() read them back, and
onFeatureFlags listeners fire. Makes no network request.
Intended for apps that evaluate flags outside the SDK (e.g. server-side local
evaluation) and push the results in at runtime, typically together with the
disableRemoteFeatureFlags option so the SDK never fetches flags itself.
Parameters
| Parameter | Type | Description |
|---|---|---|
flags | Record<string, boolean | string> | Flag keys mapped to their values (boolean, or a variant string) |
payloads? | Record<string, JsonType> | Optional flag keys mapped to their JSON payloads |
options? | { merge?: boolean; } | Set merge: true to merge with the currently stored flags instead of replacing them |
options.merge? | boolean | - |
Returns
void
Remarks
The values are cleared by reset(), so push them again after an identity change.
Examples
Types
ActionStepStringMatching
ActionStepStringMatching = typeof
ActionStepStringMatching[keyof typeofActionStepStringMatching]
Sync with plugin-server/src/types.ts
ActionStepType
ActionStepType =
object
Properties
AutocaptureOptions
| Property | Type | Description |
|---|---|---|
androidNdkCrashes? | boolean | Enables autocapture of native C/C++ (NDK) crashes on Android, through the optional native plugin. Requires Android 12 (API 31) or later and exception autocapture enabled in the project's error tracking settings. An NDK crash kills the process immediately, so it is captured on the next app launch from the records the OS kept, which means properties such as $app_version and the identity describe that launch rather than the crash. The first launch after enabling this also captures the native crashes the OS still holds from before. For readable stack traces, upload the app's .so debug symbols. With Expo, set uploadNativeSymbols on the posthog-react-native/expo config plugin: https://posthog.com/docs/error-tracking/upload-source-maps/react-native#native-crash-symbolication Ignored on other platforms. Disabled by default. Requires @posthog/react-native-plugin 2.12.0 or newer. |
console? | boolean | LogLevel[] | - |
nativeCrashes? | boolean | Enables native iOS/Android/macOS crash autocapture through the optional native plugin. On Android this covers Java/Kotlin crashes; native C/C++ (NDK) crashes are enabled with androidNdkCrashes. On Apple platforms it covers signal crashes too. Disabled by default. Requires @posthog/react-native-plugin installed (2.2.0 or newer for macOS). |
uncaughtExceptions? | boolean | - |
unhandledRejections? | boolean | - |
BasicSurveyQuestion
BasicSurveyQuestion =
SurveyQuestionBase&object
Type Declaration
| Name | Type |
|---|---|
type | typeof SurveyQuestionType.Open |
BeforeSendFn
BeforeSendFn = (
event) =>CaptureEvent|null
Function type for the before_send hook.
Receives an event and can return a modified event or null to drop the event.
Parameters
| Parameter | Type |
|---|---|
event | CaptureEvent |
Returns
CaptureEvent | null
BeforeSendLogFn
BeforeSendLogFn = (
record) =>CaptureLogOptions|null
Pre-send filter. Inspect, mutate, or drop a captured log record before it
enters the rate cap or the buffer. Return the (possibly transformed) record
to keep it; return null to drop it.
Configure as a single function or an array. Arrays form a left-to-right
chain: each function receives the previous function's return value, and a
null from any link short-circuits the chain and drops the record. A
function that throws also drops the record (the error is logged).
Parameters
| Parameter | Type |
|---|---|
record | CaptureLogOptions |
Returns
CaptureLogOptions | null
Example
Redact secrets from log bodies
CaptureEvent
CaptureEvent =
object
Represents an event before it's sent to PostHog.
This is the interface exposed to the before_send hook, matching the web SDK's CaptureResult.
Properties
CaptureLogger
CaptureLogger =
Logger
CaptureLogOptions
Compression
EndBranching
EndBranching =
object
Properties
ErrorTrackingOptions
EvaluationReason
EvaluationReason =
object
Properties
EventHint
CoercingContext
Properties
ExceptionStepsOptions
Controls the breadcrumb-style exception steps recorded via addExceptionStep and attached
to captured exceptions as $exception_steps.
Properties
FeatureFlagDetail
FeatureFlagDetail =
object
Properties
FeatureFlagMetadata
FeatureFlagMetadata =
object
Properties
FeatureFlagResult
FeatureFlagResult =
object
Result of evaluating a feature flag, including both the flag value and its payload.
Properties
FeatureFlagResultOptions
FeatureFlagResultOptions =
object
Properties
FeatureFlagValue
FeatureFlagValue =
string|boolean
FeatureFlagWithPayload
FeatureFlagWithPayload = [
FeatureFlagValue|undefined,JsonType|undefined]
IsFeatureEnabledOptions
IsFeatureEnabledOptions =
FeatureFlagResultOptions&object
Type Declaration
| Name | Type | Description |
|---|---|---|
defaultValue? | boolean | Value to return when the flag has no value, e.g. flags have not loaded yet or no flag with that key exists. |
JsonType
JsonType =
string|number|boolean|null| {[key:string]:JsonType; } |JsonType[] |JsonType[]
LinkSurveyQuestion
LinkSurveyQuestion =
SurveyQuestionBase&object
Type Declaration
| Name | Type |
|---|---|
link? | string | null |
type | typeof SurveyQuestionType.Link |
LogAttributes
LogAttributes =
Record<string,LogAttributeValue>
LogAttributeValue
LogAttributeValue =
string|number|boolean|null|undefined|unknown[] |Record<string,unknown>
Logger
Per-level convenience logger. Each method captures a structured log record
at the corresponding severity, equivalent to
posthog.captureLog({ body, level, attributes }).
Example
Methods
debug()
debug(
body,attributes?):void
Debug-level detail. Verbose, only useful while diagnosing.
Parameters
| Parameter | Type |
|---|---|
body | string |
attributes? | LogAttributes |
Returns
void
error()
error(
body,attributes?):void
Error. Operation failed; the app may continue.
Parameters
| Parameter | Type |
|---|---|
body | string |
attributes? | LogAttributes |
Returns
void
fatal()
fatal(
body,attributes?):void
Fatal. Operation failed; the app likely cannot continue.
Parameters
| Parameter | Type |
|---|---|
body | string |
attributes? | LogAttributes |
Returns
void
info()
info(
body,attributes?):void
Informational. Normal app events worth recording.
Parameters
| Parameter | Type |
|---|---|
body | string |
attributes? | LogAttributes |
Returns
void
trace()
trace(
body,attributes?):void
Lowest severity. Trace-level diagnostic detail.
Parameters
| Parameter | Type |
|---|---|
body | string |
attributes? | LogAttributes |
Returns
void
warn()
warn(
body,attributes?):void
Warning. Something unexpected but non-fatal.
Parameters
| Parameter | Type |
|---|---|
body | string |
attributes? | LogAttributes |
Returns
void
LogLevel
LogLevel =
"debug"|"log"|"info"|"warn"|"error"
LogSeverityLevel
LogSeverityLevel =
"trace"|"debug"|"info"|"warn"|"error"|"fatal"
Log capture types
Mechanism
MultipleSurveyQuestion
MultipleSurveyQuestion =
SurveyQuestionBase&object
Type Declaration
| Name | Type |
|---|---|
choices | string[] |
hasOpenChoice? | boolean |
shuffleOptions? | boolean |
skipSubmitButton? | boolean |
type | typeof SurveyQuestionType.SingleChoice | typeof SurveyQuestionType.MultipleChoice |
NextQuestionBranching
NextQuestionBranching =
object
Properties
PartialWithRequired
PartialWithRequired<
T,K> ={ [P in K]: T[P] }&{ [P in Exclude<keyof T, K>]?: T[P] }
Creates a type with all properties of T, but makes only K properties required while the rest remain optional.
Type Parameters
Example
PostHogAutocaptureElement
PostHogAutocaptureElement =
object&PostHogEventProperties
Type Declaration
| Name | Type |
|---|---|
$el_text? | string |
href? | string |
nth_child? | number |
nth_of_type? | number |
order? | number |
tag_name | string |
PostHogAutocaptureNavigationTrackerOptions
PostHogAutocaptureNavigationTrackerOptions =
object
Properties
PostHogAutocaptureOptions
PostHogAutocaptureOptions =
object
Properties
| Property | Type | Description |
|---|---|---|
captureScreens? | boolean | Capture the screen name (or route name) and properties Only used for expo-router, @react-navigation/native and react-native-navigation For react-native-navigation, you need to call initReactNativeNavigation before using this option See example: https://posthog.com/docs/libraries/react-native#with-react-native-navigation-and-autocapture For @react-navigation/native v6 and below, you need to wrap the PostHogProvider within the NavigationContainer See example: https://posthog.com/docs/libraries/react-native#with-react-navigationnative-and-autocapture For @react-navigation/native v7 and above, because of a library change, you'll need to capture the screens manually and disable this option You can use the onStateChange callback from the NavigationContainer to capture the screens automatically using the screen capture method You can use the 'usePostHog()' hook or your own posthog instance to capture the screens Since captureScreens is disabled, you don't need to pass the navigationRef, the navigation mutation object is also ignored See example: https://reactnavigation.org/docs/screen-tracking/ and https://posthog.com/docs/libraries/react-native#manually-capturing-screen-capture-events For expo-router, expo-router uses @react-navigation/native, but does not expose the NavigationContainer, you'll need to capture the screens manually and disable this option expo-router always has access to a URL, you can use the URL to capture the screens automatically using the screen capture method You can use the 'usePostHog()' hook or your own posthog instance to capture the screens Since captureScreens is disabled, you don't need to pass the navigationRef, the navigation mutation object is also ignored See example: https://docs.expo.dev/router/reference/screen-tracking/ and https://posthog.com/docs/libraries/react-native#manually-capturing-screen-capture-events Default true |
captureTouches? | boolean | Enable autocapture of touch events. On React Native Web this also captures click events — mouse, trackpad, keyboard activation and programmatic clicks — emitted with $event_type: 'click', since browsers fire touchend only for touch input. Default false |
customLabelProp? | string | Custom prop name used to label elements for autocapture Default 'ph-label' |
ignoreLabels? | string[] | List of element labels to ignore during autocapture Default [] |
maxElementsCaptured? | number | Maximum number of elements to capture in the component tree hierarchy Default 20 |
navigation? | PostHogAutocaptureNavigationTrackerOptions | Used for mutating the screen name and properties Only used if captureScreens is true Default Default to the route name and params |
navigationRef? | PostHogNavigationRef | If you create a navigation ref with createNavigationContainerRef, you need to pass the navigation ref Only used for expo-router and @react-navigation/native if captureScreens is true Deprecated this is deprecated since it didn't work as expected, check out the captureScreens comments for capturing screen views semi-automatically |
noCaptureProp? | string | Prop name used to prevent autocapture on an element and its children Default 'ph-no-capture' |
propsToCapture? | string[] | List of prop names to capture from elements Default ['style', 'testID', 'accessibilityLabel', 'ph-label', 'children'] |
PostHogCaptureOptions
PostHogCaptureOptions =
object
Properties
PostHogCoreOptions
PostHogCoreOptions =
object
Extended by
PostHogOptions
Properties
| Property | Type | Description |
|---|---|---|
addTracingHeaders? | string[] | A list of hostnames for which to inject PostHog tracing headers (X-POSTHOG-DISTINCT-ID, X-POSTHOG-SESSION-ID) on outgoing fetch requests. Use this to link requests made from your app to session replays and LLM traces in PostHog. When set, the global fetch is patched on initialization and the headers are added to requests whose hostname matches one of the entries. Requires the SDK to wire up patchFetchForTracingHeaders against this option (currently supported in posthog-react-native). |
before_send? | BeforeSendFn | BeforeSendFn[] | Allows modification or dropping of events before they're sent to PostHog. If an array is provided, the functions are run in order. If a function returns null, the event will be dropped. |
bootstrap? | object | Option to bootstrap the library with given distinctId and feature flags |
bootstrap.distinctId? | string | - |
bootstrap.featureFlagPayloads? | Record<string, JsonType> | - |
bootstrap.featureFlags? | Record<string, FeatureFlagValue> | - |
bootstrap.isIdentifiedId? | boolean | - |
defaultOptIn? | boolean | If set to false the SDK will not track until the optIn function is called. Default true |
disable_capture_url_hashes? | boolean | Whether to strip URL fragments (#...) from automatically captured URL fields. Disabled by default for backwards compatibility. Set to true to strip hashes from: - $current_url on automatically captured browser events, including $pageview - $initial_current_url - $session_entry_url - $elements[*].attr__href and $external_click_url for autocapture and dead-click autocapture - Next.js Pages Router $pageview $current_url - web vitals $current_url - logs url.full - conversations current_url and request_url - session replay rrweb meta/custom-event href URLs - heatmap data URLs If your SPA relies on hash-based routes for analytics, enabling this is a breaking behavior change. If you want to capture hashes selectively, leave this as false and use before_send to remove sensitive hash values before events are sent. Default false |
disableCompression? | boolean | Whether to disable GZIP compression Default false |
disabled? | boolean | If set to true the SDK is essentially disabled (useful for local environments where you don't want to track anything) Default false |
disableGeoip? | boolean | Whether to disable GeoIP lookups Default false |
disableRemoteConfig? | boolean | Whether to load remote config when initialized or not Deprecated Remote config is now always loaded and this option is a no-op. It will be removed in a future version. Default false |
disableRemoteFeatureFlags? | boolean | Advanced: whether to disable fetching and evaluating feature flags from PostHog entirely. When set to true, reloadFeatureFlags() and the reloads triggered by identify(), group(), setPersonPropertiesForFlags() and reset() become no-ops, and any request to the flags endpoint that still goes out (e.g. to fetch remote config or surveys) carries disable_flags: true so the server skips flag evaluation. Flag values must be supplied via the bootstrap option or updateFlags() instead; getFeatureFlag() and related methods keep working against those values. Until updateFlags() runs, reads return their not-loaded defaults, so use bootstrap for any flags needed at startup. Equivalent to the web SDK's advanced_disable_feature_flags. Note: surveys gated on feature flags will not evaluate unless the survey targeting flags are also provided via updateFlags(). This option cannot be toggled at runtime. posthog-node inherits this option but does not implement it (no-op). Default false |
disableSurveys? | boolean | Whether to load surveys when initialized or not Requires the PostHogSurveyProvider to be used Default false |
evaluationContexts? | readonly string[] | Evaluation contexts for feature flags. When set, only feature flags that have at least one matching evaluation tag will be evaluated for this SDK instance. Feature flags with no evaluation tags will always be evaluated. Examples: ['production', 'web', 'mobile'] Default undefined |
evaluationEnvironments? | readonly string[] | Evaluation environments for feature flags. Deprecated Use evaluationContexts instead. This property will be removed in a future version. |
featureFlagsRequestMaxRetries? | number | How many times feature flag requests retry after a transient network error. Set to 0 to disable feature flag request retries. Default 1 |
featureFlagsRequestTimeoutMs? | number | Timeout in milliseconds for feature flag calls Default 10000 for stateful clients, 3000 for stateless |
fetchRetryCount? | number | How many times we will retry HTTP requests Default 3 |
fetchRetryDelay? | number | The delay between HTTP request retries in milliseconds Default 3000 |
flushAt? | number | The number of events to queue before sending to PostHog (flushing) Default 20 |
flushInterval? | number | The interval in milliseconds between periodic flushes Default 10000 |
historicalMigration? | boolean | Special flag to indicate ingested data is for a historical migration Default false |
host? | string | PostHog API host, usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com' Default 'https://us.i.posthog.com' |
maxBatchSize? | number | The maximum number of queued messages to be flushed as part of a single batch (must be higher than flushAt) Default 100 |
maxQueueSize? | number | The maximum number of cached messages either in memory or on the local storage (must be higher than flushAt) Default 1000 |
personProfiles? | "always" | "identified_only" | "never" | Determines when to create Person Profiles for users. - 'always': Always create a person profile for every user (anonymous and identified). - 'identified_only': Only create a person profile when the user is identified via identify(), alias(), or group(). Events captured before identification will NOT have person profiles and will be anonymous events. - 'never': Never create person profiles. identify(), alias(), and group() will be no-ops. Default 'identified_only' Examples // Only create profiles when users are identified (recommended for most apps) const posthog = new PostHog('<api_key>', { personProfiles: 'identified_only', }) // Later when user logs in: posthog.identify('user-123', { email: 'user@example.com' }) // Always create profiles (for apps where you want to track all users) const posthog = new PostHog('<api_key>', { personProfiles: 'always', }) // Never create profiles (anonymous analytics only) const posthog = new PostHog('<api_key>', { personProfiles: 'never', }) |
preloadFeatureFlags? | boolean | Whether to load feature flags when initialized or not Default true |
remoteConfigRequestTimeoutMs? | number | Timeout in milliseconds for remote config calls Default 3000 |
requestTimeout? | number | Timeout in milliseconds for any calls Default 10000 |
sendFeatureFlagEvent? | boolean | Whether to track that getFeatureFlag was called (used by Experiments) In posthog-node this is also the default for reads from an evaluateFlags() snapshot (isEnabled() / getFlag()). Pass sendFeatureFlagEvents to one of those reads, or to a single-flag getter, to override it for that call. Default true |
sessionExpirationTimeSeconds? | number | For Session Analysis how long before we expire a session in seconds Default 1800 |
PostHogCustomAppProperties
PostHogCustomStorage
PostHogErrorBoundaryFallbackProps
PostHogErrorBoundaryFallbackProps =
object
Properties
PostHogErrorBoundaryProps
PostHogErrorBoundaryProps =
object
Properties
PostHogErrorBoundaryState
PostHogErrorBoundaryState =
object
Properties
PostHogEventProperties
PostHogEventProperties =
object
Index Signature
[key: string]: JsonType
PostHogFeatureFlagDetails
PostHogFeatureFlagDetails =
PartialWithRequired<PostHogFlagsResponse,"flags"|"featureFlags"|"featureFlagPayloads"|"requestId">
These are the fields we care about from PostHogFlagsResponse for feature flags.
PostHogFlagsResponse
PostHogFlagsResponse =
Omit<PostHogRemoteConfig,"hasFeatureFlags"> &object
Type Declaration
| Name | Type | Description |
|---|---|---|
errorsWhileComputingFlags | boolean | - |
evaluatedAt? | number | - |
featureFlagPayloads | object | - |
featureFlags | object | - |
flags | object | - |
minimalFlagCalledEvents? | boolean | Server-controlled gate for minimal $feature_flag_called events. true only when the project opted in; omitted otherwise. Absence always means full events. |
quotaLimited? | string[] | - |
requestId? | string | - |
sessionRecording? | boolean | {[key: string]: JsonType; } | - |
PostHogGroupProperties
PostHogGroupProperties =
object
Index Signature
[type: string]: string | number
PostHogLogsConfig
Configuration for the logs feature on new PostHog(key, { logs: ... }).
All fields are optional; per-SDK defaults apply (mobile vs browser tune
differently for cellular cost vs tab-suspension behavior).
Properties
PostHogMaskViewProps
Props for the PostHogMaskView component.
Extends
ViewProps
Properties
PostHogNavigationRef
PostHogNavigationRef =
object
Deprecated
Properties
Methods
getCurrentRoute()
getCurrentRoute():
any
Returns
any
PostHogOptions
PostHogCoreOptions
Properties
| Property | Type | Description | Inherited from |
|---|---|---|---|
addTracingHeaders? | string[] | A list of hostnames for which to inject PostHog tracing headers (X-POSTHOG-DISTINCT-ID, X-POSTHOG-SESSION-ID) on outgoing fetch requests. Use this to link requests made from your app to session replays and LLM traces in PostHog. When set, the global fetch is patched on initialization and the headers are added to requests whose hostname matches one of the entries. Requires the SDK to wire up patchFetchForTracingHeaders against this option (currently supported in posthog-react-native). | PostHogCoreOptions.addTracingHeaders |
before_send? | BeforeSendFn | BeforeSendFn[] | Allows modification or dropping of events before they're sent to PostHog. If an array is provided, the functions are run in order. If a function returns null, the event will be dropped. | PostHogCoreOptions.before_send |
bootstrap? | object | Option to bootstrap the library with given distinctId and feature flags | PostHogCoreOptions.bootstrap |
bootstrap.distinctId? | string | - | - |
bootstrap.featureFlagPayloads? | Record<string, JsonType> | - | - |
bootstrap.featureFlags? | Record<string, FeatureFlagValue> | - | - |
bootstrap.isIdentifiedId? | boolean | - | - |
captureAppLifecycleEvents? | boolean | Captures app lifecycle events such as Application Installed, Application Updated, Application Opened, Application Became Active and Application Backgrounded. Application Installed and Application Updated events are not supported with persistence set to 'memory'. Default true | - |
capturePushNotificationOpened? | boolean | Whether to automatically capture $push_notification_opened on a notification tap. Requires @posthog/react-native-plugin. Fires for pushes from any provider, not just PostHog's — but title and body are attached only for PostHog's own, so third-party notification text never reaches analytics. On Android, taps that launch the app and taps while it's running are both captured from @posthog/react-native-plugin 2.6.0 (earlier versions: cold starts only); call PostHog.capturePushNotificationOpened for the taps it misses. The native SDK builds and sends this event, so JS before_send never sees it. On iOS a tap can reach the app before your JS runs, so the SDK installs a hook at launch to catch a tap that cold-launches the app. Two switches gate automatic capture there, and false on either one means the SDK sends no $push_notification_opened of its own (an explicit PostHog.capturePushNotificationOpened call still captures): - This option set to false turns capture off when setup() runs and releases the launch hook, dropping the tap it was holding. The hook is still installed for the window between launch and setup(). - com.posthog.posthog.CAPTURE_PUSH_NOTIFICATION_OPENED set to false in Info.plist (Expo: ios.infoPlist) skips the launch hook entirely, so nothing is installed before your JS runs, and forces capture off at setup() even when this option is true. It is the same key posthog-flutter reads. Not supported on web. Default true | - |
capturePushNotificationSubscriptions? | boolean | Whether to automatically register this device's push token so PostHog Workflows can target it. Requires @posthog/react-native-plugin. Your app still owns permission — PostHog only observes the token the OS hands back, and never sees later refreshes. Forward those to PostHog.registerPushNotificationToken yourself. Not supported on web or macOS. Default true | - |
customAppProperties? | PostHogCustomAppProperties | ((properties) => PostHogCustomAppProperties) | Allows you to provide your own implementation of the common information about your App or a function to modify the default App properties generated | - |
customStorage? | PostHogCustomStorage | Allows you to provide a custom asynchronous storage such as async-storage, expo-file-system or a synchronous storage such as mmkv. If not provided, PostHog will attempt to use the best available storage via optional peer dependencies (async-storage, expo-file-system). If persistence is set to 'memory', this option will be ignored. | - |
defaultOptIn? | boolean | If set to false the SDK will not track until the optIn function is called. Default true | PostHogCoreOptions.defaultOptIn |
disable_capture_url_hashes? | boolean | Whether to strip URL fragments (#...) from automatically captured URL fields. Disabled by default for backwards compatibility. Set to true to strip hashes from: - $current_url on automatically captured browser events, including $pageview - $initial_current_url - $session_entry_url - $elements[*].attr__href and $external_click_url for autocapture and dead-click autocapture - Next.js Pages Router $pageview $current_url - web vitals $current_url - logs url.full - conversations current_url and request_url - session replay rrweb meta/custom-event href URLs - heatmap data URLs If your SPA relies on hash-based routes for analytics, enabling this is a breaking behavior change. If you want to capture hashes selectively, leave this as false and use before_send to remove sensitive hash values before events are sent. Default false | PostHogCoreOptions.disable_capture_url_hashes |
disableCompression? | boolean | Whether to disable GZIP compression Default false | PostHogCoreOptions.disableCompression |
disabled? | boolean | If set to true the SDK is essentially disabled (useful for local environments where you don't want to track anything) Default false | PostHogCoreOptions.disabled |
disableGeoip? | boolean | Whether to disable GeoIP lookups Default false | PostHogCoreOptions.disableGeoip |
disableRemoteConfig? | boolean | Whether to load remote config when initialized or not Deprecated Remote config is now always loaded and this option is a no-op. It will be removed in a future version. Default false | PostHogCoreOptions.disableRemoteConfig |
disableRemoteFeatureFlags? | boolean | Advanced: whether to disable fetching and evaluating feature flags from PostHog entirely. When set to true, reloadFeatureFlags() and the reloads triggered by identify(), group(), setPersonPropertiesForFlags() and reset() become no-ops, and any request to the flags endpoint that still goes out (e.g. to fetch remote config or surveys) carries disable_flags: true so the server skips flag evaluation. Flag values must be supplied via the bootstrap option or updateFlags() instead; getFeatureFlag() and related methods keep working against those values. Until updateFlags() runs, reads return their not-loaded defaults, so use bootstrap for any flags needed at startup. Equivalent to the web SDK's advanced_disable_feature_flags. Note: surveys gated on feature flags will not evaluate unless the survey targeting flags are also provided via updateFlags(). This option cannot be toggled at runtime. posthog-node inherits this option but does not implement it (no-op). Default false | PostHogCoreOptions.disableRemoteFeatureFlags |
disableSurveys? | boolean | Whether to load surveys when initialized or not Requires the PostHogSurveyProvider to be used Default false | PostHogCoreOptions.disableSurveys |
enablePersistSessionIdAcrossRestart? | boolean | If enabled, the session id ($session_id) will be persisted across app restarts. This is an option for back compatibility, so your current data isn't skewed with the new version of the SDK. If this is false, the session id will be always reset on app restart. Default false | - |
enableSessionReplay? | boolean | Enable Recording of Session Replays for Android and iOS Requires Record user sessions to be enabled in the PostHog Project Settings This option is read once, at setup. To record only some sessions, either gate recording from your project settings (sampling, a linked flag, or event triggers), or leave this option off and drive the recorder from your app with startSessionRecording() and stopSessionRecording(). Default false | - |
errorTracking? | ErrorTrackingOptions | Error Tracking Configuration | - |
evaluationContexts? | readonly string[] | Evaluation contexts for feature flags. When set, only feature flags that have at least one matching evaluation tag will be evaluated for this SDK instance. Feature flags with no evaluation tags will always be evaluated. Examples: ['production', 'web', 'mobile'] Default undefined | PostHogCoreOptions.evaluationContexts |
evaluationEnvironments? | readonly string[] | Evaluation environments for feature flags. Deprecated Use evaluationContexts instead. This property will be removed in a future version. | PostHogCoreOptions.evaluationEnvironments |
featureFlagsRequestMaxRetries? | number | How many times feature flag requests retry after a transient network error. Set to 0 to disable feature flag request retries. Default 1 | PostHogCoreOptions.featureFlagsRequestMaxRetries |
featureFlagsRequestTimeoutMs? | number | Timeout in milliseconds for feature flag calls Default 10000 for stateful clients, 3000 for stateless | PostHogCoreOptions.featureFlagsRequestTimeoutMs |
fetchRetryCount? | number | How many times we will retry HTTP requests Default 3 | PostHogCoreOptions.fetchRetryCount |
fetchRetryDelay? | number | The delay between HTTP request retries in milliseconds Default 3000 | PostHogCoreOptions.fetchRetryDelay |
flushAt? | number | The number of events to queue before sending to PostHog (flushing) Default 20 | PostHogCoreOptions.flushAt |
flushInterval? | number | The interval in milliseconds between periodic flushes Default 10000 | PostHogCoreOptions.flushInterval |
historicalMigration? | boolean | Special flag to indicate ingested data is for a historical migration Default false | PostHogCoreOptions.historicalMigration |
host? | string | PostHog API host, usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com' Default 'https://us.i.posthog.com' | PostHogCoreOptions.host |
logs? | PostHogLogsConfig | Logs feature configuration. Enables structured log capture via posthog.captureLog(...) or posthog.logger.info(...). Records ship to PostHog's logs product (/i/v1/logs) in OTLP format, batched on a timer, AppState change, buffer fill, or manual flushLogs(). Capture is unconditional — calling the API ships records as long as the SDK is initialized and the user hasn't opted out. The only blockers are optedOut, missing/empty body, and missing API key. All fields below are optional; per-SDK defaults apply (mobile defaults are tuned for cellular bandwidth and battery, ~50 logs/sec ceiling). Examples Minimal — just service tagging, defaults for everything else new PostHog(key, { logs: { serviceName: 'my-app', environment: 'production' } }) Tune for higher-volume logging new PostHog(key, { logs: { serviceName: 'my-app', rateCap: { maxLogs: 5000, windowMs: 60000 }, maxBufferSize: 500, beforeSend: (r) => r.body.includes('secret') ? null : r, } }) | - |
maxBatchSize? | number | The maximum number of queued messages to be flushed as part of a single batch (must be higher than flushAt) Default 100 | PostHogCoreOptions.maxBatchSize |
maxQueueSize? | number | The maximum number of cached messages either in memory or on the local storage (must be higher than flushAt) Default 1000 | PostHogCoreOptions.maxQueueSize |
overrideDisplayLanguage? | string | null | Overrides the language used when rendering translated survey copy. When unset, the SDK falls back to the persisted person property language and then the device locale. | - |
persistence? | "memory" | "file" | Allows you to provide the storage type. 'file' will try to load the best available storage, the provided 'customStorage', 'customAsyncStorage' or in-memory storage. Default 'file' | - |
personProfiles? | "always" | "identified_only" | "never" | Determines when to create Person Profiles for users. - 'always': Always create a person profile for every user (anonymous and identified). - 'identified_only': Only create a person profile when the user is identified via identify(), alias(), or group(). Events captured before identification will NOT have person profiles and will be anonymous events. - 'never': Never create person profiles. identify(), alias(), and group() will be no-ops. Default 'identified_only' Examples // Only create profiles when users are identified (recommended for most apps) const posthog = new PostHog('<api_key>', { personProfiles: 'identified_only', }) // Later when user logs in: posthog.identify('user-123', { email: 'user@example.com' }) // Always create profiles (for apps where you want to track all users) const posthog = new PostHog('<api_key>', { personProfiles: 'always', }) // Never create profiles (anonymous analytics only) const posthog = new PostHog('<api_key>', { personProfiles: 'never', }) | PostHogCoreOptions.personProfiles |
preloadFeatureFlags? | boolean | Whether to load feature flags when initialized or not Default true | PostHogCoreOptions.preloadFeatureFlags |
pushIdentityProvider? | PostHogPushIdentityProvider | Mints a signed identity-verification token for push subscription requests. Only needed when your PostHog project requires identity verification for push. Requires @posthog/react-native-plugin. Called with the current distinctId and appId. Mint on your backend (HS256, sub = distinctId, an app_id claim, aud = posthog:push_identity), never in the app. Return null to send the request unauthenticated; a slow or throwing implementation does the same after 10 seconds. | - |
rageClickConfig? | PostHogRageClickConfig | Configure rage click (rage tap) detection on iOS. The native iOS SDK fires a $rageclick event when a user taps the same area repeatedly in quick succession. The default thresholds (3 taps, 30 points, 1 second) were tuned for web and frequently produce false positives on mobile. Raise the thresholds or set enabled: false to suppress them. Android is unaffected — posthog-android does not have native rage click detection. Requires @posthog/react-native-plugin version 2.7.0 or newer. | - |
remoteConfigRequestTimeoutMs? | number | Timeout in milliseconds for remote config calls Default 3000 | PostHogCoreOptions.remoteConfigRequestTimeoutMs |
requestHeaders? | object | A list of headers that should be sent with requests to the PostHog API. | - |
requestTimeout? | number | Timeout in milliseconds for any calls Default 10000 | PostHogCoreOptions.requestTimeout |
sendFeatureFlagEvent? | boolean | Whether to track that getFeatureFlag was called (used by Experiments) In posthog-node this is also the default for reads from an evaluateFlags() snapshot (isEnabled() / getFlag()). Pass sendFeatureFlagEvents to one of those reads, or to a single-flag getter, to override it for that call. Default true | PostHogCoreOptions.sendFeatureFlagEvent |
sessionExpirationTimeSeconds? | number | For Session Analysis how long before we expire a session in seconds Default 1800 | PostHogCoreOptions.sessionExpirationTimeSeconds |
sessionReplayConfig? | PostHogSessionReplayConfig | Configuration for Session Replay | - |
setDefaultPersonProperties? | boolean | Automatically include common device and app properties in feature flag evaluation. When enabled, the following properties are sent with every /flags request: - $app_version: App version - $app_build: App build number - $app_namespace: App bundle identifier / namespace - $os_name: Operating system name - $os_version: Operating system version - $device_type: Device type (Mobile, Desktop) - $lib: Name of the SDK library - $lib_version: Version of the SDK library This ensures feature flags that rely on these properties work correctly without waiting for server-side processing of identify() calls. Default true | - |
PostHogPersistedProperty
PostHogProviderProps
Props for the PostHogProvider component.
Properties
| Property | Type | Description |
|---|---|---|
apiKey? | string | Your PostHog project token. Ignored when projectToken is set. Deprecated Use projectToken instead. This will be removed in the next major version. |
autocapture? | boolean | PostHogAutocaptureOptions | Autocapture configuration - can be a boolean or detailed options. When not set, the default behavior is: - captureScreens: true - captureTouches: false - captureAppLifecycleEvents: true Set to true to enable all autocapture features (including touches). Set to false to disable all autocapture features. |
children | ReactNode | The child components to render within the PostHog context |
client? | PostHog | An existing PostHog client instance |
debug? | boolean | Enable debug mode for additional logging Default false |
options? | PostHogOptions | PostHog configuration options |
projectToken? | string | Your PostHog project token, which starts with phc_. Find it in your project settings: https://us.posthog.com/settings/project-details#variables |
style? | StyleProp<ViewStyle> | Custom styles for the provider wrapper View |
PostHogPushIdentityProvider
PostHogPushIdentityProvider = (
distinctId,appId) =>Promise<string|null>
Mints a signed identity-verification token for a push subscription request.
Called by the native SDK with the current distinctId and appId. Return
null to send the request without an identity token.
Parameters
| Parameter | Type |
|---|---|
distinctId | string |
appId | string |
Returns
Promise<string | null>
PostHogRageClickConfig
PostHogRageClickConfig =
object
Properties
PostHogRemoteConfig
PostHogRemoteConfig =
object
Properties
PostHogSessionReplayConfig
PostHogSessionReplayConfig =
object
Properties
PostHogSurveyProviderProps
PostHogSurveyProviderProps =
object
Properties
Properties
Properties =
Record<string,any>
Properties
Properties =
Record<string,Property>
Property
Property =
any
Common types shared across PostHog SDKs
PropertyFilters
PropertyFilters =
Record<string, {operator:PropertyOperator;values:string[]; }>
PropertyMatchType
PropertyMatchType =
SurveyMatchType
PropertyOperator
PropertyOperator =
PropertyMatchType|"gt"|"lt"
RatingSurveyQuestion
RatingSurveyQuestion =
SurveyQuestionBase&object
Type Declaration
| Name | Type |
|---|---|
display | SurveyRatingDisplay |
lowerBoundLabel | string |
scale | 2 | 3 | 5 | 7 | 10 |
skipSubmitButton? | boolean |
type | typeof SurveyQuestionType.Rating |
upperBoundLabel | string |
ResponseBasedBranching
ResponseBasedBranching =
object
Properties
SpecificQuestionBranching
SpecificQuestionBranching =
object
Properties
Survey
Survey =
object
Properties
SurveyActionType
SurveyActionType =
object
Properties
SurveyAppearance
React Native survey appearance, including native-only text scaling options.
Extends
SurveyAppearance
Properties
SurveyAppearance
SurveyAppearance =
object
Extended by
SurveyAppearance
Properties
SurveyAppearanceTheme
SurveyAppearanceTheme =
Omit<Required<SurveyAppearance>,"widgetSelector"|"widgetType"|"widgetColor"|"widgetLabel"|"shuffleQuestions"|"textColor"|"inputTextColor"|"placeholder"|"maxFontSizeMultiplier"> &object
Type Declaration
| Name | Type |
|---|---|
inputTextColor? | string |
maxFontSizeMultiplier? | SurveyAppearance["maxFontSizeMultiplier"] |
placeholder? | string |
textColor? | string |
SurveyEventWithFilters
SurveyMatchType
SurveyMatchType = typeof
SurveyMatchType[keyof typeofSurveyMatchType]
SurveyModalProps
SurveyModalProps =
object
Properties
SurveyPosition
SurveyPosition = typeof
SurveyPosition[keyof typeofSurveyPosition]
SurveyProgress
SurveyProgress =
object
Properties
SurveyQuestion
SurveyQuestion =
BasicSurveyQuestion|LinkSurveyQuestion|RatingSurveyQuestion|MultipleSurveyQuestion
SurveyQuestionBase
SurveyQuestionBase =
object
Properties
SurveyQuestionDescriptionContentType
SurveyQuestionDescriptionContentType = typeof
SurveyQuestionDescriptionContentType[keyof typeofSurveyQuestionDescriptionContentType]
SurveyQuestionTranslation
SurveyRatingDisplay
SurveyRatingDisplay = typeof
SurveyRatingDisplay[keyof typeofSurveyRatingDisplay]
SurveyResponses
SurveyResponses =
Record<string,SurveyResponseValue>
SurveyResponseValue
SurveyResponseValue =
string|number|string[] |null
SurveySchedule
SurveySchedule = typeof
SurveySchedule[keyof typeofSurveySchedule]
SurveyTextRole
SurveyTextRole =
"question"|"description"|"header"|"choice"|"input"|"button"|"ratingLabel"|"ratingNumber"|"validationHint"
The distinct kinds of text a survey renders, each at its own base size. They
are separate because one ceiling cannot serve all of them: question is an
18pt headline that can wrap freely, while ratingNumber sits inside a
fixed-width button and has nowhere to grow.
SurveyTranslation
SurveyType
SurveyType = typeof
SurveyType[keyof typeofSurveyType]
SurveyValidationRule
SurveyValidationType
SurveyValidationType = typeof
SurveyValidationType[keyof typeofSurveyValidationType]
SurveyWidgetType
SurveyWidgetType = typeof
SurveyWidgetType[keyof typeofSurveyWidgetType]





