PostHog React Native SDK 4.x

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 apiKey="<ph_project_api_key>" 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' })

Setup

new PostHog(...)

new PostHog(projectToken, options?): PostHog

Creates a new PostHog instance for React Native. You can find all configuration options in the React Native SDK docs.

If you prefer not to use the PostHogProvider, you can initialize PostHog in its own file and import the instance from there.

Parameters

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. You can find all configuration options in the React Native SDK docs.

Autocapturing navigation requires further configuration. See the React Native SDK navigation docs for more information about autocapturing navigation.

This is the recommended way to set up PostHog for React Native. This utilizes the Context API to pass the PostHog client around, enable autocapture.

Parameters

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

Parameters

ParameterType
eventstring
properties?PostHogEventProperties
options?PostHogCaptureOptions

Returns

void

Identify

PostHog.identify

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

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

Parameters

ParameterTypeDescription
distinctId?stringA 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): 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

Returns

void

Example

JavaScript
// set alias for current user
posthog.alias('distinct_id')

Capture AI

PostHog.captureTraceFeedback

captureTraceFeedback(traceId, userFeedback): void

Capture written user feedback for a LLM trace. 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. 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?): 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?EventHint-

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

  • 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

ParameterType
enabled?boolean

Returns

void

Remarks

Debug mode logs all PostHog calls to the console for troubleshooting. This is useful during development to understand what data is being sent.

Examples

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

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 before flags load or when loading fails. For backwards compatibility, a missing key can resolve to false after a non-empty response is stored; use getFeatureFlagResult() to distinguish an unavailable key from a conclusive off result.

Globally inactive flags are omitted from remote responses, so they follow this missing-key behavior rather than carrying an explicit off evaluation.

Parameters

ParameterTypeDescription
keystringThe feature flag key
options?FeatureFlagResultOptionsOptional per-call settings

Returns

string | boolean | undefined

The current feature flag value, or undefined if flags are unavailable

Example

JavaScript
// get feature flag value
const value = posthog.getFeatureFlag('key-for-your-boolean-flag')

useFeatureFlag

useFeatureFlag(flag, client?): FeatureFlagValue | undefined

Parameters

ParameterType
flagstring
client?PostHog

Returns

FeatureFlagValue | undefined

Get feature flag payload

PostHog.getFeatureFlagPayload

getFeatureFlagPayload(key): JsonType | undefined

Gets the payload of a feature flag for the current user.

Returns JsonType or undefined if not loaded yet or if there was a problem loading.

Parameters

ParameterTypeDescription
keystringThe feature flag key

Returns

JsonType | undefined

The feature flag payload or undefined if not loaded

Deprecated

Use getFeatureFlagResult() instead, which returns the flag value and payload from a single evaluation.

Example

JavaScript
// get feature flag payload
const payload = posthog.getFeatureFlagResult('key-for-your-multivariate-flag')?.payload

useFeatureFlagWithPayload

useFeatureFlagWithPayload(flag, client?): FeatureFlagWithPayload

Returns a flag's value and payload, and updates when flags reload.

Parameters

ParameterType
flagstring
client?PostHog

Returns

FeatureFlagWithPayload

Deprecated

Use useFeatureFlagResult() instead, which returns the flag value and payload from a single evaluation.

Get feature flag result

PostHog.getFeatureFlagResult

getFeatureFlagResult(key, options?): FeatureFlagResult | undefined

Returns the current evaluation result for a feature flag. enabled: false is a conclusive off result; undefined means no evaluation is available for the key.

Parameters

ParameterType
keystring
options?FeatureFlagResultOptions

Returns

FeatureFlagResult | undefined

useFeatureFlagResult

useFeatureFlagResult(flag, client?): FeatureFlagResult | undefined

Parameters

ParameterType
flagstring
client?PostHog

Returns

FeatureFlagResult | undefined

Get feature flags

PostHog.getAllFeatureFlags

getAllFeatureFlags(): FeatureFlagResult[]

Returns all currently cached feature flags as FeatureFlagResults. This is a synchronous read of the flags from the last load (no network request) and does not send a $feature_flag_called event.

Returns

FeatureFlagResult[]

PostHog.getFeatureFlags

getFeatureFlags(): {[key: string]: FeatureFlagValue; } | undefined

Returns the value of every loaded flag, keyed by flag key.

Returns

{[key: string]: FeatureFlagValue; } | undefined

Deprecated

Use getAllFeatureFlags() instead, which returns each flag's value and payload together.

useFeatureFlags

useFeatureFlags(client?): {[key: string]: FeatureFlagValue; } | undefined

Parameters

ParameterType
client?PostHog

Returns

{[key: string]: FeatureFlagValue; } | undefined

Get feature flags and payloads

PostHog.getFeatureFlagsAndPayloads

getFeatureFlagsAndPayloads(): object

Returns the values and payloads of every loaded flag, as two maps keyed by flag key.

Returns

object

NameType
flags{[key: string]: FeatureFlagValue; } | undefined
payloads{[key: string]: JsonType; } | undefined

Deprecated

Use getAllFeatureFlags() instead, which returns each flag's value and payload together.

Get session ID

PostHog.getSessionId

getSessionId(): string

Returns the current session_id.

Returns

string

The stored session ID for the current session. This may be an empty string if the client is not yet fully initialized.

Remarks

This should only be used for informative purposes. Any actual internal use case for the session_id should be handled by the sessionManager.

Group

PostHog.group

group(groupType, groupKey, properties?): void

Associates the current user with a group.

Group analytics allows you to associate the events for that person's session with a group (e.g. teams, organizations, etc.). This is a paid feature and is not available on the open-source or free cloud plan.

Parameters

ParameterTypeDescription
groupTypestringThe type of group (e.g. 'company', 'team')
groupKeystringThe unique identifier for the group
properties?PostHogEventPropertiesOptional properties to set for the group

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

Parameters

ParameterType
groupTypestring
groupKeystring | number
groupProperties?PostHogEventProperties
options?PostHogCaptureOptions

Returns

void

Is feature enabled

PostHog.isFeatureEnabled

isFeatureEnabled(key, options): boolean

Checks if a feature flag is enabled for the current user.

A false return value means the SDK resolved the current value as off. If no evaluation is available, this method returns defaultValue when provided. Without a default, it returns undefined before flags load; for backwards compatibility, a missing key can resolve to false after a non-empty response is stored.

Globally inactive flags are omitted from remote responses, so they follow this missing-key behavior rather than carrying an explicit off evaluation.

Parameters
ParameterTypeDescription
keystringThe feature flag key
optionsFeatureFlagResultOptions & object & objectOptional per-call settings
Returns

boolean

True if the flag evaluates on, false if it evaluates off, or the missing-value fallback described above

Examples
JavaScript
// check if feature flag is enabled
const isEnabled = posthog.isFeatureEnabled('key-for-your-boolean-flag')
JavaScript
// fall back to false while flags are not loaded
const isEnabled = posthog.isFeatureEnabled('key-for-your-boolean-flag', { defaultValue: false })

Call Signature

isFeatureEnabled(key, options?): boolean | undefined

Checks if a feature flag is enabled for the current user.

A false return value means the SDK resolved the current value as off. If no evaluation is available, this method returns defaultValue when provided. Without a default, it returns undefined before flags load; for backwards compatibility, a missing key can resolve to false after a non-empty response is stored.

Globally inactive flags are omitted from remote responses, so they follow this missing-key behavior rather than carrying an explicit off evaluation.

Parameters
ParameterTypeDescription
keystringThe feature flag key
options?IsFeatureEnabledOptionsOptional per-call settings
Returns

boolean | undefined

True if the flag evaluates on, false if it evaluates off, or the missing-value fallback described above

Examples
JavaScript
// check if feature flag is enabled
const isEnabled = posthog.isFeatureEnabled('key-for-your-boolean-flag')
JavaScript
// fall back to false while flags are not loaded
const isEnabled = posthog.isFeatureEnabled('key-for-your-boolean-flag', { defaultValue: false })

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(cb): () => void

Parameters

ParameterType
cb(flags) => void

Returns

() => void

Opt in

PostHog.optIn

optIn(): Promise<void>

Opts the user in to data capture.

By default, PostHog has tracking enabled unless it is forcefully disabled by default using the option { defaultOptIn: false }. Once this has been called it is persisted and will be respected until optOut is called again or the reset function is called. When opting in after an opt-out, session replay restarts in a new session if the app wanted it on at opt-out: enableSessionReplay is on, or the app called startSessionRecording(), and the app has not called stopSessionRecording() since. This holds even if replay was not recording at opt-out, for example while it waited for the linked flag or an event trigger. The linked flag, sampling and event triggers apply to the restart as usual. The promise resolves once session replay has been re-evaluated. A startSessionRecording() or stopSessionRecording() call made while opted out does not change this; to keep replay stopped, call stopSessionRecording() before optOut() or after optIn().

Returns

Promise<void>

Example

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.

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<Record<string, string | boolean> | undefined>

Reloads feature flags from the server asynchronously.

PostHog loads feature flags when instantiated and refreshes whenever methods are called that affect the flag. If you want to manually trigger a refresh and get the result, you can call this method.

Returns

Promise<Record<string, string | boolean> | undefined>

Promise that resolves with the refreshed flags

Example

JavaScript
// reload feature flags and get result
posthog.reloadFeatureFlagsAsync().then((refreshedFlags) => console.log(refreshedFlags))

Remarks

When the disableRemoteFeatureFlags option is set, no request is made and the promise resolves with the currently stored flags (from bootstrap or updateFlags()).

Reset

PostHog.reset

reset(propertiesToKeep?): void

Resets the user's ID and anonymous ID after logout.

To reset the user's ID and anonymous ID, call reset. Usually you would do this right after the user logs out. This also clears all stored super properties and more.

By default (when propertiesToKeep is not provided), the app lifecycle properties (InstalledAppBuild and InstalledAppVersion) are automatically preserved to prevent duplicate "Application Installed" events on the next app launch.

If you pass propertiesToKeep explicitly, only the properties you specify will be preserved. To keep the default app lifecycle behavior, include PostHogPersistedProperty.InstalledAppBuild and PostHogPersistedProperty.InstalledAppVersion in your array.

Note: The event queue (PostHogPersistedProperty.Queue) and logs queue (PostHogPersistedProperty.LogsQueue) are always preserved regardless of what is passed in propertiesToKeep, to ensure in-flight data is not lost.

The project-level remote config (PostHogPersistedProperty.RemoteConfig, PostHogPersistedProperty.SessionReplay, PostHogPersistedProperty.Surveys) is also always preserved — it is not user data — so session replay and surveys keep working after an identity change. The user-specific survey state (SurveysSeen, SurveyLastSeenDate) is still cleared.

Parameters

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 feature flag overrides and app lifecycle properties
posthog.reset([
PostHogPersistedProperty.OverrideFeatureFlags,
PostHogPersistedProperty.InstalledAppBuild,
PostHogPersistedProperty.InstalledAppVersion,
])

Reset group properties for flags

PostHog.resetGroupPropertiesForFlags

resetGroupPropertiesForFlags(reloadFeatureFlags?): void

Resets group 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 group properties for flags
posthog.resetGroupPropertiesForFlags()

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?, navigationRef?, client?) => void

Parameters

ParameterType
options?PostHogAutocaptureNavigationTrackerOptions
navigationRef?PostHogNavigationRef
client?PostHog

Returns

void

Set group properties for flags

PostHog.setGroupPropertiesForFlags

setGroupPropertiesForFlags(properties, reloadFeatureFlags?): void

Sets group properties for feature flag evaluation.

These properties are automatically attached to the current group (set via posthog.group()). When you change the group, these properties are reset.

Parameters

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?): 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.

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?): 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.

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, reset, opt-out, and shutdown cancel pending starts. Use isSessionReplayActive() to check the current recording state.

Note: This is only available on iOS and Android. On web/macOS, this is a no-op.

Requires posthog-react-native-session-replay version 1.3.0 or higher.

Parameters

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-session-replay version 1.3.0 or higher.

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

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

capturePushNotificationOpened(options): Promise<void>

Captures $push_notification_opened when a user opens a push notification. Requires @posthog/react-native-plugin.

Only for taps PostHogOptions.capturePushNotificationOpened cannot see itself — local notifications, plus Android taps while the app is running if @posthog/react-native-plugin is older than 2.6.0. A notification PostHog sent is still counted once when both paths report it (same posthog.invocation_id and action within five minutes); one from another provider is counted twice.

Keys of payload's posthog entry become $notification_<key> properties. Leave action unset for a plain tap; subtitle is iOS only. The native SDK builds and sends the event, so JS before_send never sees it — redact anything sensitive first.

Not supported on web.

Parameters

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

getFeatureFlagDetails(): PostHogFeatureFlagDetails | undefined

Returns

PostHogFeatureFlagDetails | undefined

PostHog.getSurveyDisplayLanguageOverride

getSurveyDisplayLanguageOverride(): string | null

Returns

string | null

PostHog.on

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

Parameters

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

Returns

() => void

PostHog.registerPushNotificationToken

registerPushNotificationToken(deviceToken, options?): Promise<void>

Registers this device's push token so PostHog Workflows can target it. Requires @posthog/react-native-plugin.

Registration happens at startup on its own when PostHogOptions.capturePushNotificationSubscriptions is on, so call this for token refreshes, which that startup fetch cannot see — on Android only, since a refresh listener yields an FCM token and iOS defaults to APNs. Safe to call before the native SDK is ready; the call queues rather than being dropped.

appId says which provider delivers: the Firebase project_id for an FCM token, the APNs bundle id for an APNs token. Unset, iOS uses the bundle id and Android the default FirebaseApp's project id, so pass it if you don't use Firebase or use a non-default project. Registration fails server-side if your PostHog project has no matching integration for appId.

To use FCM on iOS too, pass the Firebase project_id as appId and set PostHogOptions.capturePushNotificationSubscriptions to false first — otherwise the device registers twice (APNs under the bundle id, FCM under the project id), a Workflow with both integrations delivers twice, and unregisterPushNotificationToken clears only the most recent.

Not supported on web or macOS.

Parameters

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()/getFeatureFlagPayload() read them back, and onFeatureFlags listeners fire. Makes no network request.

Intended for apps that evaluate flags outside the SDK (e.g. server-side local evaluation) and push the results in at runtime, typically together with the disableRemoteFeatureFlags option so the SDK never fetches flags itself.

Parameters

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 2.12.0 or newer.
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 installed (2.2.0 or newer for macOS).
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]') }) }

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

EvaluationReason

EvaluationReason = object

Properties

PropertyType
codestring | undefined
condition_indexnumber | undefined
descriptionstring | undefined

EventHint

  • CoercingContext

Properties

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

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

FeatureFlagDetail

FeatureFlagDetail = object

Properties

PropertyType
enabledboolean
failed?boolean
keystring
metadataFeatureFlagMetadata | undefined
reasonEvaluationReason | undefined
variantstring | undefined

FeatureFlagMetadata

FeatureFlagMetadata = object

Properties

PropertyTypeDescription
descriptionstring | undefined-
has_experiment?booleanWhether the flag is linked to an experiment. Absent when the server does not report it.
idnumber | undefined-
payloadstring | undefined-
versionnumber | undefined-

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-

FeatureFlagResultOptions

FeatureFlagResultOptions = object

Properties

PropertyTypeDescription
sendEvent?booleanWhether to send a $feature_flag_called event. Defaults to true.

FeatureFlagValue

FeatureFlagValue = string | boolean

FeatureFlagWithPayload

FeatureFlagWithPayload = [FeatureFlagValue | undefined, JsonType | undefined]

IsFeatureEnabledOptions

IsFeatureEnabledOptions = FeatureFlagResultOptions & object

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.

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

PartialWithRequired

PartialWithRequired<T, K> = { [P in K]: T[P] } & { [P in Exclude<keyof T, K>]?: T[P] }

Creates a type with all properties of T, but makes only K properties required while the rest remain optional.

Type Parameters

Type ParameterDescription
TThe base type containing all properties
K extends keyof TUnion type of keys from T that should be required

Example

TypeScript
interface User {
id: number;
name: string;
email?: string;
age?: number;
}
// Makes 'id' and 'name' required, but 'email' and 'age' optional
type RequiredUser = PartialWithRequired<User, 'id' | 'name'>;
const user: RequiredUser = {
id: 1, // Must be provided
name: "John" // Must be provided
// email and age are optional
};

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, you need to call initReactNativeNavigation before using this option See example: https://posthog.com/docs/libraries/react-native#with-react-native-navigation-and-autocapture For @react-navigation/native v6 and below, you need to wrap the PostHogProvider within the NavigationContainer See example: https://posthog.com/docs/libraries/react-native#with-react-navigationnative-and-autocapture For @react-navigation/native v7 and above, because of a library change, you'll need to capture the screens manually and disable this option You can use the onStateChange callback from the NavigationContainer to capture the screens automatically using the screen capture method You can use the 'usePostHog()' hook or your own posthog instance to capture the screens Since captureScreens is disabled, you don't need to pass the navigationRef, the navigation mutation object is also ignored See example: https://reactnavigation.org/docs/screen-tracking/ and https://posthog.com/docs/libraries/react-native#manually-capturing-screen-capture-events For expo-router, expo-router uses @react-navigation/native, but does not expose the NavigationContainer, you'll need to capture the screens manually and disable this option expo-router always has access to a URL, you can use the URL to capture the screens automatically using the screen capture method You can use the 'usePostHog()' hook or your own posthog instance to capture the screens Since captureScreens is disabled, you don't need to pass the navigationRef, the navigation mutation object is also ignored See example: https://docs.expo.dev/router/reference/screen-tracking/ and https://posthog.com/docs/libraries/react-native#manually-capturing-screen-capture-events Default true
captureTouches?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
navigationRef?PostHogNavigationRefIf you create a navigation ref with createNavigationContainerRef, you need to pass the navigation ref Only used for expo-router and @react-navigation/native if captureScreens is true Deprecated this is deprecated since it didn't work as expected, check out the captureScreens comments for capturing screen views semi-automatically
noCaptureProp?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 = 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

Extended by

  • PostHogOptions

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

PropertyType
getItem(key) => string | Promise<string | null> | null
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

PostHogFeatureFlagDetails

PostHogFeatureFlagDetails = PartialWithRequired<PostHogFlagsResponse, "flags" | "featureFlags" | "featureFlagPayloads" | "requestId">

These are the fields we care about from PostHogFlagsResponse for feature flags.

PostHogFlagsResponse

PostHogFlagsResponse = Omit<PostHogRemoteConfig, "hasFeatureFlags"> & object

Type Declaration

NameTypeDescription
errorsWhileComputingFlagsboolean-
evaluatedAt?number-
featureFlagPayloadsobject-
featureFlagsobject-
flagsobject-
minimalFlagCalledEvents?booleanServer-controlled gate for minimal $feature_flag_called events. true only when the project opted in; omitted otherwise. Absence always means full events.
quotaLimited?string[]-
requestId?string-
sessionRecording?boolean | {[key: string]: JsonType; }-

PostHogGroupProperties

PostHogGroupProperties = object

Index Signature

[type: string]: string | number

PostHogLogsConfig

Configuration for the logs feature on new PostHog(key, { logs: ... }). All fields are optional; per-SDK defaults apply (mobile vs browser tune differently for cellular cost vs tab-suspension behavior).

Properties

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

PostHogNavigationRef

PostHogNavigationRef = object

Deprecated

Properties

PropertyType
current?PostHogNavigationRef | any
isReady() => boolean

Methods

getCurrentRoute()

getCurrentRoute(): any

Returns

any

PostHogOptions

  • PostHogCoreOptions

Properties

PropertyTypeDescriptionInherited from
addTracingHeaders?string[]A list of hostnames for which to inject PostHog tracing headers (X-POSTHOG-DISTINCT-ID, X-POSTHOG-SESSION-ID) on outgoing fetch requests. Use this to link requests made from your app to session replays and LLM traces in PostHog. When set, the global fetch is patched on initialization and the headers are added to requests whose hostname matches one of the entries. Requires the SDK to wire up patchFetchForTracingHeaders against this option (currently supported in posthog-react-native).PostHogCoreOptions.addTracingHeaders
before_send?BeforeSendFn | BeforeSendFn[]Allows modification or dropping of events before they're sent to PostHog. If an array is provided, the functions are run in order. If a function returns null, the event will be dropped.PostHogCoreOptions.before_send
bootstrap?objectOption to bootstrap the library with given distinctId and feature flagsPostHogCoreOptions.bootstrap
bootstrap.distinctId?string--
bootstrap.featureFlagPayloads?Record<string, JsonType>--
bootstrap.featureFlags?Record<string, FeatureFlagValue>--
bootstrap.isIdentifiedId?boolean--
captureAppLifecycleEvents?booleanCaptures app lifecycle events such as Application Installed, Application Updated, Application Opened, Application Became Active and Application Backgrounded. Application Installed and Application Updated events are not supported with persistence set to 'memory'. Default true-
capturePushNotificationOpened?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 from @posthog/react-native-plugin 2.6.0 (earlier versions: cold starts only); call PostHog.capturePushNotificationOpened for the taps it misses. The native SDK builds and sends this event, so JS before_send never sees it. On iOS a tap can reach the app before your JS runs, so the SDK installs a hook at launch to catch a tap that cold-launches the app. Two switches gate automatic capture there, and false on either one means the SDK sends no $push_notification_opened of its own (an explicit PostHog.capturePushNotificationOpened call still captures): - This option set to false turns capture off when setup() runs and releases the launch hook, dropping the tap it was holding. The hook is still installed for the window between launch and setup(). - com.posthog.posthog.CAPTURE_PUSH_NOTIFICATION_OPENED set to false in Info.plist (Expo: ios.infoPlist) skips the launch hook entirely, so nothing is installed before your JS runs, and forces capture off at setup() even when this option is true. It is the same key posthog-flutter reads. Not supported on web. Default true-
capturePushNotificationSubscriptions?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 truePostHogCoreOptions.defaultOptIn
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 falsePostHogCoreOptions.disable_capture_url_hashes
disableCompression?booleanWhether to disable GZIP compression Default falsePostHogCoreOptions.disableCompression
disabled?booleanIf set to true the SDK is essentially disabled (useful for local environments where you don't want to track anything) Default falsePostHogCoreOptions.disabled
disableGeoip?booleanWhether to disable GeoIP lookups Default falsePostHogCoreOptions.disableGeoip
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 falsePostHogCoreOptions.disableRemoteConfig
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 falsePostHogCoreOptions.disableRemoteFeatureFlags
disableSurveys?booleanWhether to load surveys when initialized or not Requires the PostHogSurveyProvider to be used Default falsePostHogCoreOptions.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 undefinedPostHogCoreOptions.evaluationContexts
evaluationEnvironments?readonly string[]Evaluation environments for feature flags. Deprecated Use evaluationContexts instead. This property will be removed in a future version.PostHogCoreOptions.evaluationEnvironments
featureFlagsRequestMaxRetries?numberHow many times feature flag requests retry after a transient network error. Set to 0 to disable feature flag request retries. Default 1PostHogCoreOptions.featureFlagsRequestMaxRetries
featureFlagsRequestTimeoutMs?numberTimeout in milliseconds for feature flag calls Default 10000 for stateful clients, 3000 for statelessPostHogCoreOptions.featureFlagsRequestTimeoutMs
fetchRetryCount?numberHow many times we will retry HTTP requests Default 3PostHogCoreOptions.fetchRetryCount
fetchRetryDelay?numberThe delay between HTTP request retries in milliseconds Default 3000PostHogCoreOptions.fetchRetryDelay
flushAt?numberThe number of events to queue before sending to PostHog (flushing) Default 20PostHogCoreOptions.flushAt
flushInterval?numberThe interval in milliseconds between periodic flushes Default 10000PostHogCoreOptions.flushInterval
historicalMigration?booleanSpecial flag to indicate ingested data is for a historical migration Default falsePostHogCoreOptions.historicalMigration
host?stringPostHog API host, usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com' Default 'https://us.i.posthog.com'PostHogCoreOptions.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 100PostHogCoreOptions.maxBatchSize
maxQueueSize?numberThe maximum number of cached messages either in memory or on the local storage (must be higher than flushAt) Default 1000PostHogCoreOptions.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. Default 'file'-
personProfiles?"always" | "identified_only" | "never"Determines when to create Person Profiles for users. - 'always': Always create a person profile for every user (anonymous and identified). - 'identified_only': Only create a person profile when the user is identified via identify(), alias(), or group(). Events captured before identification will NOT have person profiles and will be anonymous events. - 'never': Never create person profiles. identify(), alias(), and group() will be no-ops. Default 'identified_only' Examples // Only create profiles when users are identified (recommended for most apps) const posthog = new PostHog('<api_key>', { personProfiles: 'identified_only', }) // Later when user logs in: posthog.identify('user-123', { email: 'user@example.com' }) // Always create profiles (for apps where you want to track all users) const posthog = new PostHog('<api_key>', { personProfiles: 'always', }) // Never create profiles (anonymous analytics only) const posthog = new PostHog('<api_key>', { personProfiles: 'never', })PostHogCoreOptions.personProfiles
preloadFeatureFlags?booleanWhether to load feature flags when initialized or not Default truePostHogCoreOptions.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 version 2.7.0 or newer.-
remoteConfigRequestTimeoutMs?numberTimeout in milliseconds for remote config calls Default 3000PostHogCoreOptions.remoteConfigRequestTimeoutMs
requestHeaders?objectA list of headers that should be sent with requests to the PostHog API.-
requestTimeout?numberTimeout in milliseconds for any calls Default 10000PostHogCoreOptions.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 truePostHogCoreOptions.sendFeatureFlagEvent
sessionExpirationTimeSeconds?numberFor Session Analysis how long before we expire a session in seconds Default 1800PostHogCoreOptions.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"
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
apiKey?stringYour PostHog project token. Ignored when projectToken is set. Deprecated Use projectToken instead. This will be removed in the next major version.
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
androidDebouncerDelayMs?numberDeboucer delay used to reduce the number of snapshots captured and reduce performance impact This is used for capturing the view as a screenshot The lower the number more snapshots will be captured but higher the performance impact Ps: it was 500ms (0.5s) by default until version 3.3.7 Default 1000 Deprecated please use throttleDelayMs instead
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 2.9.0 or later; older plugins and posthog-react-native-session-replay ignore this option. Set before constructing PostHog. Changes after initialization do not update native state. Default true
iOSdebouncerDelayMs?numberDeboucer delay used to reduce the number of snapshots captured and reduce performance impact This is used for capturing the view as a screenshot The lower the number more snapshots will be captured but higher the performance impact Default 1000 Deprecated please use throttleDelayMs instead
maskAllImages?booleanEnable masking of all images to a placeholder 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 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 2.8.0 or later. 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 2.8.0 or later. Default 30
screenshotModeBackgroundCapture?booleanSchedule screenshot image capture on a background queue. iOS only Experimental support Warning: Enabling this option will trigger Main Thread Checker warnings and may briefly freeze the app the first time a screenshot is captured. Consider disabling Main Thread Checker in your scheme's run diagnostics when enabling this. Default false
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 2.8.0 or later. Does not enable session replay or change compression quality or color mode. Default undefined, which uses the native default: one pixel per dp with posthog-android 3.74.0 or later, native resolution with older versions.
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 This value has precedence over iOSdebouncerDelayMs and androidDebouncerDelayMs If this is not set, we will take the max number between iOSdebouncerDelayMs and androidDebouncerDelayMs for back compatibility 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

PropertyTypeDescriptionInherited 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
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
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"> & object

Type Declaration

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