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

Terminal
npm install posthog-react-native

Initialize

Wrap your app in PostHogProvider.

TSX
import { PostHogProvider } from 'posthog-react-native'
export default function App() {
return (
<PostHogProvider projectToken="<ph_project_token>" options={{ host: 'https://us.i.posthog.com' }}>
<YourApp />
</PostHogProvider>
)
}

Capture an event

TSX
import { usePostHog } from 'posthog-react-native'
const posthog = usePostHog()
posthog.capture('signed_up', { plan: 'pro' })

Identify a user

TSX
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.

TSX
import { PostHogProvider } from 'posthog-react-native'
export function App() {
return (
<PostHogProvider
projectToken="<ph_project_token>"
options={{ host: 'https://us.i.posthog.com', disabled: __DEV__ }}
>
<YourApp />
</PostHogProvider>
)
}

Proxy, projects, and allowlists

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.

PathRequirementsSetup
CocoaPodsReact Native 0.75 or later and Xcode 26 or laterRun 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 targetRun 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

FromChange
1.x.xReplace PostHog.setup(...) with new PostHog(token, options) or PostHogProvider. PostHogProvider replaces captureApplicationLifecycleEvents and recordScreenViews. Remove captureDeepLinks, android, and iOS.
2.x.xReplace await PostHog.initAsync(...) with new PostHog(token, options).
3.x.xRename captureNativeAppLifecycleEvents and autocapture={{ captureLifecycleEvents: true }} to captureAppLifecycleEvents. Remove captureMode and maskPhotoLibraryImages. Call setPersonPropertiesForFlags and setGroupPropertiesForFlags in place of personProperties and groupProperties.
4.x.xSee the migration guide.

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 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

ParameterTypeDescription
projectTokenstringYour PostHog project token, which starts with phc_. Find it in your project settings: https://us.posthog.com/settings/project-details#variables
options?PostHogOptionsPostHog configuration options

Returns

PostHog

Example

TypeScript
// posthog.ts
import PostHog from 'posthog-react-native'
export const posthog = new PostHog('<ph_project_token>', {
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 <View>Your app code</View>
}

PostHogProvider

PostHogProvider(props): Element | null

PostHogProvider is a React component that provides PostHog functionality to your React Native app. See PostHogOptions for all configuration options.

Autocapturing navigation requires further configuration. See 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

ParameterTypeDescription
propsPostHogProviderPropsThe PostHogProvider props

Returns

Element | null

Examples

JSX
// Add to App.(js|ts)
import { usePostHog, PostHogProvider } from 'posthog-react-native'
export function MyApp() {
return (
<PostHogProvider projectToken="<ph_project_token>" options={{
host: 'https://us.i.posthog.com',
}}>
<MyComponent />
</PostHogProvider>
)
}
// 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('<ph_project_token>', {
host: 'https://us.i.posthog.com'
})
export function MyApp() {
return (
<PostHogProvider client={posthog}>
<MyComponent />
</PostHogProvider>
)
}

usePostHog

usePostHog(): PostHog

Returns

PostHog

Capture

PostHog.capture

capture(event, properties?, options?): void

Captures an event.

Parameters

ParameterTypeDescription
eventstringThe name of the event
properties?PostHogEventPropertiesOptional properties to include with the event
options?PostHogCaptureOptionsOptional 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 dropped, 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
ParameterType
optionsCaptureErrorParams
Returns

CaptureError

Properties

PropertyModifierTypeOverrides
cause?publicunknownError.cause
dropsreadonlyCaptureDroppedEvent[]-
endpointreadonlyCaptureEndpoint-
namepublicstringError.name
requestIdreadonlystring-
retryExhaustedreadonlystring[]-

Identify

PostHog.identify

identify(distinctId, properties?, options?): void

Associates events with a specific user. Learn more about identifying users

Parameters

ParameterTypeDescription
distinctIdstringA unique identifier for your user. Typically either their email or database ID.
properties?PostHogEventPropertiesOptional dictionary with key:value pairs to set the person properties
options?PostHogCaptureOptionsOptional 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

ParameterTypeDescription
optionsCaptureLogOptionsLog 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

ParameterTypeDescription
aliasstringThe alias to assign to the current user
options?PostHogCaptureOptionsOptional 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

ParameterTypeDescription
eventstringThe AI event name, such as $ai_generation
properties?PostHogEventPropertiesProperties attached only to this event
options?PostHogCaptureOptionsSame 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

ParameterTypeDescription
traceIdstring | numberThe trace ID to capture feedback for.
userFeedbackstringThe 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

ParameterTypeDescription
traceIdstring | numberThe trace ID to capture the metric for.
metricNamestringThe name of the metric to capture.
metricValuestring | number | booleanThe 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

ParameterTypeDescription
errorunknownThe error to capture
additionalProperties?PostHogEventPropertiesAny additional properties to add to the error event
hint?EventHintOptional details about how the error was caught
options?PostHogCaptureOptionsOptional 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
ParameterType
propsPostHogErrorBoundaryProps
Returns

PostHogErrorBoundary

Properties

PropertyModifierTypeDefault valueDescriptionOverrides
contextpublicobjectundefinedIf 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#contextReact.Component.context
context.clientpublicPostHogundefined--
contextTypestaticContext<{ client: PostHog; }>PostHogContextIf 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-contexttypeReact.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
ParameterType
errorunknown
errorInfoErrorInfo
Returns

void

render()

render(): ReactNode

Returns

ReactNode

getDerivedStateFromError()

static getDerivedStateFromError(error): Partial<PostHogErrorBoundaryState>

Parameters
ParameterType
errorunknown
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

ParameterTypeDefault value
enabled?booleantrue

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

ParameterTypeDescription
messagestringA non-empty description of the step
properties?PropertiesOptional 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

ParameterTypeDescription
keystringThe feature flag key
options?PostHogFeatureFlagOptionsOptional 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

ParameterTypeDescription
flagstringKey of the feature flag
client?PostHogA 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

ParameterTypeDescription
flagstringKey of the feature flag
client?PostHogA 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

ParameterTypeDescription
keystringThe feature flag key
options?PostHogFeatureFlagOptionsOptional 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

ParameterType
flagstring
client?PostHog

Returns

FeatureFlagResult | undefined

Get feature flags

PostHog.getAllFeatureFlags

getAllFeatureFlags(): FeatureFlagResult[] | undefined

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 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

ParameterTypeDescription
client?PostHogA 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

ParameterTypeDescription
groupTypestringThe type of group (e.g. 'company', 'team')
groupKeystringThe unique identifier for the group
properties?PostHogEventPropertiesOptional properties to set for the group
options?PostHogCaptureOptionsOptional 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

ParameterType
groupsPostHogGroupProperties

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

ParameterTypeDescription
groupTypestringThe type of group (e.g. 'company', 'team')
groupKeystring | numberThe unique identifier for the group
groupProperties?PostHogEventPropertiesOptional properties to set for the group
options?PostHogCaptureOptionsOptional 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

ParameterTypeDescription
keystringThe feature flag key
options?PostHogIsFeatureEnabledOptionsOptional 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
ParameterTypeDescription
flagstringKey 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
ParameterTypeDescription
flagstringKey of the feature flag
defaultValuebooleanReturned instead of undefined while the value is unknown
client?PostHogA 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
ParameterTypeDescription
flagstringKey of the feature flag
defaultValue?booleanReturned instead of undefined while the value is unknown
client?PostHogA 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

ParameterTypeDescription
callback(loaded) => voidCalled 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

ParameterTypeDescription
propertiesPostHogEventPropertiesAn 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

ParameterType
propertiesPostHogEventProperties

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

ParameterTypeDescription
languagestring | nullA 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

ParameterTypeDescription
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
ParameterTypeDescription
reloadFeatureFlags?booleanWhether 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
ParameterTypeDescription
groupTypestringThe group type whose properties to reset
reloadFeatureFlags?booleanWhether 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

ParameterTypeDefault valueDescription
reloadFeatureFlags?booleantrueWhether 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

ParameterTypeDescription
namestringThe name of the screen
properties?PostHogEventPropertiesOptional properties to include with the screen event
options?PostHogCaptureOptionsOptional 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

ParameterType
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

ParameterTypeDefault valueDescription
propertiesRecord<string, Record<string, JsonType>>undefinedThe group properties to set for flag evaluation
reloadFeatureFlags?booleantrueWhether 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

Parameters

ParameterTypeDefault valueDescription
userPropertiesToSet?{[key: string]: JsonType; }undefinedOptional: An object of properties to store about the user. These properties will overwrite any existing values for the same keys.
userPropertiesToSetOnce?{[key: string]: JsonType; }undefinedOptional: An object of properties to store about the user. If a property is previously set, this does not override that value.
reloadFeatureFlags?booleantrueWhether to reload feature flags after setting the properties. Defaults to true.
options?PostHogCaptureOptionsundefinedOptional 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

Parameters

ParameterTypeDefault valueDescription
propertyNamesstring | string[]undefinedThe name (or names) of the person properties to remove.
reloadFeatureFlags?booleantrueWhether to reload feature flags after removing the properties. Defaults to true.
options?PostHogCaptureOptionsundefinedOptional 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

ParameterTypeDefault valueDescription
propertiesRecord<string, JsonType>undefinedThe person properties to set for flag evaluation
reloadFeatureFlags?booleantrueWhether 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

ParameterTypeDescription
shutdownTimeoutMs?numberMaximum 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

ParameterTypeDefault valueDescription
resumeCurrent?booleantrueWhether 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

ParameterTypeDescription
propertystringThe 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

ParameterType
propertystring

Returns

void

Autocapture

PostHog.autocapture

autocapture(eventType, elements, properties?, options?): void

Parameters

ParameterType
eventTypestring
elementsPostHogAutocaptureElement[]
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

ParameterType
optionsPostHogMaskViewProps

Returns

Element

Example

JSX
import { PostHogMaskView } from 'posthog-react-native'
function SensitiveForm() {
return (
<PostHogMaskView>
<TextInput placeholder="Credit card number" />
<TextInput placeholder="CVV" />
</PostHogMaskView>
)
}

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

ParameterType
propsPostHogSurveyProviderProps

Returns

Element

Questions

Questions(options): Element

Parameters

ParameterType
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.appearanceSurveyAppearanceTheme
options.client?PostHog
options.initialProgress?SurveyProgress
options.onProgressChange?(progress, completed) => boolean
options.onResponsesChange?(responses) => void
options.onSubmit() => void
options.styleOverrides?StyleProp<ViewStyle>
options.surveySurvey
options.surveyLanguage?string | null

Returns

Element

SurveyModal

SurveyModal(props): Element | null

Parameters

ParameterType
propsSurveyModalProps

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/<flag> 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

ParameterTypeDescription
flagstringThe feature flag key
flagVariant?stringThe variant the user interacted with. Defaults to the flag's current value.

Returns

void

Example

JavaScript
<Button onPress={() => posthog.captureFeatureInteraction('new-checkout')} title="Checkout" />

PostHog.captureFeatureView

captureFeatureView(flag, flagVariant?): void

Captures a $feature_view event when the user sees the feature behind a feature flag.

The event carries feature_flag and, for multivariate flags, feature_flag_variant, and sets the person property $feature_view/<flag> 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

ParameterTypeDescription
flagstringThe feature flag key
flagVariant?stringThe variant the user saw. Defaults to the flag's current value.

Returns

void

Example

JavaScript
posthog.captureFeatureView('new-checkout')

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, such as local notifications. 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

ParameterType
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.getSurveyDisplayLanguageOverride

getSurveyDisplayLanguageOverride(): string | null

Returns

string | null

PostHog.on

on(event, cb): () => void

Listens for an SDK event and returns a function that removes the listener. The SDK does not throw for failures in background work, so listen for them on the 'error' event.

Parameters

ParameterType
eventstring
cb(...args) => void

Returns

() => void

Example

JavaScript
posthog.on('error', (err) => {
console.error('PostHog had an error', err)
})

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

ParameterType
deviceTokenstring
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()/getFeatureFlagResult() 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

ParameterTypeDescription
flagsRecord<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

JavaScript
// replace all stored flags with locally evaluated ones
posthog.updateFlags({ 'my-flag': true, 'multivariate-flag': 'variant-1' })
JavaScript
// include payloads
posthog.updateFlags({ 'my-flag': true }, { 'my-flag': { color: 'blue' } })
JavaScript
// merge into the stored flags instead of replacing them
posthog.updateFlags({ 'my-flag': false }, undefined, { merge: true })

Types

ActionStepStringMatching

ActionStepStringMatching = typeof ActionStepStringMatching[keyof typeof ActionStepStringMatching]

Sync with plugin-server/src/types.ts

ActionStepType

ActionStepType = object

Properties

PropertyTypeDescription
event?string-
href?string-
href_matching?ActionStepStringMatchingDefault ActionStepStringMatching.Exact
selector?string-
text?string-
text_matching?ActionStepStringMatchingDefault StringMatching.Exact
url?string-
url_matching?ActionStepStringMatchingDefault StringMatching.Contains

AutocaptureOptions

PropertyTypeDescription
androidNdkCrashes?booleanEnables 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.
console?boolean | LogLevel[]-
nativeCrashes?booleanEnables 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.
uncaughtExceptions?boolean-
unhandledRejections?boolean-

BasicSurveyQuestion

BasicSurveyQuestion = SurveyQuestionBase & object

Type Declaration

NameType
typetypeof 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

ParameterType
eventCaptureEvent

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

ParameterType
recordCaptureLogOptions

Returns

CaptureLogOptions | null

Example

Redact secrets from log bodies

TypeScript
logs: { beforeSend: (record) => ({ ...record, body: record.body.replace(/token=\S+/g, 'token=[REDACTED]') }) }

CaptureDroppedEvent

A single event the server explicitly rejected (drop).

Properties

PropertyType
details?string
uuidstring

CaptureEndpoint

CaptureEndpoint = typeof ANALYTICS_CAPTURE_ENDPOINT | typeof AI_CAPTURE_ENDPOINT

CaptureErrorParams

PropertyTypeDescription
cause?unknownThe underlying transport/HTTP/parse failure, when the whole batch failed.
dropsCaptureDroppedEvent[]Events the server rejected outright (billing/validation).
endpointCaptureEndpointThe capture lane the batch was sent to.
requestIdstring-
retryExhaustedstring[]UUIDs of events still pending retry after the attempt budget was exhausted, or lost to a batch-level failure.

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

PropertyTypeDescription
$set?PostHogEventPropertiesProperties to set on the person (overrides existing values)
$set_once?PostHogEventPropertiesProperties to set on the person only once (does not override existing values)
eventstringThe name of the event
options?objectSettings that tell PostHog how to process the event, sent apart from its properties.
properties?PostHogEventPropertiesProperties associated with the event (optional to allow compatibility with Node SDK's EventMessage)
timestamp?DateTimestamp for the event
uuid?stringUUID for the event (optional to allow compatibility with Node SDK's EventMessage). Must be a valid UUID.

CaptureLogger

CaptureLogger = Logger

CaptureLogOptions

PropertyTypeDescription
attributes?LogAttributesPer-log attributes (request-specific context like order_id, duration_ms)
bodystringThe log message body (required)
level?LogSeverityLevelLog severity level (default: 'info')
span_id?stringSpan ID for correlation — 16 hex chars
trace_flags?numberW3C trace flags (default: 0)
trace_id?stringTrace ID for correlation — 32 hex chars

Compression

Enumeration MemberValue
Base64"base64"
GZipJS"gzip-js"

EndBranching

EndBranching = object

Properties

PropertyType
typetypeof SurveyQuestionBranchingType.End

ErrorTrackingOptions

PropertyType
autocapture?boolean | AutocaptureOptions
exceptionSteps?ExceptionStepsOptions

EventHint

  • CoercingContext

Properties

PropertyType
mechanism?Partial<Mechanism>
skipFirstLines?number
syntheticException?Error | null

EventOptions

EventOptions = object

Settings that tell PostHog how to process one event, sent with the event apart from its properties. Keys and values are sent as given, including keys this type doesn't list. An option wins over its legacy $process_person_profile, $cookieless_mode, $ignore_sent_at or $product_tour_id property.

Indexable

[key: string]: JsonType | undefined

Properties

PropertyTypeDescription
cookieless_mode?booleanWhether PostHog processes this event in cookieless mode.
disable_skew_correction?booleanWhether PostHog skips correcting this event's timestamp for client clock skew.
process_person_profile?booleanWhether PostHog creates or updates a person profile for this event.
product_tour_id?stringThe product tour this event belongs to.

ExceptionStepsOptions

Controls the breadcrumb-style exception steps recorded via addExceptionStep and attached to captured exceptions as $exception_steps.

Properties

PropertyTypeDescription
enabled?booleanWhether exception steps are recorded and attached. Default true
maxBytes?numberTotal UTF-8 byte budget (~32KB) for the in-memory buffer. Oldest steps are evicted first when exceeded. Default 32768

FeatureFlagResult

FeatureFlagResult = object

Result of evaluating a feature flag, including both the flag value and its payload.

Properties

PropertyModifierTypeDescription
enabledreadonlybooleanWhether the returned feature flag evaluation is enabled. false is a conclusive off result.
keyreadonlystring-
payload?readonlyJsonType-
variant?readonlystring-

FeatureFlagValue

FeatureFlagValue = string | boolean

JsonType

JsonType = string | number | boolean | null | {[key: string]: JsonType; } | JsonType[] | JsonType[]

LinkSurveyQuestion

LinkSurveyQuestion = SurveyQuestionBase & object

Type Declaration

NameType
link?string | null
typetypeof 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

TypeScript
posthog.logger.info('checkout completed', { order_id: 'ord_789' })
posthog.logger.error('payment failed', { code: 'E001' })

Methods

debug()

debug(body, attributes?): void

Debug-level detail. Verbose, only useful while diagnosing.

Parameters
ParameterType
bodystring
attributes?LogAttributes
Returns

void

error()

error(body, attributes?): void

Error. Operation failed; the app may continue.

Parameters
ParameterType
bodystring
attributes?LogAttributes
Returns

void

fatal()

fatal(body, attributes?): void

Fatal. Operation failed; the app likely cannot continue.

Parameters
ParameterType
bodystring
attributes?LogAttributes
Returns

void

info()

info(body, attributes?): void

Informational. Normal app events worth recording.

Parameters
ParameterType
bodystring
attributes?LogAttributes
Returns

void

trace()

trace(body, attributes?): void

Lowest severity. Trace-level diagnostic detail.

Parameters
ParameterType
bodystring
attributes?LogAttributes
Returns

void

warn()

warn(body, attributes?): void

Warning. Something unexpected but non-fatal.

Parameters
ParameterType
bodystring
attributes?LogAttributes
Returns

void

LogLevel

LogLevel = "debug" | "log" | "info" | "warn" | "error"

LogSeverityLevel

LogSeverityLevel = "trace" | "debug" | "info" | "warn" | "error" | "fatal"

Log capture types

Mechanism

PropertyType
exception_id?number
handled?boolean
parent_id?number
source?string
synthetic?boolean
type?string

MultipleSurveyQuestion

MultipleSurveyQuestion = SurveyQuestionBase & object

Type Declaration

NameType
choicesstring[]
hasOpenChoice?boolean
shuffleOptions?boolean
skipSubmitButton?boolean
typetypeof SurveyQuestionType.SingleChoice | typeof SurveyQuestionType.MultipleChoice

NextQuestionBranching

NextQuestionBranching = object

Properties

PropertyType
typetypeof SurveyQuestionBranchingType.NextQuestion

PostHogAutocaptureElement

PostHogAutocaptureElement = object & PostHogEventProperties

Type Declaration

NameType
$el_text?string
href?string
nth_child?number
nth_of_type?number
order?number
tag_namestring

PostHogAutocaptureNavigationTrackerOptions

PostHogAutocaptureNavigationTrackerOptions = object

Properties

PropertyType
routeToName?(name, params) => string
routeToProperties?(name, params) => Record<string, any>

PostHogAutocaptureOptions

PostHogAutocaptureOptions = object

Properties

PropertyTypeDescription
captureScreens?booleanCapture the screen name (or route name) and properties Only used for expo-router, @react-navigation/native and react-native-navigation For react-native-navigation, call initReactNativeNavigation before using this option. For @react-navigation/native v6 and below, wrap PostHogProvider within NavigationContainer. For @react-navigation/native v7 and above, because of a library change, you'll need to capture screens manually and disable this option. You can use the onStateChange callback from NavigationContainer to capture screens with PostHog.screen. You can use the usePostHog() hook or your own PostHog instance to capture screens. Since captureScreens is disabled, the navigation mutation object is ignored. See: https://reactnavigation.org/docs/screen-tracking/ For expo-router, expo-router uses @react-navigation/native, but does not expose NavigationContainer, so capture screens manually and disable this option. expo-router always has access to a URL, so you can pass the URL to PostHog.screen. You can use the usePostHog() hook or your own PostHog instance to capture screens. Since captureScreens is disabled, the navigation mutation object is ignored. See: https://docs.expo.dev/router/reference/screen-tracking/ Default true
captureTouches?booleanEnable 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?stringCustom prop name used to label elements for autocapture Default 'ph-label'
ignoreLabels?string[]List of element labels to ignore during autocapture Default []
maxElementsCaptured?numberMaximum number of elements to capture in the component tree hierarchy Default 20
navigation?PostHogAutocaptureNavigationTrackerOptionsUsed for mutating the screen name and properties Only used if captureScreens is true Default Default to the route name and params
noCaptureProp?stringProp 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 = PostHogCaptureOptionsWithEventOptions & object

Options for a call that sends an event, such as capture(), identify() or alias().

Type Declaration

NameTypeDescription
options?EventOptionsSettings that tell PostHog how to process the event. before_send can change them through the event's options.

PostHogCaptureOptions

PostHogCaptureOptions = object

Properties

PropertyTypeDescription
_originatedFromCaptureException?booleanInternal flag set by captureException() to indicate this $exception event originated from the proper exception capture path. Used to warn users who call capture('$exception') directly.
disableGeoip?boolean-
timestamp?DateIf provided, overrides the auto-generated timestamp. UTC is preferred; non-UTC input is converted to UTC.
uuid?stringIf provided overrides the auto-generated event UUID. Must be a valid UUID.

PostHogCoreOptions

PostHogCoreOptions = object

Properties

PropertyTypeDescription
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. Hostnames match exactly, so pass hostnames only, without a protocol or path. 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?objectOption 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?booleanIf set to false the SDK will not track until the optIn function is called. Default true
disable_capture_url_hashes?booleanWhether 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?booleanWhether to disable GZIP compression Default false
disabled?booleanIf set to true the SDK is essentially disabled (useful for local environments where you don't want to track anything) Default false
disableGeoip?booleanWhether to disable GeoIP lookups Default false
disableRemoteConfig?booleanWhether 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?booleanAdvanced: 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?booleanWhether 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?numberHow many times feature flag requests retry after a transient network error. Set to 0 to disable feature flag request retries. Default 1
featureFlagsRequestTimeoutMs?numberTimeout in milliseconds for feature flag calls Default 10000 for stateful clients, 3000 for stateless
fetchRetryCount?numberHow many times we will retry HTTP requests Default 3
fetchRetryDelay?numberThe delay between HTTP request retries in milliseconds Default 3000
flushAt?numberThe number of events to queue before sending to PostHog (flushing) Default 20
flushInterval?numberThe interval in milliseconds between periodic flushes Default 10000
historicalMigration?booleanSpecial flag to indicate ingested data is for a historical migration Default false
host?stringPostHog API host, usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com' Default 'https://us.i.posthog.com'
maxBatchSize?numberThe maximum number of queued messages to be flushed as part of a single batch (must be higher than flushAt) Default 100
maxQueueSize?numberThe maximum number of cached messages either in memory or on the local storage (must be higher than flushAt) When the queue is full, the SDK drops the oldest event first. 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?booleanWhether to load feature flags when initialized or not Default true
remoteConfigRequestTimeoutMs?numberTimeout in milliseconds for remote config calls Default 3000
requestTimeout?numberTimeout in milliseconds for any calls Default 10000
sendFeatureFlagEvent?booleanWhether 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?numberFor Session Analysis how long before we expire a session in seconds Default 1800

PostHogCustomAppProperties

PropertyTypeDescription
$app_build?string | nullBuild number like "1.2.2" or "122"
$app_name?string | nullName of the app as displayed below the icon like "PostHog"
$app_namespace?string | nullNamespace of the app usually like "com.posthog.app"
$app_version?string | nullHuman friendly app version like what a user would see in the app store like "1.2.2"
$device_manufacturer?string | nullManufacturer like "Apple", "Samsung" or "Android"
$device_model?string | nullModel identifier like "iPhone13,2" or "SM-S921B"
$device_name?string | nullReadable model name like "iPhone 12" or "Samsung Galaxy S24"
$device_type?string | nullDevice type ("Mobile" | "Desktop")
$is_emulator?boolean | nullWhether the app is running on an emulator/simulator
$locale?string | nullLocale (language) of the device like "en-US"
$os_name?string | nullOperating system name like iOS or Android
$os_version?string | nullOperating system version "14.0"
$react_native_version?string | nullReact Native version like "0.79.6". Not set by default: the SDK sends it only on Application Installed and Application Updated
$timezone?string | nullTimezone of the device like "Europe/Berlin"

PostHogCustomStorage

PropertyTypeDescription
getItem(key) => string | Promise<string | null> | null-
removeItem?(key) => void | Promise<void>Deletes an entry. Used to delete the storage entries 4.x shared between project tokens once 5.0 no longer needs them. Without it, those entries are set to an empty value instead.
setItem(key, value) => void | Promise<void>-

PostHogErrorBoundaryFallbackProps

PostHogErrorBoundaryFallbackProps = object

Properties

PropertyType
componentStackstring
errorunknown
resetError() => void

PostHogErrorBoundaryProps

PostHogErrorBoundaryProps = object

Properties

PropertyType
additionalProperties?Properties | ((error) => Properties)
children?React.ReactNode | (() => React.ReactNode)
fallback?React.ReactNode | FunctionComponent<PostHogErrorBoundaryFallbackProps>

PostHogErrorBoundaryState

PostHogErrorBoundaryState = object

Properties

PropertyType
componentStackstring | null
errorunknown
hasErrorboolean

PostHogEventProperties

PostHogEventProperties = object

Index Signature

[key: string]: JsonType

PostHogFeatureFlagOptions

PostHogFeatureFlagOptions = object

Per-call settings for reading a feature flag.

Properties

PropertyTypeDescription
sendFeatureFlagEvent?booleanWhether this read sends a $feature_flag_called event. Defaults to the sendFeatureFlagEvent client option.

PostHogFeatureFlagsLoaded

PostHogFeatureFlagsLoaded = object

The feature flags passed to an onFeatureFlags callback. Disabled flags are left out.

Properties

PropertyTypeDescription
errorsLoadingbooleantrue if the latest attempt to load feature flags failed. flags and variants then hold the last known values, which can be empty. A quota-limited response is not a failure.
flagsstring[]The keys of the enabled feature flags.
variantsRecord<string, string | boolean>The values of the enabled feature flags: true for a boolean flag, or the variant for a multivariate flag.

PostHogGroupProperties

PostHogGroupProperties = object

Index Signature

[type: string]: string | number

PostHogIsFeatureEnabledOptions

PostHogIsFeatureEnabledOptions = PostHogFeatureFlagOptions & object

Per-call settings for isFeatureEnabled().

Type Declaration

NameTypeDescription
defaultValue?booleanValue to return when the flag has no value, e.g. flags have not loaded yet or no flag with that key exists. Defaults to false.

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

PropertyTypeDescription
beforeSend?BeforeSendLogFn | BeforeSendLogFn[]Pre-send filter. See BeforeSendLogFn for shape and examples. Configure as a single function or a chain.
environment?stringDeployment environment attached as OTLP deployment.environment (e.g. 'production', 'staging', 'dev').
flushIntervalMs?numberHow often the periodic background flush fires (ms). Records also flush eagerly when the buffer fills, on AppState changes (RN), and on shutdown(). Lower values trade battery/bandwidth for fresher data. Default: 10000 (RN) / 3000 (browser).
maxBatchRecordsPerPost?numberMax records per outbound POST. Keeps each request under the server's request body cap. On a 413 response, the SDK halves this value, retries the same records, then ramps back up by 1 per healthy send. A 413 on a single-record batch drops the record (it's larger than the server can accept regardless of batch size). Default: 50 (RN) / 100 (browser).
maxBufferSize?numberNumber of buffered records that triggers an immediate flush. Records also flush on the periodic interval and on shutdown(). The queue can grow past this while an async flush is in flight (e.g. during a synchronous burst); a separate, larger memory backstop evicts the oldest only once the queue exceeds the per-interval rate cap. Default: 100.
rateCap?objectTumbling-window rate cap. Bounds how many records can be captured within a sliding (technically tumbling) time window. Records exceeding the cap are dropped synchronously at captureLog() (they never enter the buffer or consume bandwidth). A single warn line is logged per window when the cap is hit. Defaults are per-SDK; on RN the default is { maxLogs: 500, windowMs: 10000 } (≈50 logs/sec ceiling, tuned for cellular bandwidth). Examples Allow brief bursts up to 1000/min logs: { rateCap: { maxLogs: 1000, windowMs: 60000 } } Disable the cap entirely (unbounded) logs: { rateCap: { maxLogs: undefined } }
rateCap.maxLogs?numberMax records accepted per windowMs window. undefined = unbounded.
rateCap.windowMs?numberWindow length in ms. Tumbling, not sliding — the counter resets the first time a capture fires after the window expires.
resourceAttributes?Record<string, LogAttributeValue>Extra OTLP resource attributes attached to every record. Spread first; SDK-controlled keys (service.name, telemetry.sdk.*, RN's os.*) are layered on top so users cannot accidentally clobber them. Use the dedicated serviceName / environment / serviceVersion fields to override those keys.
serviceName?stringService name attached to every record as the OTLP service.name resource attribute. Used by the Logs UI for filtering / grouping. Defaults to 'unknown_service' when unset.
serviceVersion?stringService version attached as OTLP service.version. Useful for correlating regressions to specific app releases.

PostHogMaskViewProps

Props for the PostHogMaskView component.

Extends

  • ViewProps

Properties

PropertyTypeDescriptionOverrides
childrenReactNodeThe child components to mask from PostHog captureViewProps.children

PostHogOptions

  • Omit<PostHogCoreOptions, "evaluationEnvironments" | "disableRemoteConfig" | "disable_capture_url_hashes">

Properties

PropertyTypeDescriptionOverridesInherited 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. Hostnames match exactly, so pass hostnames only, without a protocol or path. Requires the SDK to wire up patchFetchForTracingHeaders against this option (currently supported in posthog-react-native).-Omit.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.-Omit.before_send
bootstrap?objectOption to bootstrap the library with given distinctId and feature flags-Omit.bootstrap
bootstrap.distinctId?string---
bootstrap.featureFlagPayloads?Record<string, JsonType>---
bootstrap.featureFlags?Record<string, FeatureFlagValue>---
bootstrap.isIdentifiedId?boolean---
captureAiCompression?"gzip" | "none"How PostHog.captureAi request bodies are compressed, separately from disableCompression. On iOS and Android, 'gzip' needs @posthog/react-native-plugin 3.0 or newer, which gzips natively; without it, bodies are sent uncompressed. Default 'gzip'--
captureAiMaxEventBytes?numberMaximum size, in bytes, of a serialized PostHog.captureAi event. A larger event is sent without $ai_input, $ai_output, $ai_output_choices, $ai_input_state, $ai_output_state and $ai_tools, with $ai_content_removal_reason: 'event_too_large' and $ai_event_bytes_before_removal set, so its model, token and cost data still arrive. The SDK drops an event still over the limit, or with none of those properties, and captureAi() returns undefined. Use it to lower the limit: PostHog drops AI events whose properties are over 8 MiB, so a larger value, or a value of 0 or less, uses the default. Default 8454144 (8 MiB plus 64 KiB for the rest of the event)--
captureAiMaxQueueSize?numberMaximum number of PostHog.captureAi events kept in their queue before the oldest are dropped. AI events can be megabytes, so this is lower than maxQueueSize. The queue also keeps at most 50 MiB of AI events, whatever this is set to. A value of 0 or less uses the default. With the default storage on iOS and Android, unsent AI events are stored as files in the app's cache directory, which isn't backed up, so they are sent on the next launch if the app is killed. The OS may clear that directory when the device is low on space. With persistence: 'memory', customStorage, or where Expo's file system isn't available, unsent AI events are kept only in memory. Default 100--
captureAiRequestTimeoutMs?numberTimeout, in milliseconds, of a PostHog.captureAi request. AI requests can carry several MB, so this is longer than requestTimeout. A value of 0 or less uses the default. After a request times out, its events are sent again in batches half the size. Default 60000--
captureAppLifecycleEvents?booleanCaptures app lifecycle events such as Application Installed, Application Updated, Application Opened and Application Backgrounded. Application Opened carries from_background: false at launch, true when the app returns from the background. Application Installed and Application Updated events are not supported with persistence set to 'memory'. On by default from 4.39.0. Default true--
capturePushNotificationOpened?booleanWhether 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; 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?booleanWhether 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?PostHogCustomStorageAllows 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?booleanIf set to false the SDK will not track until the optIn function is called. Default true-Omit.defaultOptIn
disableCompression?booleanWhether to disable GZIP compression Default false-Omit.disableCompression
disabled?booleanIf set to true the SDK is essentially disabled (useful for local environments where you don't want to track anything) Default false-Omit.disabled
disableGeoip?booleanWhether to disable GeoIP lookups Default false-Omit.disableGeoip
disableRemoteFeatureFlags?booleanAdvanced: 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-Omit.disableRemoteFeatureFlags
disableSurveys?booleanWhether to load surveys when initialized or not Requires the PostHogSurveyProvider to be used Default false-Omit.disableSurveys
enablePersistSessionIdAcrossRestart?booleanIf 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?booleanEnable 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?ErrorTrackingOptionsError 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-Omit.evaluationContexts
featureFlagsRequestMaxRetries?numberHow many times feature flag requests retry after a transient network error. Set to 0 to disable feature flag request retries. Default 1-Omit.featureFlagsRequestMaxRetries
featureFlagsRequestTimeoutMs?numberTimeout in milliseconds for feature flag calls Default 10000 for stateful clients, 3000 for stateless-Omit.featureFlagsRequestTimeoutMs
fetchRetryCount?numberHow many times we will retry HTTP requests Default 3-Omit.fetchRetryCount
fetchRetryDelay?numberThe delay between HTTP request retries in milliseconds Default 3000-Omit.fetchRetryDelay
flushAt?numberThe number of events to queue before sending to PostHog (flushing) Default 20-Omit.flushAt
flushInterval?numberThe interval in milliseconds between periodic flushes Default 30000Omit.flushInterval-
historicalMigration?booleanSpecial flag to indicate ingested data is for a historical migration Default false-Omit.historicalMigration
host?stringPostHog API host, usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com' Default 'https://us.i.posthog.com'-Omit.host
logs?PostHogLogsConfigLogs 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?numberThe maximum number of queued messages to be flushed as part of a single batch (must be higher than flushAt) Default 50Omit.maxBatchSize-
maxQueueSize?numberThe maximum number of cached messages either in memory or on the local storage (must be higher than flushAt) When the queue is full, the SDK drops the oldest event first. Default 1000-Omit.maxQueueSize
overrideDisplayLanguage?string | nullOverrides 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. Events captured offline stay in the queue. A flush that fails with a network error keeps them and retries later. With 'file', the queue is stored on the device and survives an app restart. 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', })-Omit.personProfiles
preloadFeatureFlags?booleanWhether to load feature flags when initialized or not Default true-Omit.preloadFeatureFlags
pushIdentityProvider?PostHogPushIdentityProviderMints 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?PostHogRageClickConfigConfigure 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.--
remoteConfigRequestTimeoutMs?numberTimeout in milliseconds for remote config calls Default 3000-Omit.remoteConfigRequestTimeoutMs
requestHeaders?objectHeaders sent with requests to the PostHog API. On capture requests, headers the SDK sets itself, such as Authorization and User-Agent, replace yours.--
requestTimeout?numberTimeout in milliseconds for any calls Default 10000-Omit.requestTimeout
sendFeatureFlagEvent?booleanWhether 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-Omit.sendFeatureFlagEvent
sessionExpirationTimeSeconds?numberFor Session Analysis how long before we expire a session in seconds Default 1800-Omit.sessionExpirationTimeSeconds
sessionReplayConfig?PostHogSessionReplayConfigConfiguration for Session Replay--
setDefaultPersonProperties?booleanAutomatically 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

Enumeration MemberValue
AiCaptureQueue"ai_capture_queue"
AiQueue"ai_queue"
AnonymousId"anonymous_id"
BootstrapFeatureFlagDetails"bootstrap_feature_flag_details"
BootstrapFeatureFlagPayloads"bootstrap_feature_flag_payloads"
BootstrapFeatureFlags"bootstrap_feature_flags"
DeviceId"device_id"
DistinctId"distinct_id"
EnablePersonProcessing"enable_person_processing"
FeatureFlagDetails"feature_flag_details"
FeatureFlagPayloads"feature_flag_payloads"
FeatureFlags"feature_flags"
FlagsEndpointWasHit"flags_endpoint_was_hit"
GroupProperties"group_properties"
InstalledAppBuild"installed_app_build"
InstalledAppVersion"installed_app_version"
LogsQueue"logs_queue"
OptedOut"opted_out"
OverrideFeatureFlags"override_feature_flags"
PersonMode"person_mode"
PersonProperties"person_properties"
Props"props"
PushRegistered"push_registered"
Queue"queue"
RemoteConfig"remote_config"
SessionId"session_id"
SessionLastTimestamp"session_timestamp"
SessionReplay"session_replay"
SessionReplayEventTriggerActivatedSession"session_replay_event_trigger_activated_session"
SessionReplayTriggerGroupsActivation"session_replay_trigger_groups_activation"
SessionStartTimestamp"session_start_timestamp"
SurveyLastSeenDate"survey_last_seen_date"
Surveys"surveys"
SurveysInProgress"surveys_in_progress"
SurveysSeen"surveys_seen"

PostHogProviderProps

Props for the PostHogProvider component.

Properties

PropertyTypeDescription
autocapture?boolean | PostHogAutocaptureOptionsAutocapture 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.
childrenReactNodeThe child components to render within the PostHog context
client?PostHogAn existing PostHog client instance
debug?booleanEnable debug mode for additional logging Default false
options?PostHogOptionsPostHog configuration options
projectToken?stringYour 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

ParameterType
distinctIdstring
appIdstring

Returns

Promise<string | null>

PostHogRageClickConfig

PostHogRageClickConfig = object

Properties

PropertyTypeDescription
enabled?booleanEnable or disable rage click (rage tap) detection. When enabled the native SDK emits a $rageclick event whenever a user taps the same area repeatedly in quick succession. Default true
minimumTapCount?numberNumber of consecutive taps required to trigger a rage click. Default 3
thresholdPoints?numberMaximum pixel distance between consecutive taps for them to still count toward a rage click. Default 30
timeoutInterval?numberMaximum time in seconds allowed between consecutive taps. Default 1.0

PostHogRemoteConfig

PostHogRemoteConfig = object

Properties

PropertyTypeDescription
capturePerformance?boolean | {[key: string]: JsonType; }Capture performance remote config. Either a boolean (false = disabled) or a map with configuration. When a map, network_timing (boolean) controls whether network timing capture is enabled remotely.
errorTracking?boolean | {[key: string]: JsonType; }Error tracking remote config. Either a boolean (false = disabled) or a map with configuration. When a map, autocaptureExceptions (boolean) controls whether automatic exception capture is enabled remotely.
hasFeatureFlags?booleanIndicates if the team has any flags enabled (if not we don't need to load them)
logs?boolean | {[key: string]: JsonType; }Logs feature remote config. When a map, captureConsoleLogs (boolean) is the local opt-in flag for console.* autocapture (read by the JS SDK's PostHogLogs extension to decide whether to load the autocapture bundle).
sessionRecording?boolean | {[key: string]: JsonType; }-
supportedCompression?Compression[]Supported compression algorithms
surveys?boolean | Survey[]Whether surveys are enabled

PostHogSessionReplayConfig

PostHogSessionReplayConfig = object

Properties

PropertyTypeDescription
captureLog?booleanEnable capturing of logs as console events Default true
captureNetworkTelemetry?booleanEnable capturing network telemetry iOS only Default true
captureTouches?booleanCapture touch coordinates in session replay. Set to false to keep screenshots without recording taps that could reveal sensitive input on a known keypad layout. Does not change masking or PostHogProvider touch autocapture. Android and iOS only. Requires @posthog/react-native-plugin. Set before constructing PostHog. Changes after initialization do not update native state. Default true
iOSCaptureMethod?"standard" | "gpu"How iOS captures each replay screenshot. - 'standard': draws the window on the main thread. - 'gpu': experimental. Copies the window's layers and renders the copy on the GPU, in short main-thread steps. Content from another process, such as a web view's page, and Metal content are not captured. A custom CALayer subclass that is animating, such as a playing Lottie animation, is left out of the frame. Recording keeps roughly 25 to 30 MB more memory resident on average. Falls back to 'standard' when a capture can't be made this way. iOS only. Requires @posthog/react-native-plugin. Default 'standard'
maskAllImages?booleanEnable masking of all images to a placeholder. The project setting can also turn this on. It never turns it off. Older @posthog/react-native-plugin versions and posthog-react-native-session-replay ignore the project setting. Default true
maskAllSandboxedViews?booleanEnable masking of all sandboxed system views These may include UIImagePickerController, PHPickerViewController and CNContactPickerViewController iOS only Default true
maskAllTextInputs?booleanEnable masking of all text and text input fields. The project setting can also turn this on. It never turns it off. Older @posthog/react-native-plugin versions and posthog-react-native-session-replay ignore the project setting. Default true
sampleRate?numberSession replay sample rate between 0 and 1 Local config has precedence over remote config when both are set. If undefined, sampling is controlled by remote config (when available).
screenshotColorMode?"ARGB_8888" | "RGB_565"Experimental Experimental. Screenshot bitmap pixel format. ARGB_8888 preserves transparency and color precision. RGB_565 uses half the bitmap memory but reduces color precision and removes alpha, making transparent window regions appear black. Unsupported devices fall back to ARGB_8888. Android only. Requires @posthog/react-native-plugin. Default 'ARGB_8888'
screenshotCompressionQuality?numberExperimental Experimental. WebP compression quality, clamped to 0–100. Fractional values are truncated. Higher values generally retain more detail and produce larger payloads. Compression is lossy, except at quality 100 on Android 10, which uses lossless WebP. Non-finite values use the native default. Does not change screenshot resolution. Android only. Requires @posthog/react-native-plugin. Default 30
screenshotScale?numberExperimental Experimental. Multiplier for the physical width and height of screenshots, clamped to 0.1–1.0. For example, 0.5 captures half the width and height, or one quarter of the pixels. The logical replay viewport is unchanged. Non-finite values use the native default. Android only. Requires @posthog/react-native-plugin. Does not enable session replay or change compression quality or color mode. Default undefined, which uses the native default of one pixel per dp.
throttleDelayMs?numberThrottling delay used to reduce the number of snapshots captured and reduce performance impact This is used for capturing the view as a wireframe or screenshot The lower the number more snapshots will be captured but higher the performance impact Default 1000
verifyScreenshotMaskAlignment?booleanVerify that masks remain aligned while capturing session replay screenshots. Android only. Requires @posthog/react-native-plugin. Enabling this can preserve screenshots during pixel-only redraws, including continuously animated content, but performs additional view hierarchy walks while a screenshot is captured. Default false

PostHogSurveyProviderProps

PostHogSurveyProviderProps = object

Properties

PropertyTypeDescription
androidKeyboardBehavior?"padding" | "height"The keyboard avoiding behavior for the survey modal (KeyboardAvoidingView), applied only to Android devices. - 'padding': Adds padding to avoid keyboard (recommended) - 'height': Resizes the view height (default, for legacy - may cause flickering on some Android devices) Default 'height'
autoPresentSurveys?booleanWhether eligible popover surveys are automatically presented. (Default: true) Set to false to defer presentation — e.g. while a native-stack formSheet/modal is on top. Deferral is display-only: the survey stays armed and presents once this is true again. A survey already on screen is not interrupted when this becomes false. You own flipping this back to true (e.g. wire it to route/screen focus). While it stays false the survey remains deferred and never shows — if the un-defer never happens (sheet dismissed without re-focusing the provider, an unmount, an error boundary), the survey stays armed indefinitely and no "survey shown" event fires.
childrenReact.ReactNode-
client?PostHog-
defaultSurveyAppearance?SurveyAppearanceThe default appearance for surveys when not specified in PostHog. Accepts the React Native-only appearance fields as well (e.g. maxFontSizeMultiplier) — they are merged into the same theme object the survey components read, and PostHog never sends them down.
overrideAppearanceWithDefault?booleanIf true, PosHog appearance will be ignored and defaultSurveyAppearance is always used.

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

NameType
displaySurveyRatingDisplay
lowerBoundLabelstring
scale2 | 3 | 5 | 7 | 10
skipSubmitButton?boolean
typetypeof SurveyQuestionType.Rating
upperBoundLabelstring

ResponseBasedBranching

ResponseBasedBranching = object

Properties

PropertyType
responseValuesRecord<string, any>
typetypeof SurveyQuestionBranchingType.ResponseBased

SpecificQuestionBranching

SpecificQuestionBranching = object

Properties

PropertyType
indexnumber
typetypeof SurveyQuestionBranchingType.SpecificQuestion

Survey

Survey = object

Properties

PropertyType
appearance?SurveyAppearance
conditions?object
conditions.actions?object
conditions.actions.valuesSurveyActionType[]
conditions.deviceTypes?string[]
conditions.deviceTypesMatchType?SurveyMatchType
conditions.events?object
conditions.events.repeatedActivation?boolean
conditions.events.values?SurveyEventWithFilters[]
conditions.linkedFlagVariant?string
conditions.seenSurveyWaitPeriodInDays?number
conditions.selector?string
conditions.url?string
conditions.urlMatchType?SurveyMatchType
current_iteration?number | null
current_iteration_start_date?string | null
description?string
enable_partial_responses?boolean | null
end_date?string
feature_flag_keys?object[]
idstring
internal_targeting_flag_key?string
linked_flag_key?string
namestring
questionsSurveyQuestion[]
schedule?SurveySchedule | null
start_date?string
targeting_flag_key?string
translations?Record<string, SurveyTranslation>
typeSurveyType

SurveyActionType

SurveyActionType = object

Properties

PropertyType
idnumber
name?string
steps?ActionStepType[]

SurveyAppearance

React Native survey appearance, including native-only text scaling options.

Extends

  • SurveyAppearance

Properties

PropertyTypeDescriptionOverridesInherited from
allowGoBack?boolean--SurveyAppearance.allowGoBack
autoDisappear?boolean--SurveyAppearance.autoDisappear
backButtonText?string--SurveyAppearance.backButtonText
backgroundColor?string--SurveyAppearance.backgroundColor
borderColor?string--SurveyAppearance.borderColor
displayIntroScreen?boolean--SurveyAppearance.displayIntroScreen
displayThankYouMessage?boolean--SurveyAppearance.displayThankYouMessage
fontFamily?stringFont family for survey text. Use a font bundled with the app; other names fall back to the system font. On Android the survey editor's web fonts (Georgia, Courier New, ...) use the matching system font. inherit (the editor's default) or an empty value uses defaultSurveyAppearance.fontFamily, then the system font. system-ui uses the system font.SurveyAppearance.fontFamily-
inputBackground?string--SurveyAppearance.inputBackground
inputTextColor?string--SurveyAppearance.inputTextColor
introScreenButtonText?string--SurveyAppearance.introScreenButtonText
introScreenDescription?string--SurveyAppearance.introScreenDescription
introScreenDescriptionContentType?SurveyQuestionDescriptionContentType--SurveyAppearance.introScreenDescriptionContentType
introScreenHeader?string--SurveyAppearance.introScreenHeader
maxFontSizeMultiplier?number | Partial<Record<SurveyTextRole, number>>Caps how far survey text may grow under the OS text-size setting, as a multiple of its base size - React Native's maxFontSizeMultiplier, applied to every semantic Text and TextInput the survey renders. Icon-only text fallbacks do not scale because they occupy fixed-size icon boxes. Pass a number to cap every role at once, or an object to cap them separately: a survey headline can usually take more scaling than a numeral inside a rating button, and a host app that already caps its own text by role will want to match those ceilings here. maxFontSizeMultiplier: 1.6 // or maxFontSizeMultiplier: { question: 1.5, description: 1.8, ratingNumber: 1.2 } Roles left out of the object are uncapped, as they are today. Use 0 for no maximum, or a value of 1 or greater to set a cap. Other values below 1 (such as 0.8) do not shrink text and are unsupported by React Native; depending on the platform and version, they may be ignored or rejected. Leave it unset (the default) and survey text scales without a ceiling. That is what the OS asks for, but not always what a fixed-size survey card can hold - at the largest accessibility sizes an unbounded 18pt headline renders roughly one word per line. React Native only inherits this prop through nested Text, so a host app cannot apply it from the outside - it has to come in here. Default undefined (no ceiling)--
placeholder?string--SurveyAppearance.placeholder
position?SurveyPosition--SurveyAppearance.position
ratingButtonActiveColor?string--SurveyAppearance.ratingButtonActiveColor
ratingButtonColor?string--SurveyAppearance.ratingButtonColor
shuffleQuestions?boolean--SurveyAppearance.shuffleQuestions
submitButtonColor?string--SurveyAppearance.submitButtonColor
submitButtonText?string--SurveyAppearance.submitButtonText
submitButtonTextColor?string--SurveyAppearance.submitButtonTextColor
surveyPopupDelaySeconds?number--SurveyAppearance.surveyPopupDelaySeconds
textColor?string--SurveyAppearance.textColor
thankYouMessageCloseButtonText?string--SurveyAppearance.thankYouMessageCloseButtonText
thankYouMessageDescription?string--SurveyAppearance.thankYouMessageDescription
thankYouMessageDescriptionContentType?SurveyQuestionDescriptionContentType--SurveyAppearance.thankYouMessageDescriptionContentType
thankYouMessageHeader?string--SurveyAppearance.thankYouMessageHeader
widgetColor?string--SurveyAppearance.widgetColor
widgetLabel?string--SurveyAppearance.widgetLabel
widgetSelector?string--SurveyAppearance.widgetSelector
widgetType?SurveyWidgetType--SurveyAppearance.widgetType

SurveyAppearance

SurveyAppearance = object

Extended by

  • SurveyAppearance

Properties

PropertyType
allowGoBack?boolean
autoDisappear?boolean
backButtonText?string
backgroundColor?string
borderColor?string
displayIntroScreen?boolean
displayThankYouMessage?boolean
fontFamily?string
inputBackground?string
inputTextColor?string
introScreenButtonText?string
introScreenDescription?string
introScreenDescriptionContentType?SurveyQuestionDescriptionContentType
introScreenHeader?string
placeholder?string
position?SurveyPosition
ratingButtonActiveColor?string
ratingButtonColor?string
shuffleQuestions?boolean
submitButtonColor?string
submitButtonText?string
submitButtonTextColor?string
surveyPopupDelaySeconds?number
textColor?string
thankYouMessageCloseButtonText?string
thankYouMessageDescription?string
thankYouMessageDescriptionContentType?SurveyQuestionDescriptionContentType
thankYouMessageHeader?string
widgetColor?string
widgetLabel?string
widgetSelector?string
widgetType?SurveyWidgetType

SurveyAppearanceTheme

SurveyAppearanceTheme = Omit<Required<SurveyAppearance>, "widgetSelector" | "widgetType" | "widgetColor" | "widgetLabel" | "shuffleQuestions" | "textColor" | "inputTextColor" | "placeholder" | "maxFontSizeMultiplier" | "fontFamily"> & object

Type Declaration

NameType
fontFamily?string
inputTextColor?string
maxFontSizeMultiplier?SurveyAppearance["maxFontSizeMultiplier"]
placeholder?string
textColor?string

SurveyEventWithFilters

PropertyType
namestring
propertyFilters?PropertyFilters

SurveyMatchType

SurveyMatchType = typeof SurveyMatchType[keyof typeof SurveyMatchType]

SurveyModalProps

SurveyModalProps = object

Properties

PropertyType
androidKeyboardBehavior?"padding" | "height"
appearanceSurveyAppearanceTheme
client?PostHog
initialProgress?SurveyProgress
onClose(submitted, responses) => void
onProgressChange?(progress, completed) => boolean
onShow() => void
surveySurvey
surveyLanguagestring | null

SurveyPosition

SurveyPosition = typeof SurveyPosition[keyof typeof SurveyPosition]

SurveyProgress

SurveyProgress = object

Properties

PropertyType
questionIndexnumber
questionOrdernumber[]
questionSnapshotsRecord<string, string>
responsesSurveyResponses
submissionIdstring
surveyLanguage?string | null

SurveyQuestion

SurveyQuestion = BasicSurveyQuestion | LinkSurveyQuestion | RatingSurveyQuestion | MultipleSurveyQuestion

SurveyQuestionBase

SurveyQuestionBase = object

Properties

PropertyType
branching?NextQuestionBranching | EndBranching | ResponseBasedBranching | SpecificQuestionBranching
buttonText?string
description?string | null
descriptionContentType?SurveyQuestionDescriptionContentType
idstring
optional?boolean
originalQuestionIndexnumber
questionstring
translations?Record<string, SurveyQuestionTranslation>
validation?SurveyValidationRule[]

SurveyQuestionDescriptionContentType

SurveyQuestionDescriptionContentType = typeof SurveyQuestionDescriptionContentType[keyof typeof SurveyQuestionDescriptionContentType]

SurveyQuestionTranslation

PropertyType
buttonText?string
choices?string[]
description?string | null
link?string | null
lowerBoundLabel?string
question?string
upperBoundLabel?string

SurveyRatingDisplay

SurveyRatingDisplay = typeof SurveyRatingDisplay[keyof typeof SurveyRatingDisplay]

SurveyResponses

SurveyResponses = Record<string, SurveyResponseValue>

SurveyResponseValue

SurveyResponseValue = string | number | string[] | null

SurveySchedule

SurveySchedule = typeof SurveySchedule[keyof typeof SurveySchedule]

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

PropertyType
backButtonText?string
introScreenButtonText?string
introScreenDescription?string
introScreenHeader?string
name?string
submitButtonText?string
thankYouMessageCloseButtonText?string
thankYouMessageDescription?string
thankYouMessageHeader?string

SurveyType

SurveyType = typeof SurveyType[keyof typeof SurveyType]

SurveyValidationRule

PropertyType
errorMessage?string
typeSurveyValidationType
value?number

SurveyValidationType

SurveyValidationType = typeof SurveyValidationType[keyof typeof SurveyValidationType]

SurveyWidgetType

SurveyWidgetType = typeof SurveyWidgetType[keyof typeof SurveyWidgetType]

Was this page useful?