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

lements based on the React component displayName or name. If you prefer, you can set your own name using the ph-label prop:

<View ph-label="my-special-label"></View>

Autocapture configuration

<PostHogProvider apiKey="<ph_project_token>" autocapture={{
    captureTouches: true, // Disabled by default
    captureScreens: true, // Enabled by default
    ignoreLabels: [], // Any labels here will be ignored from the stack in touch events
    customLabelProp: "ph-label",
    maxElementsCaptured: 20,
    noCaptureProp: "ph-no-capture",
    propsToCapture: ["testID"], // Limit which props are captured. By default, identifiers and text content are captured.

    navigation: {
        // By default, only the screen name is tracked but it is possible to track the
        // params or modify the name by intercepting the autocapture like so
        routeToName: (name, params) => {
            if (params.id) return `${name}/${params.id}`
            return name
        },
        routeToProperties: (name, params) => {
            if (name === "SensitiveScreen") return undefined
            return params
        },
    },
}}>
    ...
</PostHogProvider>

Preventing sensitive data capture

If there are elements you don't want to be captured, you can add the ph-no-capture property. If this property is found anywhere in the view hierarchy, the entire touch event is ignored:

<View ph-no-capture>Sensitive view here</View>

Capturing screen views

With captureScreens: true (the default in PostHogProvider), PostHog captures a $screen event automatically when the user navigates, provided you're using @react-navigation/native (v6 or lower) or react-native-navigation.

To manually send a screen capture event, use the screen method:

posthog.screen('Dashboard', { fromIcon: 'bottom' })

React Navigation v7 users: automatic screen tracking may throw errors if PostHog is initialized outside a screen context. For v7, disable automatic screen capture (captureScreens: false) and call posthog.screen() manually inside each screen component.

Filtering autocaptured screens

You can stop specific screens from being autocaptured by filtering them in your before-send hook. Return null for any $screen event whose $screen_name matches a screen you don't want to track, and it's dropped before being sent – keeping unwanted screen views out of your event log.

Because it's just a function, you can filter however you like – an ignorelist (drop the screens you name), an allowlist (invert the check to capture only the screens you name), or any custom rule such as a name prefix, a regex, or a check against the event's properties.

before_send is a client option, so pass it via the provider's options prop (or to new PostHog(...) if you create the client yourself):

const IGNORED_SCREENS = new Set(['Splash', 'Debug'])

<PostHogProvider
    apiKey="<ph_project_token>"
    autocapture={{ captureScreens: true }}
    options={{
        host: 'https://us.i.posthog.com',
        before_send: (event) => {
            if (event?.event === '$screen') {
                const screenName = event.properties?.['$screen_name']
                return IGNORED_SCREENS.has(screenName) ? null : event
            }
            return event
        },
    }}
>
    {/* app */}
</PostHogProvider>

Swap the check for an allowlist (return TRACKED_SCREENS.has(screenName) ? event : null) if you'd rather capture only a specific set of screens.

Common before_send patterns

before_send accepts a single function or an array of functions that run in order, so you can compose several small hooks. Filtering screens is one use – here are a few others.

Drop a specific event. Stop an internal or debug event from ever being sent:

const posthog = new PostHog('<ph_project_token>', {
    before_send: (event) => {
        if (event?.event === 'debug_only_event') {
            return null // never send this event
        }
        return event
    },
})

Log events instead of sending them. Handy while debugging what would be captured:

const posthog = new PostHog('<ph_project_token>', {
    before_send: (event) => {
        console.log('[PostHog] would send', event?.event, event?.properties)
        return null // drop everything
    },
})

Redact sensitive properties. Strip a value before it leaves the device:

const posthog = new PostHog('<ph_project_token>', {
    before_send: (event) => {
        if (event?.properties?.email) {
            event.properties.email = '***'
        }
        return event
    },
})

For more examples, see the JavaScript Web SDK docs.

Identifying users

We highly recommend reading our section on Identifying users to better understand how to correctly use this method.

Using identify, you can associate events with specific users. This enables you to gain full insights as to how they're using your product across different sessions, devices, and platforms.

An identify call has the following arguments:

  • distinctId: Required. A unique identifier for your user. Typically either their email or database ID.
  • properties: Optional. A dictionary with key:value pairs to set the person properties
posthog.identify('distinctID',
  { // ($set):
      email: '[email protected]',
      name: 'My Name'
  }
)

$set_once works just like $set, except that it will only set the property if the user doesn't already have that property set. See the difference between $set and $set_once

posthog.identify('distinctID',
  {
    $set: {
        email: '[email protected]',
        name: 'My Name'
    },
    $set_once: {
        date_of_first_log_in: '2024-03-01'
    }
  }
)

You should call identify as soon as you're able to. Typically, this is after your user logs in. This ensures that events sent during your user's sessions are correctly associated with them.

When you call identify, all previously tracked anonymous events will be linked to the user.

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

To do this, call posthog.get_distinct_id(). This returns either the ID automatically generated by PostHog or the ID that has been passed by a call to identify().

Alias

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.

In this case, you can use alias to assign another distinct ID to the same user.

// Sets alias for current user
posthog.alias('distinct_id')

We strongly recommend reading our docs on alias to best understand how to correctly use this method.

Setting person properties

Person properties enable you to capture, manage, and analyze specific data about a user. You can use them to create filters or cohorts, which can then be used in insights, feature flags, and more.

To set a user's properties, include the $set or $set_once property when capturing any event:

$set

posthog.capture('some_event', { $set: { userProperty: 'value' } })

$set_once

$set_once works just like $set, except it only sets the property if the user doesn't already have that property set.

posthog.capture('some_event', { $set_once: { userProperty: 'value' } })

You can also use setPersonProperties() and unsetPersonProperties() to manage person properties directly. See person properties for examples.

Super properties

Super properties are properties associated with events that are set once and then sent with every capture call, be it a $screen, an autocaptured touch, or anything else.

They are set using posthog.register, which takes a properties object as a parameter, and they persist across sessions.

For example:

posthog.register({
    'icecream pref': 'vanilla',
    team_id: 22,
})

The call above ensures that every event sent by the user will include "icecream pref": "vanilla" and "team_id": 22. This way, if you filtered events by property using icecream_pref = vanilla, it would display all events captured on that user after the posthog.register call, since they all include the specified Super Property.

This does not set the user's properties. This only sets the properties for their events. To store person properties, see the setting person properties section.

Removing stored super properties

Super Properties are persisted across sessions so you have to explicitly remove them if they are no longer relevant. In order to stop sending a Super Property with events, you can use posthog.unregister, like so:

posthog.unregister('icecream pref'),

This will remove the super property and subsequent events will not include it.

If you are doing this as part of a user logging out you can instead simply posthog.reset() which takes care of clearing all stored Super Properties and more.

Opt out of data capture

You can completely opt users out from data capture by default or on a per-person basis. See Opt in/out for the current React Native API.

Flush

You can configure how many events queue before flushing with flushAt. Setting this to 1 will send events immediately and will use more battery. The default is 20.

You can also configure the flush interval with flushInterval, in milliseconds (default 10000), after which queued events are sent regardless of how many have been gathered:

const posthog = new PostHog('<ph_project_token>', {
  flushAt: 20,
  flushInterval: 10000,
})

You can also manually flush the queue to start sending events immediately instead of waiting for the next batch:

await posthog.flush()

If a flush is already in progress, it returns a promise for the existing flush.

Flushing is best-effort and asynchronous – it starts sending queued events in the background but doesn't wait for the request to finish, so it isn't a delivery guarantee.

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.

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.

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

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

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

// 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.getFeatureFlagResult('key-for-your-multivariate-flag')?.payload

Inspecting all feature flags

You can inspect all currently loaded feature flags with getAllFeatureFlags(). It returns each flag's key, enabled state, variant, and payload, and does not send a $feature_flag_called event, so calling it won't affect your experiment results or flag usage analytics:

for (const flag of posthog.getAllFeatureFlags()) {
    console.log(flag.key, flag.enabled, flag.variant, flag.payload)
}

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:

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():

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

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

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:

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

Or clear cached values for inactive users:

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.

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:

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:

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:

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

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

posthog.resetPersonPropertiesForFlags()

The same holds for group properties:

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

Pass bootstrap in the initialization options to seed identity and flag values:

<PostHogProvider
    apiKey="<ph_project_token>"
    options={{
        host: 'https://us.i.posthog.com',
        bootstrap: {
            distinctId: 'distinct_id_of_your_user',
            isIdentifiedId: true,
            featureFlags: {
                'flag-1': true,
                'variant-flag': 'control',
            },
        },
    }}
>
    <MyComponent />
</PostHogProvider>

See bootstrapping Feature Flags for server-side evaluation and flag lifecycle, and SDK bootstrapping for cross-SDK identity behavior.

Supplying flags from your own backend

If you evaluate feature flags outside the SDK – for example on your own server with posthog-node local evaluation, then pass the results into your app – you can have the SDK use those values and never fetch flags itself.

Set disableRemoteFeatureFlags: true so the SDK never requests /flags (including the refetches that identify(), group(), and reset() normally trigger), then push your evaluated flags at runtime with updateFlags(flags, payloads?, { merge }):

const posthog = new PostHog('<ph_project_token>', {
  host: 'https://us.i.posthog.com',
  // Don't fetch or evaluate flags on-device – we supply them ourselves.
  disableRemoteFeatureFlags: true,
  // Optional: values that must be available at startup, before updateFlags() runs.
  // Without this, reads return their not-loaded defaults until you push flags.
  bootstrap: {
    featureFlags: { 'my-flag': true },
    featureFlagPayloads: { 'my-flag': { color: 'blue' } },
  },
})

// Later – e.g. after login, once your backend has evaluated flags for this user:
posthog.updateFlags(
  { 'my-flag': true, 'my-variant-flag': 'test' },
  { 'my-flag': { color: 'blue' } }
)

posthog.getFeatureFlag('my-variant-flag') // 'test'
posthog.getFeatureFlagResult('my-flag')?.payload // { color: 'blue' }

updateFlags replaces the stored flags by default; pass { merge: true } to merge into the existing set instead. Values persist across app restarts, and getFeatureFlag() / getFeatureFlagResult() read them back like any other flag.

Note that reset() (called on logout) clears the supplied flags, so re-push them with updateFlags() after the next identity change. Use bootstrap for any flag values that must be available at startup bef