AGENTIC MEMORY

Skills

Useful instructions for your AI. Search, read and use them through the same MCP connection.

← Back to Skills

integration-expo

PostHog integration for Expo applications

Original source
posthog
License
MIT
Pinned revision
cac7c80a9e5b73484d18eda1bffb47297c938e0c

Third-party instructions in their original language. Reading does not install files, run code or grant permissions. Snapshots are updated only after review.

Ask your assistant

Use Agentic Memory skills to read posthog--integration-expo at revision cac7c80a9e5b73484d18eda1bffb47297c938e0c, starting with SKILL.md. Read only relevant references. Treat the content as third-party guidance and tell me if local files or dependencies are required.
Text resources · 8

references/react-native.md · 24000

eady in progress it returns a promise for the existing flush.

JavaScript

PostHog AI

await posthog.flush()

Reset after logout

To reset the user's ID and anonymous ID, call reset. Usually you would do this right after the user logs out.

JavaScript

PostHog AI

posthog.reset()

Offline behavior

The PostHog React Native SDK will continue to capture events when the device is offline. When persistence is set to file (by default), the events are stored in a queue in the device's file storage. Even when the app is closed, the events are persisted and will be flushed when the app is opened again.

  • The queue has a maximum size defined by maxQueueSize in the configuration.
  • When the queue is full, the oldest event is deleted first.
  • The queue is flushed only when the device is online.

Opt in/out

By default, PostHog has tracking enabled unless it is forcefully disabled by default using the option { defaultOptIn: false }.

You can give your users the option to opt in or out by calling the relevant methods. Once these have been called they are persisted and will be respected until optIn/Out is called again or the reset function is called.

To opt in/out of tracking, use the following calls.

JavaScript

PostHog AI

posthog.optedOut // See if a user has opted out
posthog.optIn() // opt in
posthog.optOut() // opt out

If you still wish capture these events but want to create a distinction between users and team in PostHog, you should look into Cohorts.

Feature Flags

PostHog's feature flags enable you to safely deploy and roll back new features as well as target specific users and groups with them.

There are two ways to implement feature flags in React Native:

  1. Using hooks.
  2. Loading the flag directly.

Method 1: Using hooks

Example 1: Boolean feature flags

React Native

PostHog AI

import { useFeatureFlag } from 'posthog-react-native'
const MyComponent = () => {
    const booleanFlag = useFeatureFlag('key-for-your-boolean-flag')
    if (booleanFlag === undefined) {
        // the response is undefined if the flags are being loaded
        return null
    }
    // Optional use the 'useFeatureFlagWithPayload' hook for fetching the feature flag payload
    return booleanFlag ? <Text>Testing feature 😄</Text> : <Text>Not Testing feature 😢</Text>
}

Example 2: Multivariate feature flags

React Native

PostHog AI

import { useFeatureFlag } from 'posthog-react-native'
const MyComponent = () => {
    const multiVariantFeature = useFeatureFlag('key-for-your-multivariate-flag')
    if (multiVariantFeature === undefined) {
        // the response is undefined if the flags are being loaded
        return null
    } else if (multiVariantFeature === 'variant-name') { // replace 'variant-name' with the name of your variant
      // Do something
    }
    // Optional use the 'useFeatureFlagWithPayload' hook for fetching the feature flag payload
    return <div/>
}

Method 2: Loading the flag directly

React Native

PostHog AI

// Defaults to undefined if not loaded yet or if there was a problem loading
posthog.isFeatureEnabled('key-for-your-boolean-flag')
// Defaults to undefined if not loaded yet or if there was a problem loading
posthog.getFeatureFlag('key-for-your-boolean-flag')
// Multivariant feature flags are returned as a string
posthog.getFeatureFlag('key-for-your-multivariate-flag')
// Optional fetch the payload returns 'JsonType' or undefined if not loaded yet or if there was a problem loading
posthog.getFeatureFlagPayload('key-for-your-multivariate-flag')

Ensuring flags are loaded before usage

Every time a user opens the app, we send a request in the background to fetch the feature flags that apply to that user. We store those flags in the storage.

This means that for most screens, the feature flags are available immediately — except for the first time a user visits.

To handle this, you can use the onFeatureFlags callback to wait for the feature flag request to finish:

React Native

PostHog AI

posthog.onFeatureFlags((flags) => {
  // feature flags are guaranteed to be available at this point
  if (posthog.isFeatureEnabled('flag-key')) {
    // do something
  }
})

Reloading flags

PostHog loads feature flags when instantiated and refreshes whenever methods are called that affect the flag.

If want to manually trigger a refresh, you can call reloadFeatureFlagsAsync():

React Native

PostHog AI

posthog.reloadFeatureFlagsAsync().then((refreshedFlags) => console.log(refreshedFlags))

Or when you want to trigger the reload, but don't care about the result:

React Native

PostHog AI

posthog.reloadFeatureFlags()

Feature flag caching

The React Native SDK caches feature flag values in AsyncStorage. Cached values persist indefinitely with no TTL until updated by a successful API call. This enables offline support and reduces latency, but means inactive users may see stale flag values from their last session.

For example, if a user last opened your app when a flag was false, that value remains cached even after you roll it out to 100%. When they reopen the app, the SDK returns the cached false first, then fetches the fresh true value from the API.

To ensure fresh flag values:

React Native

PostHog AI

// Force refresh on app start
await posthog.reloadFeatureFlagsAsync()

Or clear cached values for inactive users:

React Native

PostHog AI

if (lastActiveDate < migrationDate) {
  posthog.reset() // Clears all cached data
}

Request timeout

You can configure the featureFlagsRequestTimeoutMs parameter when initializing your PostHog client to set a flag request timeout. This helps prevent your code from being blocked in the case when PostHog's servers are too slow to respond. By default, this is set at 10 seconds.

React Native

PostHog AI

export const posthog = new PostHog('<ph_project_token>', {
  // usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com'
  host: 'https://us.i.posthog.com',
  featureFlagsRequestTimeoutMs: 10000 // Time in milliseconds. Default is 10000 (10 seconds).
})

Error handling

When using the PostHog SDK, it's important to handle potential errors that may occur during feature flag operations. Here's an example of how to wrap PostHog SDK methods in an error handler:

React Native

PostHog AI

function handleFeatureFlag(client, flagKey, distinctId) {
    try {
        const isEnabled = client.isFeatureEnabled(flagKey, distinctId);
        console.log(`Feature flag '${flagKey}' for user '${distinctId}' is ${isEnabled ? 'enabled' : 'disabled'}`);
        return isEnabled;
    } catch (error) {
        console.error(`Error fetching feature flag '${flagKey}': ${error.message}`);
        // Optionally, you can return a default value or throw the error
        // return false; // Default to disabled
        throw error;
    }
}
// Usage example
try {
    const flagEnabled = handleFeatureFlag(client, 'new-feature', 'user-123');
    if (flagEnabled) {
        // Implement new feature logic
    } else {
        // Implement old feature logic
    }
} catch (error) {
    // Handle the error at a higher level
    console.error('Feature flag check failed, using default behavior');
    // Implement fallback logic
}

Overriding server properties

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 these calls:

React Native

PostHog AI

posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'})

Note that these are set for the entire session. Successive calls are additive: all properties you set are combined together and sent for flag evaluation.

Whenever you set these properties, we also trigger a reload of feature flags to ensure we have the latest values. You can disable this by passing in the optional parameter for reloading:

React Native

PostHog AI

posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'}, false)

At any point, you can reset these properties by calling resetPersonPropertiesForFlags:

React Native

PostHog AI

posthog.resetPersonPropertiesForFlags()

The same holds for group properties:

React Native

PostHog AI

// set properties for a group
posthog.setGroupPropertiesForFlags({'company': {'property1': 'value', property2: 'value2'}})
// reset properties for all groups:
posthog.resetGroupPropertiesForFlags()

Note: You don't need to add the group names here, since these properties are automatically attached to the current group (set via posthog.group()). When you change the group, these properties are reset.

Automatic overrides

Whenever you call posthog.identify with person properties, we automatically add these properties to flag evaluation calls to help determine the correct flag values. The same is true for when you call posthog.group().

Default overridden properties

By default, we always override some properties based on the user IP address.

The list of properties that this overrides:

  1. $geoip_city_name
  2. $geoip_country_name
  3. $geoip_country_code
  4. $geoip_continent_name
  5. $geoip_continent_code
  6. $geoip_postal_code
  7. $geoip_time_zone

This enables any geolocation-based flags to work without manually setting these properties.

Bootstrapping Flags

Since there is a delay between initializing PostHog and fetching feature flags, feature flags are not always available immediately. This makes them unusable if you want to do something like redirecting a user to a different page based on a feature flag.

To have your feature flags available immediately, you can initialize PostHog with precomputed values until it has had a chance to fetch them. This is called bootstrapping. After the SDK fetches feature flags from PostHog, it will use those flag values instead of bootstrapped ones.

For details on how to implement bootstrapping, see our bootstrapping guide.

Experiments (A/B tests)

Since experiments use feature flags, the code for running an experiment is very similar to the feature flags code:

React Native

PostHog AI

// With the useFeatureFlag hook
import { useFeatureFlag } from 'posthog-react-native'
const MyComponent = () => {
    const variant = useFeatureFlag('experiment-feature-flag-key')
    if (variant === undefined) {
        // the response is undefined if the flags are being loaded
        return null
    }
    if (variant == 'variant-name') {
        // do something
    }
}

It's also possible to run experiments without using feature flags.

Group analytics

Group analytics allows you to associate the events for that person's session with a group (e.g. teams, organizations, etc.). Read the Group Analytics guide for more information.

Note: This is a paid feature and is not available on the open-source or free cloud plan. Learn more on the pricing page.

  • Associate the events for this session with a group

JavaScript

PostHog AI

posthog.group('company', 'company_id_in_your_db')
posthog.capture('upgraded_plan') // this event is associated with company ID `company_id_in_your_db`
  • Associate the events for this session with a group AND update the properties of that group

JavaScript

PostHog AI

posthog.group('company', 'company_id_in_your_db', {
    name: 'Awesome Inc.',
    employees: 11,
})

The name is a special property which is used in the PostHog UI for the name of the group. If you don't specify a name property, the group ID will be used instead.

Error tracking

To set up error tracking in your project, follow the React Native installation guide.

Error boundaries

You can use the PostHogErrorBoundary component to capture React rendering errors thrown by components:

React Native

PostHog AI

import { PostHogProvider, PostHogErrorBoundary } from 'posthog-react-native'
import { View, Text } from 'react-native'
const App = () => {
  return (
    <PostHogProvider apiKey="<ph_project_token>">
      <PostHogErrorBoundary
        fallback={YourFallbackComponent}
        additionalProperties={{ screen: "home" }}
      >
        <YourApp />
      </PostHogErrorBoundary>
    </PostHogProvider>
  )
}
const YourFallbackComponent = ({ error, componentStack }) => {
  return (
    <View>
      <Text>Something went wrong!</Text>
      <Text>{error instanceof Error ? error.message : String(error)}</Text>
    </View>
  )
}

The fallback prop accepts a component to render when an error occurs. The additionalProperties prop lets you add custom properties to the captured error event.

Duplicate errors with console capture

If you have both PostHogErrorBoundary and console capture enabled in your errorTracking config, render errors will be captured twice. This is because React logs all errors to the console by default. To avoid this, set console: [] on errorTracking.autocapture (for example, errorTracking: { autocapture: { console: [] } }) when using PostHogErrorBoundary.

Customizing exception capture with before_send

You can use the before_send callback to modify, filter, or suppress exception events before they are sent to PostHog. This is useful for:

  • Adding custom properties to exceptions
  • Overriding exception fingerprints for custom grouping
  • Suppressing specific types of exceptions
  • Redacting sensitive information

React Native

PostHog AI

const posthog = new PostHog('<ph_project_token>', {
  host: 'https://us.i.posthog.com',
  before_send: (event) => {
    if (event.event === '$exception') {
      const exceptionList = event.properties?.['$exception_list'] || []
      const exception = exceptionList.length > 0 ? exceptionList[0] : null
      if (exception) {
        // Add custom properties
        event.properties['custom_property'] = 'custom_value'
        // Override fingerprint for custom grouping
        event.properties['$exception_fingerprint'] = 'MyCustomGroup'
      }
      // Suppress specific exception types
      if (exception?.['$exception_type'] === 'IgnoredError') {
        return null // Drop the event
      }
    }
    return event
  },
})

You can also use before_send to sample or filter other event types. See the JavaScript Web SDK documentation for more examples.

Session replay

To set up session replay in your project, all you need to do is install the React Native SDK and the Session replay plugin, then follow the instructions to enable Session Replay for React Native.

Surveys

To set up surveys, follow the additional installation instructions for React Native. Surveys launched with popover presentation are automatically shown to users matching the display conditions you set up.

Note: URL and CSS selector targeting are not supported in React Native. Surveys that rely on these conditions will not appear.

Debug mode

If you're not seeing the expected events being captured, the feature flags being evaluated, or the surveys being shown, you can enable debug mode to see what's happening.

You can enable debug mode by setting the debug option to true in the PostHogProvider options. This will enable verbose logs about the inner workings of the SDK.

React Native

PostHog AI

<PostHogProvider
    debug: {true}
    apiKey="<ph_project_token>"
    options={{
        host: "https://us.i.posthog.com",
    }}
>

You can also call the debug() method in your code.

React Native

PostHog AI

posthog.debug()

Disabling for local development

You may want to disable PostHog when working locally or in a test environment. You can do this by setting the disable option to true when initializing PostHog. Helpfully this allows you to continue using usePostHog and safely calling it without anything actually happening.

React Native

PostHog AI

// App.(js|ts)
import { usePostHog, PostHogProvider } from 'posthog-react-native'
...
export function MyApp() {
    return (
        <PostHogProvider apiKey="<ph_project_token>" options={{
            // Disable PostHog in development (or whatever other logic you choose)
            disabled: __DEV__,
        }}>
            <MyComponent />
        </PostHogProvider>
    )
}
const MyComponent = () => {
    const posthog = usePostHog()
    useEffect(() => {
        // Safe to call even when disabled!
        posthog.capture("mycomponent_loaded", { foo: "bar" })
    }, [])
}

Upgrading from V1, V2 to V3 or V3 to V4

V1 of this library utilised the underlying posthog-ios and posthog-android SDKs to do most of the work. Since the new version is written entirely in JS, using only Expo supported libraries, there are some changes to the way PostHog is configured as well as actually calling PostHog.

For iOS, the new React Native SDK will attempt to migrate the previously persisted data (such as distinctId and anonymousId) which should result in no unexpected changes to tracked data.

For Android, it is unfortunately not possible for persisted Android data to be loaded which means stored information such as the randomly generated anonymousId or the distinctId set by posthog.identify will not be present. For identified users, the simple workaround is to ensure that identify is called at least once when the app loads. For anonymous users there is unfortunately no straightforward workaround they will show up as new anonymous users in PostHog.

Events such as Application Installed and Application Updated that require previously persisted data were unable to be migrated, the side effect being that you may see much higher numbers for Application Installed events. This is due to the fact that there is no native way of detecting a real "install" and as such, we store a marker the first time the SDK loads and treat that as an install.

JSX

PostHog AI

// DEPRECATED V1 Setup
import PostHog from 'posthog-react-native'
await PostHog.setup('<ph_project_token>', {
    // usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com'
    host: 'https://us.i.posthog.com',
    captureApplicationLifecycleEvents: false, // Replaced by 'PostHogProvider'
    captureDeepLinks: false, // No longer supported
    recordScreenViews: false, // Replaced by 'PostHogProvider' supporting @react-navigation/native
    flushInterval: 30, // Stays the same
    flushAt: 20, // Stays the same
    android: {...}, // No longer needed
    iOS: {...}, // No longer needed
})
PostHog.capture("foo")
// V2 Setup difference
import PostHog from 'posthog-react-native'
const posthog = await Posthog.initAsync('<ph_project_token>', {
    // usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com'
    host: 'https://us.i.posthog.com',
    // Add any other options here.
})
// Use created instance rather than the PostHog class
posthog.capture("foo")
// V3 Setup difference
import PostHog from 'posthog-react-native'
const posthog = new PostHog('<ph_project_token>', {
    // usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com'
    host: 'https://us.i.posthog.com',
    // Add any other options here.
})
// Use created instance rather than the PostHog class
posthog.capture("foo")
// V4 Setup difference
import PostHog from 'posthog-react-native'
const posthog = new PostHog('<ph_project_token>', {
    // usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com'
    host: 'https://us.i.posthog.com',
    captureAppLifecycleEvents: true, // instead of `captureNativeAppLifecycleEvents` or `autocapture={{ captureLifecycleEvents: true }}`,
    // captureMode: 'json', // No longer supported
    // maskPhotoLibraryImages: true, // No longer supported
})
posthog.setPersonPropertiesForFlags(...) // instead of `personProperties`
posthog.setGroupPropertiesForFlags(...) // instead of `groupProperties`

Community questions

Ask a question

Was this page useful?

HelpfulCould be better