Chapter 125 · Integration Expo
Subchapter 125.5
references/EXAMPLE.mdMarkdown36 KBView on GitHub
Repository: https://github.com/PostHog/context-mill Path: basics/expo
A React Native Expo app demonstrating PostHog product analytics integration with modern React Native best practices.
$exception eventsbasics/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 templateFor 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.
Install dependencies:
cd basics/expo
npm installConfigure PostHog (optional):
cp .env.example .env
# Edit .env with your PostHog project tokenStart the development server:
npx expo start# Start development server
npx expo start
# Run on iOS Simulator
npx expo run:ios
# Run on Android Emulator
npx expo run:androidPostHog is configured in src/config/posthog.ts using environment variables from app.json:
import Constants from 'expo-constants'
const apiKey = Constants.expoConfig?.extra?.posthogProjectTokenEvents are captured with properties:
posthog.capture('burrito_considered', {
total_considerations: count,
username: user.username,
})Users are identified on login:
posthog.identify(username, {
$set: { username },
$set_once: { first_login_date: new Date().toISOString() },
})Manual screen tracking with Expo Router:
useEffect(() => {
posthog.screen(pathname, {
previous_screen: previousPathname.current,
})
}, [pathname])Manual exception capture:
posthog.capture('$exception', {
$exception_type: error.name,
$exception_message: error.message,
$exception_stack_trace_raw: error.stack,
})Automatic memoization is enabled via babel-plugin-react-compiler. No need for manual useMemo, useCallback, or React.memo.
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
}Enabled in app.json for better performance:
{
"expo": {
"newArchEnabled": true
}
}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 androidJ in Expo CLI to open Chrome DevToolsMIT
POSTHOG_PROJECT_TOKEN=phc_your_project_token_here
POSTHOG_HOST=https://us.i.posthog.com
legacy-peer-deps=true
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'],
},
}
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>
)
}
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
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
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
module.exports = function (api) {
api.cache(true)
return {
presets: ['babel-preset-expo'],
plugins: [
['babel-plugin-react-compiler'],
'react-native-reanimated/plugin', // Must be last
],
}
}
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
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
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)
}
},
}
/**
* 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,
},
}