
Integration Expo
- 106 installs
- 58 repo stars
- Updated August 5, 2026
- posthog/skills
integration-expo is a Claude Code skill for ai & agent building.
About
integration-expo is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted coding.
- integration-expo
- AI & Agent Building
- AI-coding skill
Integration Expo by the numbers
- 106 all-time installs (skills.sh)
- +4 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #4,152 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/posthog/skills --skill integration-expoAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 106 |
|---|---|
| repo stars | ★ 58 |
| Last updated | August 5, 2026 |
| Repository | posthog/skills ↗ |
How do I helps with ai & agent building tasks during AI-assisted development.?
Helps with ai & agent building tasks during AI-assisted development.
Who is it for?
Best when you're working on ai & agent building and need structured help with integration expo.
Skip if: Teams with no ai & agent building needs, or anyone wanting a generic chat assistant without this specific workflow.
When should I use this skill?
When you need to helps with ai & agent building tasks during AI-assisted development., or when integration-expo is a claude code skill for ai & agent building.
What you get
Structured output aligned to integration-expo: integration-expo, AI & Agent Building.
Files
PostHog integration for Expo
This skill helps you add PostHog analytics to Expo applications.
Workflow
Follow these steps in order to complete the integration:
1. basic-integration-1.0-begin.md - PostHog Setup - Begin ← Start here 2. basic-integration-1.1-edit.md - PostHog Setup - Edit 3. basic-integration-1.2-revise.md - PostHog Setup - Revise 4. basic-integration-1.3-conclude.md - PostHog Setup - Conclusion
Reference files
references/EXAMPLE.md- Expo example project codereferences/react-native.md- React native - docsreferences/identify-users.md- Identify users - docsreferences/basic-integration-1.0-begin.md- PostHog setup - beginreferences/basic-integration-1.1-edit.md- PostHog setup - editreferences/basic-integration-1.2-revise.md- PostHog setup - revisereferences/basic-integration-1.3-conclude.md- PostHog setup - conclusion
The example project shows the target implementation pattern. Consult the documentation for API details.
Key principles
- Environment variables: Always use environment variables for PostHog keys. Never hardcode them.
- Minimal changes: Add PostHog code alongside existing integrations. Don't replace or restructure existing code.
- Match the example: Your implementation should follow the example project's patterns as closely as possible.
Framework guidelines
- posthog-react-native is the React Native SDK package name (same as bare RN)
- Use expo-constants with app.config.js extras for POSTHOG_PROJECT_TOKEN and POSTHOG_HOST (NOT react-native-config)
- Access config via
Constants.expoConfig?.extra?.posthogProjectTokenin your posthog.ts config file - For expo-router, wrap PostHogProvider in app/_layout.tsx and manually track screens with
posthog.screen(pathname, params)in a useEffect - posthog-react-native is the React Native SDK package name
- Use react-native-config to load POSTHOG_PROJECT_TOKEN and POSTHOG_HOST from .env (variables are embedded at build time, not runtime)
- react-native-svg is a required peer dependency of posthog-react-native (used by the surveys feature) and must be installed alongside it
- Place PostHogProvider INSIDE NavigationContainer for React Navigation v7 compatibility
Identifying users
Identify users during login and signup events. Refer to the example code and documentation for the correct identify pattern for this framework. If both frontend and backend code exist, pass the client-side session and distinct ID using X-POSTHOG-DISTINCT-ID and X-POSTHOG-SESSION-ID headers to maintain correlation.
Error tracking
Add PostHog error tracking to relevant files, particularly around critical user flows and API boundaries.
We're making an event tracking plan for this project.
Before proceeding, find any existing posthog.capture() code. Make note of event name formatting.
From the project's file list, select between 10 and 15 files that might have interesting business value for event tracking, especially conversion and churn events. Also look for additional files related to login that could be used for identifying users, along with error handling. Read the files. If a file is already well-covered by PostHog events, replace it with another option. Do not spawn subagents.
Look for opportunities to track client-side events.
IMPORTANT: Server-side events are REQUIRED if the project includes any instrumentable server-side code. If the project has API routes (e.g., app/api/**/route.ts) or Server Actions, you MUST include server-side events for critical business operations like:
- Payment/checkout completion
- Webhook handlers
- Authentication endpoints
Do not skip server-side events - they capture actions that cannot be tracked client-side.
Create a new file with a JSON array at the root of the project: .posthog-events.json. It should include one object for each event we want to add: event name, event description, and the file path we want to place the event in. If events already exist, don't duplicate them; supplement them.
Track actions only, not pageviews. These can be captured automatically. Exceptions can be made for "viewed"-type events that correspond to the top of a conversion funnel.
As you review files, make an internal note of opportunities to identify users and catch errors. We'll need them for the next step.
Status
Before beginning a phase of the setup, you will send a status message with the exact prefix '[STATUS]', as in:
[STATUS] Checking project structure.
Status to report in this phase:
- Checking project structure
- Verifying PostHog dependencies
- Generating events based on project
---
Upon completion, continue with: basic-integration-1.1-edit.md
For each of the files and events noted in .posthog-events.json, make edits to capture events using PostHog. Make sure to set up any helper files needed. Carefully examine the included example project code: your implementation should match it as closely as possible. Do not spawn subagents.
Use environment variables for PostHog keys. Do not hardcode PostHog keys.
If a file already has existing integration code for other tools or services, don't overwrite or remove that code. Place PostHog code below it.
For each event, add useful properties, and use your access to the PostHog source code to ensure correctness. You also have access to documentation about creating new events with PostHog. Consider this documentation carefully and follow it closely before adding events. Your integration should be based on documented best practices. Carefully consider how the user project's framework version may impact the correct PostHog integration approach.
Remember that you can find the source code for any dependency in the node_modules directory. This may be necessary to properly populate property names. There are also example project code files available via the PostHog MCP; use these for reference.
Where possible, add calls for PostHog's identify() function on the client side upon events like logins and signups. Use the contents of login and signup forms to identify users on submit. If there is server-side code, pass the client-side session and distinct ID to the server-side code to identify the user. On the server side, make sure events have a matching distinct ID where relevant.
It's essential to do this in both client code and server code, so that user behavior from both domains is easy to correlate.
You should also add PostHog exception capture error tracking to these files where relevant.
Remember: Do not alter the fundamental architecture of existing files. Make your additions minimal and targeted.
Remember the documentation and example project resources you were provided at the beginning. Read them now.
Status
Status to report in this phase:
- Inserting PostHog capture code
- A status message for each file whose edits you are planning, including a high level summary of changes
- A status message for each file you have edited
---
Upon completion, continue with: basic-integration-1.2-revise.md
Check the project for errors. Read the package.json file for any type checking or build scripts that may provide input about what to fix. Remember that you can find the source code for any dependency in the node_modules directory. Do not spawn subagents.
Ensure that any components created were actually used.
Once all other tasks are complete, run any linter or prettier-like scripts found in the package.json, but ONLY on the files you have edited or created during this session. Do not run formatting or linting across the entire project's codebase.
Status
Status to report in this phase:
- Finding and correcting errors
- Report details of any errors you fix
- Linting, building and prettying
---
Upon completion, continue with: basic-integration-1.3-conclude.md
Use the PostHog MCP to create a new dashboard named "Analytics basics" based on the events created here. Make sure to use the exact same event names as implemented in the code. Populate it with up to five insights, with special emphasis on things like conversion funnels, churn events, and other business critical insights.
Search for a file called .posthog-events.json and read it for available events. Do not spawn subagents.
Create the file posthog-setup-report.md. It should include a summary of the integration edits, a table with the event names, event descriptions, and files where events were added, along with a list of links for the dashboard and insights created. Follow this format:
<wizard-report>
PostHog post-wizard report
The wizard has completed a deep integration of your project. [Detailed summary of changes]
[table of events/descriptions/files]
Next steps
We've built some insights and a dashboard for you to keep an eye on user behavior, based on the events we just instrumented:
[links]
Agent skill
We've left an agent skill folder in your project. You can use this context for further agent development when using Claude Code. This will help ensure the model provides the most up-to-date approaches for integrating PostHog.
</wizard-report>
Upon completion, remove .posthog-events.json.
Status
Status to report in this phase:
- Configured dashboard: [insert PostHog dashboard URL]
- Created setup report: [insert full local file path]
PostHog Expo Example Project
Repository: https://github.com/PostHog/context-mill Path: basics/expo
---
README.md
Burrito Consideration App (Expo)
A React Native Expo app demonstrating PostHog product analytics integration with modern React Native best practices.
Features
- Product Analytics: Full PostHog integration with event tracking
- Autocapture: Touch events and screen tracking
- Error Tracking: Manual exception capture with
$exceptionevents - User Authentication: Demo login with PostHog user identification
- Session Persistence: AsyncStorage for session management
- Modern React: React 19 with React Compiler for automatic memoization
- File-based Routing: Expo Router for navigation
- New Architecture: Enabled by default for better performance
Project Structure
basics/expo/
├── app/ # Expo Router screens (file-based routing)
│ ├── _layout.tsx # Root layout with PostHogProvider + AuthProvider
│ ├── index.tsx # Home screen (login/welcome)
│ ├── burrito.tsx # Burrito consideration screen
│ └── profile.tsx # User profile screen
├── src/
│ ├── config/
│ │ └── posthog.ts # PostHog client configuration
│ ├── contexts/
│ │ └── AuthContext.tsx # Authentication context with PostHog
│ ├── services/
│ │ └── storage.ts # AsyncStorage wrapper
│ └── styles/
│ └── theme.ts # Shared style constants
├── app.json # Expo configuration
├── babel.config.js # Babel config with React Compiler
├── eslint.config.js # ESLint flat config
├── package.json # Dependencies
├── tsconfig.json # TypeScript strict configuration
└── .env.example # Environment variables templateGetting Started
Prerequisites
- Node.js 18+
- iOS: Xcode (for iOS Simulator)
- Android: Android Studio with emulator
For Android builds: Set environment variables (required):
Add to ~/.zshrc or ~/.bashrc:
# Java from Android Studio (required for Gradle)
export JAVA_HOME="<path-to-android-studio-jdk>"
# Android SDK location
export ANDROID_HOME="$HOME/Library/Android/sdk"Examples:
export JAVA_HOME="/Applications/Android Studio.app/Contents/jbr/Contents/Home"export ANDROID_HOME="$HOME/Library/Android/sdk"
Then run source ~/.zshrc to apply.
Installation
1. Install dependencies:
cd basics/expo
npm install2. Configure PostHog (optional):
cp .env.example .env
# Edit .env with your PostHog project token3. Start the development server:
npx expo startRunning the App
# Start development server
npx expo start
# Run on iOS Simulator
npx expo run:ios
# Run on Android Emulator
npx expo run:androidPostHog Integration
Configuration
PostHog is configured in src/config/posthog.ts using environment variables from app.json:
import Constants from 'expo-constants'
const apiKey = Constants.expoConfig?.extra?.posthogProjectTokenEvent Tracking
Events are captured with properties:
posthog.capture('burrito_considered', {
total_considerations: count,
username: user.username,
})User Identification
Users are identified on login:
posthog.identify(username, {
$set: { username },
$set_once: { first_login_date: new Date().toISOString() },
})Screen Tracking
Manual screen tracking with Expo Router:
useEffect(() => {
posthog.screen(pathname, {
previous_screen: previousPathname.current,
})
}, [pathname])Error Tracking
Manual exception capture:
posthog.capture('$exception', {
$exception_type: error.name,
$exception_message: error.message,
$exception_stack_trace_raw: error.stack,
})Modern React Features
React Compiler
Automatic memoization is enabled via babel-plugin-react-compiler. No need for manual useMemo, useCallback, or React.memo.
React 19 use API
The useAuth hook uses the new use API for context:
export function useAuth() {
const context = use(AuthContext)
if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider')
}
return context
}New Architecture
Enabled in app.json for better performance:
{
"expo": {
"newArchEnabled": true
}
}Building for Production
Use EAS Build for production builds:
# Install EAS CLI
npm install -g eas-cli
# Configure EAS
eas build:configure
# Build for iOS
eas build --platform ios
# Build for Android
eas build --platform androidPerformance Debugging
1. Press J in Expo CLI to open Chrome DevTools 2. Go to: Profiler > [Gear icon] > "Highlight updates when components render" 3. Interact with your app to see which components re-render
Tech Stack
- Expo SDK 54 - Managed workflow
- React 19 - Latest React with Compiler support
- React Native 0.81 - Latest stable
- Expo Router 6 - File-based navigation
- PostHog - Product analytics
- TypeScript - Strict mode enabled
- React Native Reanimated - Smooth animations
- React Native Gesture Handler - Native gestures
License
MIT
---
.env.example
POSTHOG_PROJECT_TOKEN=phc_your_project_token_here
POSTHOG_HOST=https://us.i.posthog.com
---
.npmrc
legacy-peer-deps=true
---
app.config.js
export default {
expo: {
name: 'BurritoApp',
slug: 'burrito-app',
version: '1.0.0',
orientation: 'portrait',
icon: './assets/icon.png',
userInterfaceStyle: 'light',
newArchEnabled: true,
experiments: {
reactCompiler: true,
},
splash: {
image: './assets/splash-icon.png',
resizeMode: 'contain',
backgroundColor: '#333333',
},
ios: {
supportsTablet: true,
bundleIdentifier: 'com.posthog.burritoapp',
},
android: {
adaptiveIcon: {
foregroundImage: './assets/adaptive-icon.png',
backgroundColor: '#333333',
},
package: 'com.posthog.burritoapp',
edgeToEdgeEnabled: true,
},
web: {
favicon: './assets/favicon.png',
},
scheme: 'burritoapp',
extra: {
posthogProjectToken: process.env.POSTHOG_PROJECT_TOKEN,
posthogHost: process.env.POSTHOG_HOST || 'https://us.i.posthog.com',
},
plugins: ['expo-router', 'expo-localization'],
},
}
---
app/_layout.tsx
import { Stack, usePathname, useGlobalSearchParams } from 'expo-router'
import { useEffect, useRef } from 'react'
import { StatusBar } from 'expo-status-bar'
import { PostHogProvider } from 'posthog-react-native'
import { SafeAreaProvider } from 'react-native-safe-area-context'
import { GestureHandlerRootView } from 'react-native-gesture-handler'
import { AuthProvider } from '../src/contexts/AuthContext'
import { posthog } from '../src/config/posthog'
import { colors } from '../src/styles/theme'
export default function RootLayout() {
const pathname = usePathname()
const params = useGlobalSearchParams()
const previousPathname = useRef<string | undefined>(undefined)
// Manual screen tracking for Expo Router
// @see https://docs.expo.dev/router/reference/screen-tracking/
// React Compiler will auto-optimize this effect
useEffect(() => {
if (previousPathname.current !== pathname) {
posthog.screen(pathname, {
previous_screen: previousPathname.current ?? null,
// Include route params for analytics (filter sensitive data if needed)
...params,
})
previousPathname.current = pathname
}
}, [pathname, params])
return (
<GestureHandlerRootView style={{ flex: 1 }}>
<SafeAreaProvider>
<StatusBar style="light" backgroundColor={colors.headerBackground} />
<PostHogProvider
client={posthog}
autocapture={{
captureScreens: false, // Manual tracking with Expo Router
captureTouches: true,
propsToCapture: ['testID'],
maxElementsCaptured: 20,
}}
>
<AuthProvider>
<Stack
screenOptions={{
headerStyle: { backgroundColor: colors.headerBackground },
headerTintColor: colors.headerText,
headerTitleStyle: { fontWeight: 'bold' },
animation: 'slide_from_right',
}}
>
<Stack.Screen name="index" options={{ title: 'Burrito App' }} />
<Stack.Screen name="burrito" options={{ title: 'Burrito Consideration' }} />
<Stack.Screen name="profile" options={{ title: 'Profile' }} />
</Stack>
</AuthProvider>
</PostHogProvider>
</SafeAreaProvider>
</GestureHandlerRootView>
)
}
---
app/burrito.tsx
import { useState, useEffect } from 'react'
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native'
import { useRouter } from 'expo-router'
import { usePostHog } from 'posthog-react-native'
import { useAuth } from '../src/contexts/AuthContext'
import { colors, spacing, typography, borderRadius, shadows } from '../src/styles/theme'
/**
* Burrito Consideration Screen
*
* Demonstrates PostHog event tracking with custom properties.
* Each time the user considers a burrito, an event is captured.
*
* @see https://posthog.com/docs/libraries/react-native#capturing-events
*/
export default function BurritoScreen() {
const { user, incrementBurritoConsiderations } = useAuth()
const router = useRouter()
const posthog = usePostHog()
const [hasConsidered, setHasConsidered] = useState(false)
// Redirect to home if not logged in
useEffect(() => {
if (!user) {
router.replace('/')
}
}, [user, router])
if (!user) {
return null
}
const handleConsideration = async () => {
const newCount = user.burritoConsiderations + 1
// Update state first for immediate feedback
await incrementBurritoConsiderations()
setHasConsidered(true)
// Hide success message after 2 seconds
setTimeout(() => setHasConsidered(false), 2000)
// Capture custom event in PostHog with properties
// We recommend using a [object] [verb] format for event names
// @see https://posthog.com/docs/libraries/react-native#capturing-events
posthog.capture('burrito_considered', {
total_considerations: newCount,
username: user.username,
})
}
return (
<View style={styles.container}>
<View style={styles.card}>
<Text style={styles.title}>Burrito Consideration Zone</Text>
<Text style={styles.text}>
Take a moment to truly consider the potential of burritos.
</Text>
{/*
testID is captured by PostHog autocapture for touch events
This helps identify the button in analytics
@see https://posthog.com/docs/libraries/react-native#autocapture
*/}
<TouchableOpacity
style={styles.burritoButton}
onPress={handleConsideration}
activeOpacity={0.8}
testID="consider-burrito-button"
>
<Text style={styles.burritoButtonText}>Consider Burrito</Text>
</TouchableOpacity>
{hasConsidered && (
<View style={styles.successContainer}>
<Text style={styles.success}>Thank you for your consideration!</Text>
<Text style={styles.successCount}>Count: {user.burritoConsiderations}</Text>
</View>
)}
<View style={styles.stats}>
<Text style={styles.statsTitle}>Consideration Stats</Text>
<Text style={styles.statsText}>Total considerations: {user.burritoConsiderations}</Text>
</View>
</View>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: colors.background,
padding: spacing.md,
},
card: {
backgroundColor: colors.cardBackground,
borderRadius: borderRadius.md,
padding: spacing.lg,
...shadows.md,
},
title: {
fontSize: typography.sizes.xl,
fontWeight: typography.weights.bold,
color: colors.text,
marginBottom: spacing.sm,
},
text: {
fontSize: typography.sizes.md,
color: colors.text,
marginBottom: spacing.lg,
lineHeight: 24,
},
burritoButton: {
backgroundColor: colors.burrito,
borderRadius: borderRadius.sm,
padding: spacing.lg,
alignItems: 'center',
marginVertical: spacing.md,
...shadows.sm,
},
burritoButtonText: {
color: colors.white,
fontSize: typography.sizes.lg,
fontWeight: typography.weights.bold,
},
successContainer: {
alignItems: 'center',
marginVertical: spacing.sm,
},
success: {
color: colors.success,
fontSize: typography.sizes.md,
fontWeight: typography.weights.medium,
},
successCount: {
color: colors.success,
fontSize: typography.sizes.lg,
fontWeight: typography.weights.bold,
marginTop: spacing.xs,
},
stats: {
backgroundColor: colors.statsBackground,
padding: spacing.md,
borderRadius: borderRadius.sm,
marginTop: spacing.lg,
},
statsTitle: {
fontSize: typography.sizes.lg,
fontWeight: typography.weights.semibold,
color: colors.text,
marginBottom: spacing.xs,
},
statsText: {
fontSize: typography.sizes.md,
color: colors.text,
},
})
---
app/index.tsx
import { useState } from 'react'
import {
View,
Text,
TextInput,
TouchableOpacity,
StyleSheet,
ScrollView,
KeyboardAvoidingView,
Platform,
} from 'react-native'
import { useRouter } from 'expo-router'
import { useAuth } from '../src/contexts/AuthContext'
import { colors, spacing, typography, borderRadius, shadows } from '../src/styles/theme'
export default function HomeScreen() {
const { user, login, logout } = useAuth()
const router = useRouter()
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState('')
const [isSubmitting, setIsSubmitting] = useState(false)
const handleSubmit = async () => {
setError('')
if (!username.trim() || !password.trim()) {
setError('Please provide both username and password')
return
}
setIsSubmitting(true)
try {
const success = await login(username, password)
if (success) {
setUsername('')
setPassword('')
} else {
setError('An error occurred during login')
}
} catch {
setError('An error occurred during login')
} finally {
setIsSubmitting(false)
}
}
// Logged in view
if (user) {
return (
<ScrollView style={styles.scrollView} contentContainerStyle={styles.scrollContent}>
<View style={styles.card}>
<Text style={styles.title}>Welcome back, {user.username}!</Text>
<Text style={styles.text}>You are now logged in. Feel free to explore:</Text>
<View style={styles.buttonGroup}>
<TouchableOpacity
style={[styles.button, styles.burritoButton]}
onPress={() => router.push('/burrito')}
activeOpacity={0.8}
>
<Text style={styles.buttonText}>Consider Burritos</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.button, styles.primaryButton]}
onPress={() => router.push('/profile')}
activeOpacity={0.8}
>
<Text style={styles.buttonText}>View Profile</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.button, styles.logoutButton]}
onPress={logout}
activeOpacity={0.8}
>
<Text style={styles.buttonText}>Logout</Text>
</TouchableOpacity>
</View>
</View>
</ScrollView>
)
}
// Login view
return (
<KeyboardAvoidingView
style={styles.container}
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
>
<ScrollView
style={styles.scrollView}
contentContainerStyle={styles.scrollContent}
keyboardShouldPersistTaps="handled"
>
<View style={styles.card}>
<Text style={styles.title}>Welcome to Burrito Consideration App</Text>
<Text style={styles.text}>Please sign in to begin your burrito journey</Text>
<View style={styles.form}>
<Text style={styles.label}>Username:</Text>
<TextInput
style={styles.input}
value={username}
onChangeText={setUsername}
placeholder="Enter any username"
placeholderTextColor={colors.textLight}
autoCapitalize="none"
autoCorrect={false}
autoComplete="username"
editable={!isSubmitting}
/>
<Text style={styles.label}>Password:</Text>
<TextInput
style={styles.input}
value={password}
onChangeText={setPassword}
placeholder="Enter any password"
placeholderTextColor={colors.textLight}
secureTextEntry
autoComplete="password"
editable={!isSubmitting}
/>
{error ? <Text style={styles.error}>{error}</Text> : null}
<TouchableOpacity
style={[styles.button, styles.primaryButton, isSubmitting && styles.buttonDisabled]}
onPress={handleSubmit}
disabled={isSubmitting}
activeOpacity={0.8}
>
<Text style={styles.buttonText}>{isSubmitting ? 'Signing In...' : 'Sign In'}</Text>
</TouchableOpacity>
</View>
<Text style={styles.note}>
Note: This is a demo app. Use any username and password to sign in.
</Text>
</View>
</ScrollView>
</KeyboardAvoidingView>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: colors.background,
},
scrollView: {
flex: 1,
backgroundColor: colors.background,
},
scrollContent: {
flexGrow: 1,
padding: spacing.md,
justifyContent: 'center',
},
card: {
backgroundColor: colors.cardBackground,
borderRadius: borderRadius.md,
padding: spacing.lg,
...shadows.md,
},
title: {
fontSize: typography.sizes.xl,
fontWeight: typography.weights.bold,
color: colors.text,
marginBottom: spacing.sm,
},
text: {
fontSize: typography.sizes.md,
color: colors.text,
marginBottom: spacing.md,
lineHeight: 24,
},
form: {
marginTop: spacing.md,
},
label: {
fontSize: typography.sizes.md,
fontWeight: typography.weights.medium,
color: colors.text,
marginBottom: spacing.xs,
},
input: {
backgroundColor: colors.inputBackground,
borderWidth: 1,
borderColor: colors.border,
borderRadius: borderRadius.sm,
padding: spacing.sm,
fontSize: typography.sizes.md,
color: colors.text,
marginBottom: spacing.md,
},
buttonGroup: {
marginTop: spacing.md,
gap: spacing.sm,
},
button: {
borderRadius: borderRadius.sm,
padding: spacing.md,
alignItems: 'center',
marginTop: spacing.sm,
},
primaryButton: {
backgroundColor: colors.primary,
},
burritoButton: {
backgroundColor: colors.burrito,
},
logoutButton: {
backgroundColor: colors.danger,
},
buttonDisabled: {
opacity: 0.6,
},
buttonText: {
color: colors.white,
fontSize: typography.sizes.md,
fontWeight: typography.weights.semibold,
},
error: {
color: colors.danger,
marginBottom: spacing.sm,
fontSize: typography.sizes.sm,
},
note: {
marginTop: spacing.lg,
color: colors.textSecondary,
fontSize: typography.sizes.sm,
textAlign: 'center',
lineHeight: 20,
},
})
---
app/profile.tsx
import { useEffect } from 'react'
import { View, Text, TouchableOpacity, StyleSheet, Alert } from 'react-native'
import { useRouter } from 'expo-router'
import { usePostHog } from 'posthog-react-native'
import { useAuth } from '../src/contexts/AuthContext'
import { colors, spacing, typography, borderRadius, shadows } from '../src/styles/theme'
/**
* Profile Screen
*
* Displays user information and demonstrates PostHog error tracking.
* The test error button shows how to capture exceptions manually.
*
* @see https://posthog.com/docs/libraries/react-native#error-tracking
*/
export default function ProfileScreen() {
const { user } = useAuth()
const router = useRouter()
const posthog = usePostHog()
// Redirect to home if not logged in
useEffect(() => {
if (!user) {
router.replace('/')
}
}, [user, router])
if (!user) {
return null
}
/**
* Triggers a test error and captures it in PostHog
*
* This demonstrates manual exception capture using the $exception event.
* In production, you would typically set up automatic exception capture
* or use the before_send callback for customization.
*
* @see https://posthog.com/docs/libraries/react-native#error-tracking
*/
const triggerTestError = () => {
try {
throw new Error('Test error for PostHog error tracking')
} catch (err) {
const error = err as Error
// Capture exception in PostHog
// @see https://posthog.com/docs/error-tracking
posthog.capture('$exception', {
$exception_list: [
{
type: error.name,
value: error.message,
stacktrace: {
type: 'raw',
frames: error.stack ?? '',
},
},
],
$exception_source: 'react-native',
// Additional context
username: user.username,
screen: 'Profile',
})
console.error('Captured error:', error)
Alert.alert('Error Captured', 'The test error has been sent to PostHog!', [{ text: 'OK' }])
}
}
const getJourneyMessage = () => {
const count = user.burritoConsiderations
if (count === 0) {
return "You haven't considered any burritos yet. Visit the Burrito Consideration page to start!"
} else if (count === 1) {
return "You've considered the burrito potential once. Keep going!"
} else if (count < 5) {
return "You're getting the hang of burrito consideration!"
} else if (count < 10) {
return "You're becoming a burrito consideration expert!"
} else {
return 'You are a true burrito consideration master!'
}
}
return (
<View style={styles.container}>
<View style={styles.card}>
<Text style={styles.title}>User Profile</Text>
<View style={styles.stats}>
<Text style={styles.statsTitle}>Your Information</Text>
<View style={styles.infoRow}>
<Text style={styles.infoLabel}>Username:</Text>
<Text style={styles.infoValue}>{user.username}</Text>
</View>
<View style={styles.infoRow}>
<Text style={styles.infoLabel}>Burrito Considerations:</Text>
<Text style={styles.infoValue}>{user.burritoConsiderations}</Text>
</View>
</View>
{/*
testID is captured by PostHog autocapture for touch events
@see https://posthog.com/docs/libraries/react-native#autocapture
*/}
<TouchableOpacity
style={styles.errorButton}
onPress={triggerTestError}
activeOpacity={0.8}
testID="trigger-error-button"
>
<Text style={styles.buttonText}>Trigger Test Error (for PostHog)</Text>
</TouchableOpacity>
<View style={styles.journey}>
<Text style={styles.journeyTitle}>Your Burrito Journey</Text>
<Text style={styles.journeyText}>{getJourneyMessage()}</Text>
</View>
</View>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: colors.background,
padding: spacing.md,
},
card: {
backgroundColor: colors.cardBackground,
borderRadius: borderRadius.md,
padding: spacing.lg,
...shadows.md,
},
title: {
fontSize: typography.sizes.xl,
fontWeight: typography.weights.bold,
color: colors.text,
marginBottom: spacing.md,
},
stats: {
backgroundColor: colors.statsBackground,
padding: spacing.md,
borderRadius: borderRadius.sm,
},
statsTitle: {
fontSize: typography.sizes.lg,
fontWeight: typography.weights.semibold,
color: colors.text,
marginBottom: spacing.sm,
},
infoRow: {
flexDirection: 'row',
marginBottom: spacing.xs,
},
infoLabel: {
fontSize: typography.sizes.md,
fontWeight: typography.weights.bold,
color: colors.text,
marginRight: spacing.xs,
},
infoValue: {
fontSize: typography.sizes.md,
color: colors.text,
},
errorButton: {
backgroundColor: colors.danger,
borderRadius: borderRadius.sm,
padding: spacing.md,
alignItems: 'center',
marginTop: spacing.lg,
},
buttonText: {
color: colors.white,
fontSize: typography.sizes.md,
fontWeight: typography.weights.semibold,
},
journey: {
marginTop: spacing.lg,
},
journeyTitle: {
fontSize: typography.sizes.lg,
fontWeight: typography.weights.semibold,
color: colors.text,
marginBottom: spacing.sm,
},
journeyText: {
fontSize: typography.sizes.md,
color: colors.text,
lineHeight: 24,
},
})
---
babel.config.js
module.exports = function (api) {
api.cache(true)
return {
presets: ['babel-preset-expo'],
plugins: [
['babel-plugin-react-compiler'],
'react-native-reanimated/plugin', // Must be last
],
}
}
---
src/config/posthog.ts
import PostHog from 'posthog-react-native'
import Constants from 'expo-constants'
// Configuration loaded from app.config.js extras via expo-constants
// Environment variables are read at build time in app.config.js
const apiKey = Constants.expoConfig?.extra?.posthogProjectToken as string | undefined
const host = (Constants.expoConfig?.extra?.posthogHost as string) || 'https://us.i.posthog.com'
const isPostHogConfigured = apiKey && apiKey !== 'phc_your_project_token_here'
if (__DEV__) {
console.log('PostHog config:', {
apiKey: apiKey ? `SET` : 'NOT SET',
host,
isConfigured: isPostHogConfigured,
})
}
if (!isPostHogConfigured) {
console.warn(
'PostHog project token not configured. Analytics will be disabled. ' +
'Set POSTHOG_PROJECT_TOKEN in your .env file to enable analytics.'
)
}
/**
* PostHog client instance for Expo
*
* Configuration loaded from app.config.js extras via expo-constants.
* Required peer dependencies: expo-file-system, expo-application,
* expo-device, expo-localization
*
* For React Native Web targets, use @react-native-async-storage/async-storage
* instead of expo-file-system (Web and macOS targets not supported by expo-file-system).
*
* @see https://posthog.com/docs/libraries/react-native
*/
export const posthog = new PostHog(apiKey || 'placeholder_key', {
// PostHog API host
host,
// Disable PostHog if project token is not configured
disabled: !isPostHogConfigured,
// Capture app lifecycle events:
// - Application Installed, Application Updated
// - Application Opened, Application Became Active, Application Backgrounded
captureAppLifecycleEvents: true,
// Enable debug mode in development for verbose logging
debug: __DEV__,
// Batching: queue events and flush periodically to optimize battery usage
flushAt: 20, // Number of events to queue before sending
flushInterval: 10000, // Interval in ms between periodic flushes
maxBatchSize: 100, // Maximum events per batch
maxQueueSize: 1000, // Maximum queued events (oldest dropped when full)
// Feature flags
preloadFeatureFlags: true, // Load flags on initialization
sendFeatureFlagEvent: true, // Track getFeatureFlag calls for experiments
featureFlagsRequestTimeoutMs: 10000, // Timeout for flag requests (prevents blocking)
// Network settings
requestTimeout: 10000, // General request timeout in ms
fetchRetryCount: 3, // Number of retry attempts for failed requests
fetchRetryDelay: 3000, // Delay between retries in ms
})
export const isPostHogEnabled = isPostHogConfigured
---
src/contexts/AuthContext.tsx
import React, { createContext, useState, useEffect, use } from 'react'
import type { ReactNode } from 'react'
import { usePostHog } from 'posthog-react-native'
import { storage } from '../services/storage'
import type { User } from '../services/storage'
interface AuthContextType {
user: User | null
isLoading: boolean
login: (username: string, password: string) => Promise<boolean>
logout: () => Promise<void>
incrementBurritoConsiderations: () => Promise<void>
}
const AuthContext = createContext<AuthContextType | undefined>(undefined)
interface AuthProviderProps {
children: ReactNode
}
export function AuthProvider({ children }: AuthProviderProps) {
const posthog = usePostHog()
const [user, setUser] = useState<User | null>(null)
const [isLoading, setIsLoading] = useState(true)
useEffect(() => {
const restoreSession = async () => {
try {
const storedUsername = await storage.getCurrentUser()
if (storedUsername) {
const existingUser = await storage.getUser(storedUsername)
if (existingUser) {
setUser(existingUser)
posthog.identify(storedUsername, {
$set: { username: storedUsername },
})
}
}
} catch (error) {
console.error('Failed to restore session:', error)
} finally {
setIsLoading(false)
}
}
restoreSession()
}, [posthog])
// React Compiler auto-memoizes these callbacks - no useCallback needed!
const login = async (username: string, password: string): Promise<boolean> => {
if (!username.trim() || !password.trim()) {
return false
}
try {
const existingUser = await storage.getUser(username)
const isNewUser = !existingUser
const userData: User = existingUser || {
username,
burritoConsiderations: 0,
}
await storage.saveUser(userData)
await storage.setCurrentUser(username)
setUser(userData)
posthog.identify(username, {
$set: { username },
$set_once: { first_login_date: new Date().toISOString() },
})
posthog.capture('user_logged_in', {
username,
is_new_user: isNewUser,
})
return true
} catch (error) {
console.error('Login error:', error)
return false
}
}
const logout = async () => {
posthog.capture('user_logged_out')
posthog.reset()
await storage.removeCurrentUser()
setUser(null)
}
const incrementBurritoConsiderations = async () => {
if (user) {
const updatedUser: User = {
...user,
burritoConsiderations: user.burritoConsiderations + 1,
}
setUser(updatedUser)
await storage.saveUser(updatedUser)
}
}
return (
<AuthContext
value={{
user,
isLoading,
login,
logout,
incrementBurritoConsiderations,
}}
>
{children}
</AuthContext>
)
}
/**
* React 19: Use the `use` API instead of useContext
* - Can be called conditionally (unlike useContext)
* - Enables more flexible component composition
*/
export function useAuth() {
const context = use(AuthContext)
if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider')
}
return context
}
---
src/services/storage.ts
import AsyncStorage from '@react-native-async-storage/async-storage'
const CURRENT_USER_KEY = 'currentUser'
const USERS_KEY = 'users'
export interface User {
username: string
burritoConsiderations: number
}
/**
* Storage service for persisting user data
* Uses AsyncStorage (React Native's async key-value storage)
*/
export const storage = {
/**
* Get the currently logged in user's username
*/
getCurrentUser: async (): Promise<string | null> => {
try {
return await AsyncStorage.getItem(CURRENT_USER_KEY)
} catch (error) {
console.error('Error getting current user:', error)
return null
}
},
/**
* Set the currently logged in user's username
*/
setCurrentUser: async (username: string): Promise<void> => {
try {
await AsyncStorage.setItem(CURRENT_USER_KEY, username)
} catch (error) {
console.error('Error setting current user:', error)
}
},
/**
* Remove the current user (logout)
*/
removeCurrentUser: async (): Promise<void> => {
try {
await AsyncStorage.removeItem(CURRENT_USER_KEY)
} catch (error) {
console.error('Error removing current user:', error)
}
},
/**
* Get all stored users
*/
getUsers: async (): Promise<Record<string, User>> => {
try {
const data = await AsyncStorage.getItem(USERS_KEY)
return data ? JSON.parse(data) : {}
} catch (error) {
console.error('Error getting users:', error)
return {}
}
},
/**
* Get a specific user by username
*/
getUser: async (username: string): Promise<User | null> => {
try {
const users = await storage.getUsers()
return users[username] || null
} catch (error) {
console.error('Error getting user:', error)
return null
}
},
/**
* Save a user to storage
*/
saveUser: async (user: User): Promise<void> => {
try {
const users = await storage.getUsers()
users[user.username] = user
await AsyncStorage.setItem(USERS_KEY, JSON.stringify(users))
} catch (error) {
console.error('Error saving user:', error)
}
},
/**
* Clear all stored data (for testing/debugging)
*/
clearAll: async (): Promise<void> => {
try {
await AsyncStorage.multiRemove([CURRENT_USER_KEY, USERS_KEY])
} catch (error) {
console.error('Error clearing storage:', error)
}
},
}
---
src/styles/theme.ts
/**
* Theme constants for consistent styling across the app
* Matches the color scheme from the TanStack Start web version
*/
export const colors = {
// Primary colors
primary: '#0070f3',
primaryDark: '#0051cc',
// Status colors
success: '#28a745',
successDark: '#218838',
danger: '#dc3545',
dangerDark: '#c82333',
// Feature colors
burrito: '#e07c24',
burritoDark: '#c96a1a',
// Neutral colors
background: '#f5f5f5',
white: '#ffffff',
text: '#333333',
textSecondary: '#666666',
textLight: '#999999',
border: '#dddddd',
borderLight: '#eeeeee',
// Component-specific
statsBackground: '#f8f9fa',
headerBackground: '#333333',
headerText: '#ffffff',
inputBackground: '#ffffff',
cardBackground: '#ffffff',
}
export const spacing = {
xs: 4,
sm: 8,
md: 16,
lg: 24,
xl: 32,
xxl: 48,
}
export const typography = {
sizes: {
xs: 12,
sm: 14,
md: 16,
lg: 18,
xl: 24,
xxl: 32,
},
weights: {
normal: '400' as const,
medium: '500' as const,
semibold: '600' as const,
bold: '700' as const,
},
}
export const borderRadius = {
sm: 4,
md: 8,
lg: 12,
full: 9999,
}
export const shadows = {
sm: {
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.05,
shadowRadius: 2,
elevation: 1,
},
md: {
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.1,
shadowRadius: 4,
elevation: 3,
},
lg: {
shadowColor: '#000',
shadowOffset: { width: 0, height: 4 },
shadowOpacity: 0.15,
shadowRadius: 8,
elevation: 5,
},
}
---
Identify users - Docs
Linking events to specific users enables you to build a full picture of how they're using your product across different sessions, devices, and platforms.
This is straightforward to do when capturing backend events, as you associate events to a specific user using a distinct_id, which is a required argument.
However, in the frontend of a web or mobile app, a distinct_id is not a required argument — PostHog's SDKs will generate an anonymous distinct_id for you automatically and you can capture events anonymously, provided you use the appropriate configuration.
To link events to specific users, call identify:
PostHog AI
Web
posthog.identify(
'distinct_id', // Replace 'distinct_id' with your user's unique identifier
{ email: 'max@hedgehogmail.com', name: 'Max Hedgehog' } // optional: set additional person properties
);Android
PostHog.identify(
distinctId = distinctID, // Replace 'distinctID' with your user's unique identifier
// optional: set additional person properties
userProperties = mapOf(
"name" to "Max Hedgehog",
"email" to "max@hedgehogmail.com"
)
)iOS
PostHogSDK.shared.identify("distinct_id", // Replace "distinct_id" with your user's unique identifier
userProperties: ["name": "Max Hedgehog", "email": "max@hedgehogmail.com"]) // optional: set additional person propertiesReact Native
posthog.identify('distinct_id', { // Replace "distinct_id" with your user's unique identifier
email: 'max@hedgehogmail.com', // optional: set additional person properties
name: 'Max Hedgehog'
})Dart
await Posthog().identify(
userId: 'distinct_id', // Replace "distinct_id" with your user's unique identifier
userProperties: {
email: "max@hedgehogmail.com", // optional: set additional person properties
name: "Max Hedgehog"
});Events captured after calling identify are identified events and this creates a person profile if one doesn't exist already.
Due to the cost of processing them, anonymous events can be up to 4x cheaper than identified events, so it's recommended you only capture identified events when needed.
How identify works
When a user starts browsing your website or app, PostHog automatically assigns them an anonymous ID, which is stored locally.
Provided you've configured persistence to use cookies or localStorage, this enables us to track anonymous users – even across different sessions.
By calling identify with a distinct_id of your choice (usually the user's ID in your database, or their email), you link the anonymous ID and distinct ID together.
Thus, all past and future events made with that anonymous ID are now associated with the distinct ID.
This enables you to do things like associate events with a user from before they log in for the first time, or associate their events across different devices or platforms.
Using identify in the backend
Although you can call identify using our backend SDKs, it is used most in frontends. This is because there is no concept of anonymous sessions in the backend SDKs, so calling identify only updates person profiles.
Best practices when using identify
1\. Call identify as soon as you're able to
In your frontend, you should call identify as soon as you're able to.
Typically, this is every time your app loads for the first time, and directly after your users log in.
This ensures that events sent during your users' sessions are correctly associated with them.
You only need to call identify once per session, and you should avoid calling it multiple times unnecessarily.
If you call identify multiple times with the same data without reloading the page in between, PostHog will ignore the subsequent calls.
2\. Use unique strings for distinct IDs
If two users have the same distinct ID, their data is merged and they are considered one user in PostHog. Two common ways this can happen are:
- Your logic for generating IDs does not generate sufficiently strong IDs and you can end up with a clash where 2 users have the same ID.
- There's a bug, typo, or mistake in your code leading to most or all users being identified with generic IDs like
null,true, ordistinctId.
PostHog also has built-in protections to stop the most common distinct ID mistakes.
3\. Reset after logout
If a user logs out on your frontend, you should call reset() to unlink any future events made on that device with that user.
This is important if your users are sharing a computer, as otherwise all of those users are grouped together into a single user due to shared cookies between sessions.
We strongly recommend you call `reset` on logout even if you don't expect users to share a computer.
You can do that like so:
PostHog AI
Web
posthog.reset()iOS
PostHogSDK.shared.reset()Android
PostHog.reset()React Native
posthog.reset()Dart
Posthog().reset()If you also want to reset the device_id so that the device will be considered a new device in future events, you can pass true as an argument:
Web
PostHog AI
posthog.reset(true)4\. Person profiles and properties
You'll notice that one of the parameters in the identify method is a properties object.
This enables you to set person properties.
Whenever possible, we recommend passing in all person properties you have available each time you call identify, as this ensures their person profile on PostHog is up to date.
Person properties can also be set being adding a $set property to a event capture call.
See our person properties docs for more details on how to work with them and best practices.
5\. Use deep links between platforms
We recommend you call identify as soon as you're able, typically when a user signs up or logs in.
This doesn't work if one or both platforms are unauthenticated. Some examples of such cases are:
- Onboarding and signup flows before authentication.
- Unauthenticated web pages redirecting to authenticated mobile apps.
- Authenticated web apps prompting an app download.
In these cases, you can use a deep link on Android and universal links on iOS to identify users.
1. Use posthog.get_distinct_id() to get the current distinct ID. Even if you cannot call identify because the user is unauthenticated, this will return an anonymous distinct ID generated by PostHog. 2. Add the distinct ID to the deep link as query parameters, along with other properties like UTM parameters. 3. When the user is redirected to the app, parse the deep link and handle the following cases:
- The user is already authenticated on the mobile app. In this case, call `posthog.alias()` with the distinct ID from the web. This associates the two distinct IDs as a single person.
- The user is unauthenticated. In this case, call `posthog.identify()` with the distinct ID from the web. Events will be associated with this distinct ID.
As long as you associate the distinct IDs with posthog.identify() or posthog.alias(), you can track events generated across platforms.
Further reading
- Identifying users docs
- How person processing works
- An introductory guide to identifying users in PostHog
Community questions
Ask a question
Was this page useful?
HelpfulCould be better
React Native - Docs
Installation
Our React Native enables you to integrate PostHog with your React Native project. For React Native projects built with Expo, there are no mobile native dependencies outside of supported Expo packages.
To install, add the posthog-react-native package to your project as well as the required peer dependencies.
Expo apps
Terminal
PostHog AI
npx expo install posthog-react-native expo-file-system expo-application expo-device expo-localizationReact Native apps
Terminal
PostHog AI
yarn add posthog-react-native @react-native-async-storage/async-storage react-native-device-info react-native-localize
# or
npm i -s posthog-react-native @react-native-async-storage/async-storage react-native-device-info react-native-localizeReact Native Web and macOS
If you're using React Native Web or React Native macOS, do not use the expo-file-system package since the Web and macOS targets aren't supported, use the @react-native-async-storage/async-storage package instead.
Configuration
With the PosthogProvider
The recommended way to set up PostHog for React Native is to use the PostHogProvider. This utilizes the Context API to pass the PostHog client around, and enables autocapture.
To set up PostHogProvider, add it to your App.js or App.ts file:
App.js
PostHog AI
// App.(js|ts)
import { usePostHog, PostHogProvider } from 'posthog-react-native'
...
export function MyApp() {
return (
<PostHogProvider apiKey="<ph_project_token>" options={{
// usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com'
host: 'https://us.i.posthog.com',
}}>
<MyComponent />
</PostHogProvider>
)
}Then you can access PostHog using the usePostHog() hook:
React Native
PostHog AI
const MyComponent = () => {
const posthog = usePostHog()
useEffect(() => {
posthog.capture("event_name")
}, [posthog])
}Without the PosthogProvider
If you prefer not to use the provider, you can initialize PostHog in its own file and import the instance from there:
posthog.ts
PostHog AI
import PostHog from 'posthog-react-native'
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'
})Then you can access PostHog by importing your instance:
React Native
PostHog AI
import { posthog } from './posthog'
export function MyApp1() {
useEffect(() => {
posthog.capture('event_name')
}, [])
return <View>Your app code</View>
}You can even use this instance with the PostHogProvider:
React Native
PostHog AI
import { posthog } from './posthog'
export function MyApp() {
return <PostHogProvider client={posthog}>{/* Your app code */}</PostHogProvider>
}Set up a reverse proxy (recommended)
We recommend setting up a reverse proxy, so that events are less likely to be intercepted by tracking blockers.
We have our own managed reverse proxy service, which is free for all PostHog Cloud users, routes through our infrastructure, and makes setting up your proxy easy.
If you don't want to use our managed service then there are several other options for creating a reverse proxy, including using Cloudflare, AWS Cloudfront, and Vercel.
Grouping products in one project (recommended)
If you have multiple customer-facing products (e.g. a marketing website + mobile app + web app), it's best to install PostHog on them all and group them in one project.
This makes it possible to track users across their entire journey (e.g. from visiting your marketing website to signing up for your product), or how they use your product across multiple platforms.
Add IPs to Firewall/WAF allowlists (recommended)
For certain features like heatmaps, your Web Application Firewall (WAF) may be blocking PostHog’s requests to your site. Add these IP addresses to your WAF allowlist or rules to let PostHog access your site.
EU: 3.75.65.221, 18.197.246.42, 3.120.223.253
US: 44.205.89.55, 52.4.194.122, 44.208.188.173
These are public, stable IPs used by PostHog services (e.g., Celery tasks for snapshots).
Configuration options
You can further customize how PostHog works through its configuration on initialization.
| Attribute | Description |
|---|---|
| hostType: StringDefault: https://us.i.posthog.com | PostHog API host (usually https://us.i.posthog.com by default or https://eu.i.posthog.com). Host is optional if you use https://us.i.posthog.com. |
| flushAtType: NumberDefault: 20 | The number of events to queue before sending to PostHog (flushing). |
| flushIntervalType: NumberDefault: 10000 | The interval in milliseconds between periodic flushes. |
| maxBatchSizeType: NumberDefault: 100 | The maximum number of queued messages to be flushed as part of a single batch (must be higher than flushAt). |
| maxQueueSizeType: NumberDefault: 1000 | The maximum number of cached messages either in memory or on the local storage (must be higher than flushAt). |
| disabledType: BooleanDefault: false | If set to true, the SDK is essentially disabled (useful for local environments where you don't want to track anything). |
| defaultOptInType: BooleanDefault: true | If set to false, the SDK will not track until the optIn() function is called. |
| sendFeatureFlagEventType: BooleanDefault: true | Whether to track that getFeatureFlag was called (used by experiments). |
| preloadFeatureFlagsType: BooleanDefault: true | Whether to load feature flags when initialized or not. |
| bootstrapType: ObjectDefault: {} | An object containing the distinctId, isIdentifiedId, featureFlags, and featureFlagPayloads keys. distinctId is a string, and featureFlags and featureFlagPayloads are objects of key-value pairs. Used to ensure data is available as soon as the SDK loads. |
| fetchRetryCountType: NumberDefault: 3 | How many times HTTP requests will be retried. |
| fetchRetryDelayType: NumberDefault: 3000 | The delay between HTTP request retries. |
| requestTimeoutType: NumberDefault: 10000 | Timeout in milliseconds for any calls. |
| featureFlagsRequestTimeoutMsType: NumberDefault: 10000 | Timeout in milliseconds for feature flag calls. |
| sessionExpirationTimeSecondsType: NumberDefault: 1800 | For session analysis, how long before a session expires (defaults to 30 minutes). |
| persistenceType: StringDefault: 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. |
| customAppPropertiesType: Object or FunctionDefault: null | Allows you to provide your own implementation of the common information about your App or a function to modify the default App properties generated. |
| customStorageType: ObjectDefault: null | Allows 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. If persistence is set to memory, this option is ignored. |
| captureAppLifecycleEventsType: BooleanDefault: false | Captures app lifecycle events such as Application Installed, Application Updated, Application Opened, Application Became Active, and Application Backgrounded. By default, this is false. |
| disableGeoipType: BooleanDefault: false | When true, disables automatic GeoIP resolution for events and feature flags. |
| enableSessionReplayType: BooleanDefault: false | Enable Recording of Session replay for Android and iOS. |
| sessionReplayConfigType: ObjectDefault: null | Session replay configuration. See the replay install docs for more details. |
| enablePersistSessionIdAcrossRestartType: BooleanDefault: false | When true, persists the $session_id across app restarts. If false, $session_id always resets on app restart. |
| evaluationContextsType: Array of StringsDefault: undefined | Evaluation context tags that constrain which feature flags are evaluated. When set, only flags with matching evaluation context tags (or no evaluation context tags) will be returned. This helps reduce unnecessary flag evaluations and improves performance. See evaluation contexts documentation for more details. Available in version 4.8.0+. The legacy parameter evaluationEnvironments (version 4.7.2+) is also supported for backward compatibility. |
| before_sendType: FunctionDefault: undefined | A callback function that is called before each event is sent to PostHog. You can use it to modify, filter, or suppress events. Return null to drop the event, or return the modified event to send it. See customizing exception capture for details. |
Capturing events
You can send custom events using capture:
React Native
PostHog AI
posthog.capture('user_signed_up')Tip: We recommend using a[object] [verb]format for your event names, where[object]is the entity that the behavior relates to, and[verb]is the behavior itself. For example,project created,user signed up, orinvite sent.
Setting event properties
Optionally, you can include additional information with the event by including a properties object:
React Native
PostHog AI
posthog.capture('user_signed_up', {
login_type: "email",
is_free_trial: true
})Capturing screen views
With @react-navigation/native and autocapture:
When using @react-navigation/native v6 or lower, screen tracking is automatically captured if the `autocapture` property is used in the PostHogProvider:
It is important that the PostHogProvider is configured as a child of the NavigationContainer:
React Native
PostHog AI
// App.(js|ts)
import { PostHogProvider } from 'posthog-react-native'
import { NavigationContainer } from '@react-navigation/native'
export function App() {
return (
<NavigationContainer>
<PostHogProvider apiKey="<ph_project_token>" autocapture>
{/* Rest of app */}
</PostHogProvider>
</NavigationContainer>
)
}When using @react-navigation/native v7 or higher, screen tracking has to be manually captured:
React Native
PostHog AI
// App.(js|ts)
import { PostHogProvider } from 'posthog-react-native'
import { NavigationContainer } from '@react-navigation/native'
// Using `PostHogProvider` is optional, but needed if you want to capture touch events automatically with the `captureTouches` option.
export function App() {
return (
<NavigationContainer>
<PostHogProvider apiKey="<ph_project_token>" autocapture={{
captureScreens: false, // Screen events are handled differently for v7 and higher
captureTouches: true,
}}>
{/* Rest of app */}
</PostHogProvider>
</NavigationContainer>
)
}Check out and set it up the official way for Screen tracking for analytics.
Then call the screen method within the trackScreenView method.
React Native
PostHog AI
const posthog = usePostHog() // use the usePostHog hook if using the PostHogProvider or your own custom posthog instance
// you can read the params from `getCurrentRoute()`
posthog.screen(currentRouteName, params)With react-native-navigation and autocapture:
First, simplify the wrapping of your screens with a shared PostHogProvider:
React Native
PostHog AI
import PostHog, { PostHogProvider } from 'posthog-react-native'
import { Navigation } from 'react-native-navigation';
export const posthog = new PostHog('<ph_project_token>');
export const SharedPostHogProvider = (props: any) => {
return (
<PostHogProvider client={posthog} autocapture={{
captureScreens: false, // Screen events are handled differently for react-native-navigation
captureTouches: true,
}}>
{props.children}
</PostHogProvider>
);
};Then, every screen needs to be wrapped with this provider if you want to capture touches or use the usePostHog() hook
React Native
PostHog AI
export const MyScreen = () => {
return (
<SharedPostHogProvider>
<View>
...
</View>
</SharedPostHogProvider>
);
};
Navigation.registerComponent('Screen', () => MyScreen);
Navigation.events().registerAppLaunchedListener(async () => {
posthog.initReactNativeNavigation({
navigation: {
// (Optional) Set the name based on the route. Defaults to the route name.
routeToName: (name, properties) => name,
// (Optional) Tracks all passProps as properties. Defaults to undefined
routeToProperties: (name, properties) => properties,
},
captureScreens: true,
});
});With expo-router:
Check out and set it up the official way for Screen tracking for analytics.
Then call the screen method within the useEffect callback.
React Native
PostHog AI
const posthog = usePostHog() // use the usePostHog hook if using the PostHogProvider or your own custom posthog instance
posthog.screen(pathname, params)Manually capturing screen capture events
If you prefer not to use autocapture, you can manually capture screen views by calling posthog.screen(). This function requires a name. You may also pass in an optional properties object.
JavaScript
PostHog AI
posthog.screen('dashboard', {
background: 'blue',
hero: 'superhog',
})Autocapture
PostHog autocapture can automatically track the following events for you:
- Application Opened - when the app is opened from a closed state
- Application Became Active - when the app comes to the foreground (e.g. from the app switcher)
- Application Backgrounded - when the app is sent to the background by the user
- Application Installed - when the app is installed.
- Application Updated - when the app is updated.
- $screen - when the user navigates (if using
@react-navigation/native(v6 or lower) orreact-native-navigation), check out the capturing screen views section - $autocapture - touch events when the user interacts with the screen
- $exception - when the app throws exceptions.
⚠️ React Navigation v7 users
>
React Navigation v7 restricts navigation hooks (such as useNavigationState) to components rendered inside a Screen that belongs to a Navigator.>
Because of this change, automatic screen tracking may throw errors if PostHog is initialized outside a screen context. This commonly affects apps upgrading from React Navigation v6 to v7.
>
For React Navigation v7, we recommend disabling automatic screen capture for screens and manually calling posthog.screen() inside each screen component. See the Capturing screen views section below.With autocapture, all touch events for children of PosthogProvider are tracked, capturing a snapshot of the view hierarchy at that point. This enables you to create insights in PostHog without having to add custom events.
PostHog will try to generate a sensible name for the touched element based on the React component displayName or name. If you prefer, you can set your own name using the ph-label prop:
React Native
PostHog AI
<View ph-label="my-special-label"></View>Autocapture configuration
React Native
PostHog AI
<PostHogProvider apiKey="<ph_project_token>" autocapture={{
captureTouches: true,
captureScreens: true,
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:
React Native
PostHog AI
<View ph-no-capture>Sensitive view here</View>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
React Native
PostHog AI
posthog.identify('distinctID',
{ // ($set):
email: 'user@posthog.com',
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`
React Native
PostHog AI
posthog.identify('distinctID',
{
$set: {
email: 'user@posthog.com',
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.
React Native
PostHog AI
// 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
JavaScript
PostHog AI
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.
JavaScript
PostHog AI
posthog.capture('some_event', { $set_once: { userProperty: 'value' } })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:
JavaScript
PostHog AI
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:
JavaScript
PostHog AI
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-out users from data capture. To do this, there are two options:
1. Opt users out by default by setting opt_out_capturing_by_default to true in your PostHog config:
JavaScript
PostHog AI
posthog.init('<ph_project_token>', {
opt_out_capturing_by_default: true,
});2. Opt users out on a per-person basis by calling opt_out_capturing():
JavaScript
PostHog AI
posthog.opt_out_capturing()Similarly, you can opt users in:
JavaScript
PostHog AI
posthog.opt_in_capturing()To check if a user is opted out:
JavaScript
PostHog AI
posthog.has_opted_out_capturing()Flush
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 configure the flush interval. By default we flush all events after 30 seconds, no matter how many events have gathered.
You can also manually flush the queue. If a flush is already 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
maxQueueSizein 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 outIf 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
Related skills
FAQ
What does integration-expo do?
integration-expo is a Claude Code skill for ai & agent building.
When should I use integration-expo?
When you need to helps with ai & agent building tasks during AI-assisted development., or when integration-expo is a claude code skill for ai & agent building.
What are the main capabilities?
integration-expo; AI & Agent Building; AI-coding skill.