This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.
使用文员
学习如何在你的 Expo 和 React Native 项目中添加 Clerk 身份验证和用户管理。
Clerk 是一个认证和用户管理平台,提供注册、登录、多因素认证、社交登录、组织管理以及托管的用户数据库。@clerk/expo SDK 提供了 React 钩子、控制组件、托管认证,以及可以在 Android 上用 Jetpack Compose、在 iOS 上用 SwiftUI 渲染的预构建原生 UI 组件。
本指南向你展示如何安装 @clerk/expo,将你的应用封装在 <ClerkProvider> 中,以及选择最适合你项目的集成方式。它针对 @clerk/expo 4.x,支持 Expo SDK 54 及更高版本。
🌐 This guide shows you how to install @clerk/expo, wrap your app in <ClerkProvider>, and choose the integration approach that fits your project. It targets @clerk/expo 4.x, which supports Expo SDK 54 and later.
选择你的整合方法
🌐 Choose your integration approach
@clerk/expo 支持三种方法。选择一个符合你需求的即可。之后可以更改,无需重写你的应用。
信息
@clerk/expo/native中的原生 UI 组件目前处于测试阶段。它们在 Android 上使用 Jetpack Compose 渲染,在 iOS 上使用 SwiftUI 渲染,并将登录会话同步回 JavaScript SDK,因此所有@clerk/expo钩子(例如useAuth()和useUser())都保持同步。
先决条件
🌐 Prerequisites
4 要求
4 要求
安装并配置 Clerk
🌐 Install and configure Clerk
1
安装 @clerk/expo 和 expo-secure-store
🌐 Install @clerk/expo and expo-secure-store
使用 npx expo install 以使版本与你的 Expo SDK 匹配:
🌐 Use npx expo install so versions match your Expo SDK:
expo-secure-store 是一个同级依赖。Clerk 通过 @clerk/expo/token-cache 使用它来使用 iOS 密钥串和 Android 密钥库加密会话令牌。
对于托管身份验证,还需要安装 Clerk 用来打开浏览器身份验证会话的包:
🌐 For hosted authentication, also install the packages Clerk uses to open the browser authentication session:
如果你打算在自定义流程中添加原生的 Google 登录按钮,安装 @clerk/expo-google-signin 和 expo-crypto:
🌐 If you plan to add native Sign in with Google buttons to a custom flow, install @clerk/expo-google-signin and expo-crypto:
对于原生的“使用 Apple 登录”按钮,安装 expo-apple-authentication 和 expo-crypto 两个即可:
🌐 For native Sign in with Apple buttons, install both expo-apple-authentication and expo-crypto:
如果你只使用 @clerk/expo/native 中的 <AuthView />,你不需要任何这些额外的包,因为该组件会在内部处理社交登录流程。
🌐 You do not need any of these extra packages if you only use <AuthView /> from @clerk/expo/native, since the component handles social sign-in flows internally.
2
验证配置插件
🌐 Verify the config plugins
在你的 app 配置 中将 @clerk/expo 和 expo-secure-store 添加到 plugins 数组。如果你的项目使用静态 app.json 并且你是用 npx expo install 安装的包,Expo 已经帮你添加好了:
🌐 Add @clerk/expo and expo-secure-store to the plugins array in your app config. If your project uses a static app.json and you installed the packages with npx expo install, Expo has already added them:
@clerk/expo 插件会添加 Apple 登录权限(如果你的应用不使用,可以通过 appleSignIn: false 插件选项禁用),注册托管身份验证回调的 Android 意图过滤器,并应用底层 clerk-android SDK 所需的 Android 打包修复。如果你使用原生的 Google 登录按钮,也要同时添加 @clerk/expo-google-signin 插件。
🌐 The @clerk/expo plugin adds the Apple Sign In entitlement (disable it with the appleSignIn: false plugin option if your app doesn't use it), registers the Android intent filter for the hosted authentication callback, and applies the Android packaging fixes required by the underlying clerk-android SDK. If you use the native Sign in with Google buttons, also add the @clerk/expo-google-signin plugin alongside it.
托管认证的默认回调来自你应用配置中的 android.package 和 ios.bundleIdentifier 值。在创建生产构建之前,请在 Clerk 仪表板的 原生应用 页面上添加该应用,使用相同的 Android 包名和 iOS 打包标识,因为生产实例会根据注册的值验证回调。
🌐 Hosted authentication derives its default callback from the android.package and ios.bundleIdentifier values in your app config. Before you create a production build, add the app on the Native applications page in the Clerk Dashboard with the same Android package name and iOS bundle identifier, since production instances validate the callback against the registered values.
3
添加你的 Clerk 可发布密钥
🌐 Add your Clerk Publishable Key
从 Clerk 仪表板的 API keys 页面复制你的可发布密钥,然后将其添加到项目根目录下的 .env 文件中:
🌐 Copy your Publishable Key from the API keys page in the Clerk Dashboard, then add it to a .env file in the root of your project:
EXPO_PUBLIC_ 前缀是必需的,因为 Expo 会在构建时内联这些值,以便它们可以在你的 JavaScript 包中使用。Clerk 的可发布密钥是可以安全公开的。不要 将密钥放在 EXPO_PUBLIC_ 前缀下。
🌐 The EXPO_PUBLIC_ prefix is required because Expo inlines these values at build time so they are available in your JavaScript bundle. Clerk's Publishable Key is safe to expose. Do not put Secret Keys behind the EXPO_PUBLIC_ prefix.
4
将你的应用封装在 <ClerkProvider> 中
🌐 Wrap your app in <ClerkProvider>
在你的根布局文件(使用 Expo Router 的 src/app/_layout.tsx)中,将你的应用封装在 <ClerkProvider> 中并传入 Publishable Key。建议显式传入 tokenCache:
🌐 In your root layout file (src/app/_layout.tsx with Expo Router), wrap your app in <ClerkProvider> and pass the Publishable Key. Passing tokenCache explicitly is recommended:
在 Core 3 中,对于 Expo 应用,<ClerkProvider> 上需要 publishableKey。在生产环境的 React Native 构建中,node_modules 内的环境变量不会被内联,因此必须明确传递该属性。
🌐 In Core 3, publishableKey is required on <ClerkProvider> for Expo apps. Environment variables inside node_modules are not inlined during production React Native builds, so the prop must be passed explicitly.
@clerk/expo/token-cache 的 tokenCache 使用 expo-secure-store 在应用重启时保持用户会话。显式传递它可以使依赖更加清晰,并允许你以后替换自定义缓存实现。
添加身份验证
🌐 Add authentication
下一步取决于你选择了哪种方法。下面的选项卡显示了每种方法的最少代码。
🌐 The next step depends on which approach you chose. The tabs below show the minimum code for each.
托管身份验证会在你的应用上通过浏览器身份验证会话打开 Clerk 的 账户门户。用户可以完成你 Clerk 应用启用的任何登录或注册方式,SDK 会在你的应用中激活生成的会话。从 useHostedAuth() 钩子调用 startHostedAuth():
🌐 Hosted authentication opens Clerk's Account Portal in a browser authentication session over your app. Users can complete any sign-in or sign-up method enabled for your Clerk application, and the SDK activates the resulting session in your app. Call startHostedAuth() from the useHostedAuth() hook:
身份验证完成后,SDK 会关闭浏览器会话,激活新的会话,并用已登录的状态更新 useAuth()。浏览器不会保留单独的活动会话。
🌐 After authentication completes, the SDK closes the browser session, activates the new session, and updates useAuth() with the signed-in state. The browser doesn't retain a separate active session.
startHostedAuth() 默认会打开登录页面并接受 mode: 'sign-in' | 'sign-up'。当用户在未完成操作时关闭浏览器,它会以 null createdSessionId 方式结束;如果认证失败,则会抛出错误。
这种方法在 Expo Go 中有效,因为 Expo 提供了一个开发回调。在开发或生产构建中,回调是根据你的 iOS bundle identifier 或 Android 包名生成的,所以在更改任一标识符后,保持 @clerk/expo 配置插件在你的应用配置中,并重新构建原生项目。
🌐 This approach works in Expo Go, where Expo supplies a development callback. In a development or production build, the callback is derived from your iOS bundle identifier or Android package name, so keep the @clerk/expo config plugin in your app config and rebuild the native project after changing either identifier.
账户门户在浏览器中运行,所以社交登录使用每个提供商的网页OAuth流程,而不是本地流程。有关生产凭证要求和故障排除,请参阅托管认证指南。
🌐 Account Portal runs in a browser, so social sign-in uses each provider's web OAuth flow rather than the native one. See the hosted authentication guide for production credential requirements and troubleshooting.
<AuthView /> 提供了一个完整的原生登录和注册界面,可以处理邮箱、电话、通行密钥、多因素认证以及 Clerk 控制面板中启用的任何社交登录。它会在你的 React Native 视图层级中内嵌渲染,所以你可以把它放在模态框、路由或全屏视图中。下面的例子展示了如何在模态框中打开它:
用户登录后,本地会话会同步回 JavaScript SDK,因此 useAuth() 和 useUser() 会反映已登录状态。将 treatPendingAsSignedOut: false 传给 useAuth(),这样待处理的 会话任务 不会被当作已登出。
🌐 After the user signs in, the native session is synchronized back to the JavaScript SDK, so useAuth() and useUser() reflect the signed-in state. Pass treatPendingAsSignedOut: false to useAuth() so pending session tasks are not treated as signed out.
警告 保持包含
<AuthView />的<Modal>挂载在与你已登录和未登录内容相同的层级。如果你只在未登录内容中渲染它,认证状态在会话任务仍在进行时可能会发生变化,你的条件渲染会过早卸载模态框。
<AuthView /> 接受 mode="signIn" | "signUp" | "signInOrUp"(默认值)、一个控制原生关闭按钮的 isDismissible 布尔值,以及一个 onDismiss 回调。当用户必须先进行身份验证才能继续时,使用 isDismissible={false} 将其呈现为全屏视图,而不是模态窗口。
<UserButton /> 不需要任何属性。它会显示已登录用户的头像或名称首字母,点击后会打开原生的 <UserProfileView />,用户可以在其中管理个人信息、安全设置并退出登录。
<AuthView /> 会自动显示在 Clerk 仪表板中启用的任何社交登录按钮,并在内部处理登录流程,所以你不需要 expo-crypto 或原生登录钩子。原生 OAuth 仍然需要在 Clerk 仪表板和提供商控制台中设置凭据。否则,按钮会显示,但点击时会失败。请按照本页底部链接的 Clerk Google 登录和 Apple 登录指南操作。
这种方法需要开发构建,因为这些组件由原生模块支持:
🌐 This approach requires a development build because the components are backed by native modules:
使用 Core 3 钩子构建你自己的界面。这在 Expo Go 中可用。下面的示例使用 useSignUp() 构建一个带有邮箱验证码验证的邮箱和密码注册表单:
🌐 Build your own screens with the Core 3 hooks. This works in Expo Go. The following example uses useSignUp() to build an email and password sign-up form with email code verification:
在 Core 3 中,像 signUp.password() 和 signUp.verifications.verifyEmailCode() 这样的方法在遇到验证错误时会返回 { error },而不是抛出异常。当验证完成注册后,signUp.finalize() 会将其转换为活跃会话,并更新 useAuth() 为已登录状态。
🌐 In Core 3, methods such as signUp.password() and signUp.verifications.verifyEmailCode() return { error } instead of throwing for validation errors. When verification completes the sign-up, signUp.finalize() converts it into an active session and updates useAuth() with the signed-in state.
对应的登录流程使用 useSignIn(),其中 finalize() 接受一个 navigate 回调,这样你就可以在重定向之前处理 会话任务:
🌐 The corresponding sign-in flow uses useSignIn(), where finalize() accepts a navigate callback so you can handle session tasks before redirecting:
import { useSignIn } from '@clerk/expo'; import { type Href, useRouter } from 'expo-router'; export default function SignInScreen() { const { signIn } = useSignIn(); const router = useRouter(); const handleSignIn = async (emailAddress: string, password: string) => { const { error } = await signIn.password({ emailAddress, password }); if (error) { return; } if (signIn.status === 'complete') { await signIn.finalize({ navigate: ({ session, decorateUrl }) => { if (session?.currentTask) return; // let the session task layer handle it router.replace(decorateUrl('/') as Href); }, }); } }; // ... render your email and password fields }
要在你的自定义界面中添加原生的“使用 Google 登录”和“使用 Apple 登录”按钮,可以使用来自 @clerk/expo/google 的 useSignInWithGoogle() 钩子以及来自 @clerk/expo/apple 的 useSignInWithApple() 钩子。两者都返回一个启动方法(startGoogleAuthenticationFlow() 和 startAppleAuthenticationFlow()),调用后会返回 { createdSessionId, setActive }。
🌐 To add native Sign in with Google and Sign in with Apple buttons to your custom screens, use the useSignInWithGoogle() hook from @clerk/expo/google and the useSignInWithApple() hook from @clerk/expo/apple. Both return a start method (startGoogleAuthenticationFlow() and startAppleAuthenticationFlow()) that resolves with { createdSessionId, setActive }.
这两个 hooks 都使用了原生模块,所以它们需要开发版本和安装步骤中的相关包。useSignInWithGoogle() 还需要 @clerk/expo-google-signin 配置插件。在 iOS 上,根据 App Store 指南 4.8,任何提供第三方社交登录的应用也必须提供 Apple 登录。按照本页底部链接的 Clerk 指南,在 Clerk 控制面板和对应提供商的控制台中注册你的凭证。
🌐 Both hooks use native modules, so they require a development build and the packages from the install step. useSignInWithGoogle() also needs the @clerk/expo-google-signin config plugin. On iOS, App Store Guideline 4.8 requires that any app offering third-party social sign-in must also offer Sign in with Apple. Follow the Clerk guides linked at the bottom of this page to register your credentials in the Clerk Dashboard and the provider consoles.
读取已登录的用户
🌐 Read the signed-in user
在你的应用中的任何地方,使用 useUser() 和 useAuth() 来读取用户数据,另外使用 <Show> 和 useClerk() 来保护内容并登出:
🌐 Anywhere in your app, use useUser() and useAuth() to read user data, plus <Show> and useClerk() to protect content and sign out:
import { Show, useClerk, useUser } from '@clerk/expo'; import { Link } from 'expo-router'; import { Pressable, Text, View } from 'react-native'; export default function HomeScreen() { const { user } = useUser(); const { signOut } = useClerk(); return ( <View> <Show when="signed-in"> <Text>Hello, {user?.firstName ?? 'friend'}</Text> <Pressable onPress={() => signOut()}> <Text>Sign out</Text> </Pressable> </Show> <Show when="signed-out"> <Link href="/(auth)/sign-in"> <Text>Sign in</Text> </Link> </Show> </View> ); }
<Show> 替代了早期版本 SDK 中的传统 <SignedIn>、<SignedOut> 和 <Protect> 组件。它还接受 when={{ role: '...' }}、when={{ permission: '...' }} 及其他授权谓词。
运行应用
🌐 Run the app
对于托管认证和自定义流程的方法,运行以下命令并在 Expo Go 中打开项目:
🌐 For the hosted authentication and custom flow approaches, run the following command and open the project in Expo Go:
下一步
🌐 Next steps
为每种三种集成方法提供逐步设置说明,并附有 GitHub 上的配套仓库。
使用 Clerk 的账户门户从你的 Expo 应用中登录和注册用户,支持回调、取消处理和生产环境设置。
AuthView、UserButton 和 UserProfileView 的 API 参考,包括配置、主题和平台要求。
通过 Clerk 控制台和 Google Cloud 控制台,为 Android 和 iOS 设置原生的 Google 登录。
设置原生“使用 Apple 登录”以符合 App Store 指南 4.8。
在你的 Expo 应用中使用 Clerk 的 hooks 和 Show 组件来保护路由并访问用户数据。
配置生产凭证,允许列表移动单点登录重定向,并使用 EAS 构建发布。