This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.

使用 PostHog

关于安装和配置 PostHog 用于产品分析、会话回放和错误跟踪的指南。

Android
iOS

PostHog 是一个具有会话回放、功能标志和错误跟踪的产品分析平台。

EAS CLI 集成自动化了标准的 PostHog React Native 设置:安装 SDK、创建 PostHog 组织和项目,以及配置环境变量。你也可以手动设置并使用本指南的其他部分而无需更改。

🌐 The EAS CLI integration automates the standard PostHog React Native setup: installing the SDK, creating a PostHog organization and project, and configuring your environment variables. You can also set it up manually and use the rest of this guide unchanged.

先决条件

3 要求

1.

Expo 账户

注册一个 Expo 账号

2.

EAS 命令行接口
使用 npm install -g eas-cli 全局安装 EAS CLI。

3.

Expo 项目已链接到 EAS

创建一个 Expo 项目并使用 eas init 将其链接到 EAS。

你将学到什么

🌐 What you'll learn

本指南涵盖了将 PostHog 集成到你的 Expo 项目中:

🌐 This guide covers integrating PostHog with your Expo project:

安装并配置 PostHog

🌐 Install and configure PostHog

1

运行 connect 命令

🌐 Run the connect command

在你的项目目录中运行以下命令:

🌐 Run the following command in your project directory:

Terminal
eas integrations:posthog:connect

这个命令:

🌐 This command:

  • PostHog 地区 的提示(美国或欧盟)。地区会设置你的数据驻留位置,连接后无法更改。
  • 为你创建一个 PostHog 组织和项目,或者如果你已经连接过,则重用现有的。如果你的电子邮箱已经有 PostHog 账户,connect 会打开你的浏览器以批准关联,然后继续。
  • 询问要设置哪些功能:一个多选框,包括 分析会话回放错误跟踪,默认全部启用。
  • 如果你启用错误跟踪,系统会提示你粘贴 PostHog 个人 API 密钥。在 PostHog 中的 设置 → 个人 API 密钥 下创建一个,使用“Source map upload”预设。(非交互式地,通过 --posthog-cli-api-key 传递它。)
  • 安装 PostHog SDK 和所需的 Expo 模块(如果你保留会话回放功能,还包括会话回放包)。
  • posthog-react-native/expo 配置插件添加到你的应用配置中。该插件连接 PostHog 的 SDK、会话回放和错误符号化所依赖的原生模块。它会为你编辑静态 应用配置 文件,但无法编辑 动态应用配置,因此会打印出插件条目以供你添加。
  • EXPO_PUBLIC_POSTHOG_API_KEYEXPO_PUBLIC_POSTHOG_HOST 写入 .env.local,并写入你在生产、预览和开发环境中的 EAS 环境变量。启用错误跟踪后,它还会将个人 API 密钥存储为 POSTHOG_CLI_API_KEY(具有 敏感可见性)以及公共的 POSTHOG_CLI_PROJECT_IDPOSTHOG_CLI_HOST

重新运行 connect 是安全的:它会重用你现有的组织和项目,并在覆盖环境变量前进行提示。

🌐 Re-running connect is safe: it reuses your existing organization and project and prompts before overwriting environment variables.

在 CI 中或非交互方式运行

使用 --region US--region EU 传递 --non-interactive(必填,因为数据驻留没有安全的默认值)。使用 --session-replay / --no-session-replay--error-tracking / --no-error-tracking 控制功能;错误跟踪还需要 --posthog-cli-api-key。使用 --overwrite 替换现有环境变量而无需提示。

🌐 Pass --non-interactive with --region US or --region EU (required, since there's no safe default for data residency). Control features with --session-replay / --no-session-replay and --error-tracking / --no-error-tracking; error tracking also needs --posthog-cli-api-key. Use --overwrite to replace existing environment variables without prompting.

2

将你的应用封装在 <PostHogProvider>

🌐 Wrap your app in <PostHogProvider>

在你的根布局文件(使用 Expo Router 的 src/app/_layout.tsx)中,用 <PostHogProvider> 封装你的应用,读取命令写入的环境变量中的密钥。查看 PostHog React Native 文档 了解所有选项,包括 错误追踪自动捕获

🌐 In your root layout file (src/app/_layout.tsx with Expo Router), wrap your app in <PostHogProvider>, reading the keys from the environment variables the command wrote. See the PostHog React Native docs for all options, including error-tracking autocapture.

src/app/_layout.tsx
import { PostHogProvider } from 'posthog-react-native'; import { Slot } from 'expo-router'; export default function RootLayout() { return ( <PostHogProvider apiKey={process.env.EXPO_PUBLIC_POSTHOG_API_KEY} options={{ host: process.env.EXPO_PUBLIC_POSTHOG_HOST, enableSessionReplay: false, // set to true if you enabled session replay // Capture JS exceptions (remove if you didn't enable error tracking): errorTracking: { autocapture: { uncaughtExceptions: true, unhandledRejections: true }, }, // disabled: __DEV__, // uncomment to stop sending events from development builds }}> <Slot /> </PostHogProvider> ); }

3

创建开发版本

🌐 Create a development build

会话重放和原生崩溃符号化需要开发构建,因为它们在 Expo Go 中无法使用。产品分析在 Expo Go 中可用。

🌐 Session replay and native crash symbolication require a development build since they don't work in Expo Go. Product analytics works in Expo Go.

Terminal
eas build --profile development

4

验证配置

🌐 Verify the configuration

添加一个临时按钮来捕获测试事件,运行你的开发版本,然后点击它:

🌐 Add a temporary button to capture a test event, run your development build, and tap it:

import { Button } from 'react-native'; import { usePostHog } from 'posthog-react-native'; // Inside a component const posthog = usePostHog(); <Button title="发送测试事件" onPress={() => posthog?.capture('test_event')} />

打开你的 PostHog 项目(根据你的地区,在 https://us.posthog.comhttps://eu.posthog.com)并确认事件是否到达。

🌐 Open your PostHog project (at https://us.posthog.com or https://eu.posthog.com, depending on your region) and confirm the event arrives.

错误跟踪

🌐 Error tracking

如果你启用了错误追踪,PostHog 会符号化两个不同的东西,并且你是独立设置它们的:

🌐 If you enabled error tracking, PostHog symbolicates two separate things, and you set them up independently:

  • JavaScript 源映射 用于 JS/TS 异常,包括 Hermes 字节码。请参阅 Source maps
  • 本地调试符号 用于本地 Android 和 iOS 崩溃(ProGuard/R8 映射和 dSYM 文件)。可选。参见 本地崩溃符号化

源映射

🌐 Source maps

源映射可以使 JavaScript 堆栈跟踪(包括 Hermes 字节码)指向你的原始源代码,而不是压缩后的输出。

🌐 Source maps make JavaScript stack traces (including Hermes bytecode) point to your original source instead of minified output.

首先,设置注入,以便每个包都被标记为上传。在项目根目录下将此内容添加到 metro.config.js(如果文件不存在,请创建它):

🌐 First, set up injection so each bundle is tagged for upload. Add this to metro.config.js in your project root (create the file if it doesn't exist):

metro.config.js
const { getPostHogExpoConfig } = require('posthog-react-native/metro'); const config = getPostHogExpoConfig(__dirname); module.exports = config;

如果你已经自定义了你的 Metro 配置(例如,使用 NativeWind 或在 monorepo 中),请将你的更改应用到 getPostHogExpoConfig 返回的 config 对象上,而不是自己调用 getDefaultConfig

🌐 If you already customize your Metro config (for example, with NativeWind or in a monorepo), apply your changes to the config object that getPostHogExpoConfig returns instead of calling getDefaultConfig yourself.

PostHog 的 CLI 使用 connect 设置的 POSTHOG_CLI_* 环境变量进行身份验证。要从你自己的机器上传,请改为运行 posthog-cli login

🌐 PostHog's CLI authenticates with the POSTHOG_CLI_* environment variables that connect set. To upload from your own machine, run posthog-cli login instead.

在 EAS Build 上posthog-react-native/expo 配置插件会在 Android(Gradle)和 iOS(Xcode)构建阶段自动上传源映射,因此不需要运行额外的命令。

关于 EAS 更新,空中更新只推送 JavaScript,因此每次更新后只需上传它们的源映射(本地符号在构建时已固定)。安装 PostHog 的 CLI,然后:

Terminal
eas update

posthog-cli hermes upload --directory dist

dist 是默认的 EAS 更新输出目录。

使用 EAS 工作流程自动上传

EAS Build 会在原生构建过程中上传源映射,因此构建工作流程不需要额外操作。对于更新,请添加一个在发布后重新导出并上传的任务:

🌐 EAS Build uploads source maps as part of the native build, so a build workflow needs nothing extra. For updates, add a job that re-exports and uploads after publishing:

.eas/workflows/publish-update.yml
name: Publish update on: push: branches: ['main'] jobs: publish_update: name: Publish update type: update params: channel: production upload_update_sourcemaps: name: Upload OTA source maps to PostHog needs: [publish_update] environment: production steps: - uses: eas/checkout - uses: eas/install_node_modules - name: Export JS bundle and source maps run: npx expo export --dump-sourcemap --output-dir dist - name: Upload source maps to PostHog run: npx --yes @posthog/cli@latest hermes upload --directory dist

environment: production 给作业提供了 POSTHOG_CLI_* 变量,这些变量由 connect 存储。getPostHogExpoConfig 注入的块 ID 让重新导出的源映射与更新发布的打包匹配。对于外部 CI,请自己设置 POSTHOG_CLI_* 变量。

本地崩溃符号化

🌐 Native crash symbolication

可选。本地崩溃(与 JavaScript 异常相对)需要在构建时上传本地调试符号。posthog-react-native/expo 插件在你选择加入后可以在 EAS Build 期间完成此操作:

🌐 Optional. Native crashes (as opposed to JavaScript exceptions) need native debug symbols uploaded at build time. The posthog-react-native/expo plugin can do this during EAS Build once you opt in:

app.json
{ "expo": { "plugins": [["posthog-react-native/expo", { "uploadNativeSymbols": true }]] } }

这是三个必需环节之一:构建时符号上传(如上所述)、在你的提供商中进行原生崩溃自动捕获,以及在你的 PostHog 项目中设置异常自动捕获。有关完整设置,请参阅 PostHog 的原生崩溃自动捕获

🌐 This is one of three pieces required end to end: build-time symbol upload (above), native crash autocapture in your provider, and the exception-autocapture setting in your PostHog project. See PostHog's native crash autocapture for the full setup.

发布标签

🌐 Release tagging

通过从 expo-updates 注册 超级属性,将每个捕获的事件映射回特定的空中更新:

🌐 Map each captured event back to a specific over-the-air update by registering super properties from expo-updates:

import { useEffect } from 'react'; import * as Updates from 'expo-updates'; import { usePostHog } from 'posthog-react-native'; function ReleaseTagger() { const posthog = usePostHog(); useEffect(() => { posthog?.register({ expo_update_id: Updates.updateId, expo_channel: Updates.channel, expo_runtime_version: Updates.runtimeVersion, }); }, [posthog]); return null; }

<PostHogProvider> 内渲染 <ReleaseTagger />。每个后续的 capture() 都具有这些属性,因此你可以在 PostHog 中按 expo_update_id 过滤或分组事件。

🌐 Render <ReleaseTagger /> inside <PostHogProvider>. Every subsequent capture() carries these properties, so you can filter or group events by expo_update_id in PostHog.

功能标记

🌐 Feature flags

一旦提供者设置完成,功能开关无需额外配置即可工作。请参阅 PostHog 的 React Native 功能开关引导 以避免应用启动时的网络往返。

🌐 Once the provider is set up, feature flags work with no extra configuration. See PostHog's feature flags for React Native and bootstrapping to avoid a network round-trip on app start.

管理整合

🌐 Manage the integration

稍后使用这些命令来管理集成:

🌐 Use these commands to manage the integration later:

Terminal
eas integrations:posthog:dashboard

eas integrations:posthog:disconnect

dashboard 打开你已关联的 PostHog 项目。disconnect 仅移除 Expo 端的链接。你的 PostHog 组织、项目和数据保持不变。

手动设置

🌐 Manual setup

connect 是标准 PostHog React Native 设置的快捷方式。要手动操作,请按照 PostHog 的 React Native 安装指南 进行,然后设置 EXPO_PUBLIC_POSTHOG_API_KEYEXPO_PUBLIC_POSTHOG_HOST(以及用于源映射的 POSTHOG_CLI_* 变量)。按照 步骤 2 所示,将你的应用封装在 <PostHogProvider> 中。有关源映射,请参阅 Source maps

故障排除

🌐 Troubleshooting

没有到达的事件

确认在你的构建使用的环境配置文件中已设置 EXPO_PUBLIC_POSTHOG_API_KEY。注意,disabled: __DEV__ 会阻止开发构建中的事件,因此请在预览或生产构建中测试(或者暂时移除它)。如果在 connect 写入你的环境变量时开发服务器已经在运行,请进行完整重新加载(而不是快速刷新),以便应用获取新的 EXPO_PUBLIC_* 值。

🌐 Confirm EXPO_PUBLIC_POSTHOG_API_KEY is set in the environment profile your build uses. Note that disabled: __DEV__ stops events from development builds, so test in a preview or production build (or remove it temporarily). If a dev server was already running when connect wrote your environment variables, do a full reload (not Fast Refresh) so the app picks up the new EXPO_PUBLIC_* values.

会话回放无法正常工作

会话回放需要开发构建,因为它无法在 Expo Go 上运行。如果你的项目使用连续本地生成,请使用 npx expo run:androidnpx expo run:ios 在本地创建,或使用 eas build --profile development

🌐 Session replay requires a development build since it doesn't work with Expo Go. If your project uses Continuous Native Generation, create one with npx expo run:android or npx expo run:ios locally, or with eas build --profile development.

源映射无法符号化

确认你的 metro.config.js 已使用 getPostHogExpoConfig 封装(参见 Source maps),并且设置了 POSTHOG_CLI_* 环境变量(启用错误跟踪时,connect 会添加它们)。对于空中更新,请确保在 eas update 之后运行了 posthog-cli hermes upload --directory dist

🌐 Confirm your metro.config.js is wrapped with getPostHogExpoConfig (see Source maps) and that the POSTHOG_CLI_* environment variables are set (connect adds them when error tracking is enabled). For over-the-air updates, make sure you ran posthog-cli hermes upload --directory dist after eas update.

你已经有一个 PostHog 帐号

如果你的电子邮件已有 PostHog 帐号,connect 会打开你的浏览器以批准将其链接到 Expo,然后继续。在它打开的浏览器标签中批准请求。如果你拒绝或关闭了该标签,请重新运行 connect

🌐 If your email already has a PostHog account, connect opens your browser to approve linking it to Expo, then continues. Approve the request in the browser tab it opens. If you declined or closed the tab, re-run connect.

了解更多

🌐 Learn more