AGENTIC MEMORY

Skills

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

← Back to Skills

instrument-product-analytics

Add PostHog product analytics events to track user behavior. Use after implementing new features or reviewing PRs to ensure meaningful user actions are captured. Also handles initial PostHog SDK setup if not yet installed.

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--instrument-product-analytics 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 · 62

references/react-native.md · 48000

ore updateFlags() runs.

Experiments (A/B tests)

Since experiments use feature flags, the code for running an experiment is very similar to the feature flags code. See adding experiment code for React Native examples.

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.). See Group Analytics for implementation details.

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

Error tracking

To set up error tracking in your project, see the error tracking docs.

Native crash autocapture

JavaScript autocapture only covers exceptions thrown in your JS/TS code. To capture crashes in native code – a native module, the React Native runtime, or a C/C++ library – install the optional @posthog/react-native-plugin package and enable one or both of these options. What each option covers depends on the platform:

| Option | iOS | Android | | --- | --- | --- | | nativeCrashes | Every native crash: uncaught Objective-C exceptions, Mach exceptions, and signals such as SIGSEGV and SIGABRT, including crashes in C/C++ code | Java/Kotlin crashes only | | androidNdkCrashes | Ignored | C/C++ (NDK) crashes, on Android 12 (API 31) or later. Requires posthog-react-native 4.78.0 and @posthog/react-native-plugin 2.12.0 or later |

To capture every native crash on both platforms, enable both:

const posthog = new PostHog('<ph_project_token>', {
  host: 'https://us.i.posthog.com',
  errorTracking: {
    autocapture: {
      nativeCrashes: true,
      androidNdkCrashes: true,
    },
  },
})

Native capture is gated by your project's Enable exception autocapture setting, and crash reports need native debug symbols uploaded at build time to produce readable stack traces.

An Android NDK crash kills the process immediately, so PostHog captures it on the next app launch from the records the OS kept. Properties such as $app_version and the identity describe that launch, not the crash. The first launch after you enable androidNdkCrashes also captures NDK crashes the OS still holds from before.

Follow the React Native installation guide for the full setup, and native crash symbolication to upload symbols.

Error boundaries

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

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

Logs

To set up logs in your React Native app, follow the React Native logs installation guide. The SDK exposes posthog.captureLog, posthog.logger.{trace,debug,info,warn,error,fatal}, and posthog.flushLogs for sending structured records to PostHog Logs.

Minimum version: [email protected] or later.

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.

Push notifications

The React Native SDK can register a device for Workflows push notifications and capture when a user opens one. For setup, including automatic and manual registration, capturing opens, opting out, and identity verification, see Push notifications.

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.

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

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

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.

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

// 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 is enabled by default since version 4.39.0 (previously named `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`