Community编程与开发github.com

clerk/clerk-expo-patterns

Expo / React Native 模式与 Clerk — SecureStore 令牌缓存、OAuth 深度链接、原生 useAuth、Expo Router 受保护路由、带用户上下文的推送通知。

clerk-expo-patterns 是什么?

该技能提供了在 Expo / React Native 应用中使用 Clerk 进行身份验证的完整模式集合。核心功能包括:使用 SecureStore 安全存储令牌缓存,实现 OAuth 深度链接以支持原生社交登录,在原生环境中正确使用 useAuth Hook,以及基于 Expo Router 的受保护路由实现。此外,还涵盖了如何将用户上下文与推送通知关联,确保通知能准确推送至对应用户。该技能适用于所有使用 Clerk 作为身份认证服务的 React Native 和 Expo 项目,并针对 expo、clerk、SecureStore 等关键词自动触发。通过遵循这些模式,开发者可以快速构建安全、可靠的移动端认证流程,避免常见陷阱和平台差异问题。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/clerk/skills/tree/main/skills/clerk-expo-patterns

Installed? Explore more 编程与开发 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

clerk-expo-patterns 是做什么的?

Expo / React Native 模式与 Clerk — SecureStore 令牌缓存、OAuth 深度链接、原生 useAuth、Expo Router 受保护路由、带用户上下文的推送通知。触发关键词:expo clerk、clerk react native、SecureStore 令牌缓存、expo router 认证、OAuth 深度链接 clerk、移动认证 clerk。

概述

此技能提供了一套经过验证的模式,用于在 Expo / React Native 应用中集成 Clerk 身份认证。涵盖了从令牌安全存储到复杂 OAuth 流程的所有方面,确保你的移动应用认证体验既安全又流畅。

关键模式

1. SecureStore 令牌缓存

使用 Expo 的 SecureStore 安全存储 Clerk 的会话令牌,避免重复登录。

import * as SecureStore from 'expo-secure-store';
import { ClerkProvider } from '@clerk/clerk-expo';

const tokenCache = {
  async getToken(key: string) {
    try {
      return SecureStore.getItemAsync(key);
    } catch (err) {
      return null;
    }
  },
  async saveToken(key: string, value: string) {
    try {
      return SecureStore.setItemAsync(key, value);
    } catch (err) {
      return;
    }
  },
};

export default function App() {
  return (
    <ClerkProvider tokenCache={tokenCache} publishableKey={process.env.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY}>
      {/* 你的应用 */}
    </ClerkProvider>
  );
}

2. OAuth 深度链接

配置 OAuth 深度链接以支持在原生应用中使用社交登录(如 Google、Apple、GitHub)。

// app.json
{
  "expo": {
    "scheme": "yourapp",
    "plugins": [
      [
        "expo-router",
        {
          "scheme": "yourapp"
        }
      ]
    ]
  }
}
// 在 ClerkProvider 中配置深度链接
import { ClerkProvider, OAuthStrategy } from '@clerk/clerk-expo';

<ClerkProvider
  tokenCache={tokenCache}
  publishableKey={process.env.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY}
  // 自动处理深度链接
>

3. 原生 useAuth

在原生组件中正确使用 useAuth Hook。

import { useAuth } from '@clerk/clerk-expo';

function ProtectedComponent() {
  const { isSignedIn, userId, sessionId } = useAuth();

  if (!isSignedIn) {
    return null; // 或重定向到登录
  }

  return <Text>用户已登录: {userId}</Text>;
}

4. Expo Router 受保护路由

使用 Expo Router 和 Clerk 实现基于认证状态的路由保护。

// app/_layout.tsx
import { Redirect, Stack } from 'expo-router';
import { useAuth } from '@clerk/clerk-expo';

export default function AppLayout() {
  const { isSignedIn } = useAuth();

  if (!isSignedIn) {
    return <Redirect href="/sign-in" />;
  }

  return <Stack />;
}

5. 带用户上下文的推送通知

将推送通知与当前用户关联。

import { useAuth } from '@clerk/clerk-expo';
import * as Notifications from 'expo-notifications';

function usePushNotifications() {
  const { userId, getToken } = useAuth();

  useEffect(() => {
    if (!userId) return;

    async function registerForPushNotifications() {
      const { status } = await Notifications.requestPermissionsAsync();
      if (status !== 'granted') return;

      const token = await Notifications.getExpoPushTokenAsync();
      
      // 将 token 发送到后端,关联 userId
      await fetch('/api/register-push-token', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${await getToken()}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ userId, token: token.data }),
      });
    }

    registerForPushNotifications();
  }, [userId]);
}

触发说明

此技能在以下关键词出现时自动激活:

  • expo clerk
  • clerk react native
  • SecureStore token cache
  • expo router auth
  • OAuth deep link clerk
  • mobile auth clerk

平台支持

  • ✅ Expo SDK 49+
  • ✅ React Native 0.72+
  • ✅ Clerk SDK v4+
  • ✅ iOS & Android 原生
  • ✅ Web(通过 Expo for Web)

最佳实践

  1. 始终使用 SecureStore:不要依赖 AsyncStorage 存储令牌,它不安全。
  2. 测试深度链接:确保你的 app scheme 已正确配置。
  3. 处理用户注销:清除 SecureStore 中的令牌。
  4. 错误处理:在 getToken 和 saveToken 中添加 try-catch。
  5. 环境变量:使用 EXPO_PUBLIC_ 前缀暴露给客户端。

常见问题

Q: 为什么我的令牌没有持久化?

确保你的 tokenCache 实现没有错误,并且 SecureStore 在 iOS 模拟器和 Android 模拟器上都能正常工作。

Q: OAuth 深度链接在 iOS 上不起作用?

检查你的 Info.plist 是否包含正确的 URL scheme 配置。

Q: 如何在应用启动时检查认证状态?

Clerk 会自动从 SecureStore 恢复会话,无需手动检查。

相关资源

Individual skills in this repo

This repo contains 19 individual skills — each has its own dedicated page.

clerk/clerk

Clerk authentication router. Use when user asks about adding authentication, setting up Clerk, custom sign-in flows, Swift or native iOS auth, native Android auth, Next.js patterns, React patterns, Vue patterns, Nuxt patterns, Astro patterns, TanStack Start patterns, Expo patterns, React Router patterns, Chrome Extension patterns, organizations, billing, subscriptions, payments, pricing, plans, seat-based pricing, feature entitlements, syncing users, or testing. Automatically routes to the specific skill based on their task.

clerk/clerk-android

Implement Clerk authentication for native Android apps using Kotlin and Jetpack Compose with clerk-android source-guided patterns. Use for prebuilt AuthView/UserButton or custom API-driven auth flows. Do not use for Expo or React Native projects.

clerk/clerk-astro-patterns

Astro patterns with Clerk — middleware, SSR pages, island components, API routes, static vs SSR rendering. Triggers on: astro clerk, clerk astro middleware, astro protected page, clerk island component, astro API route auth, clerk astro SSR.

clerk/clerk-backend-api

Clerk Backend REST API explorer and executor. Browse tags, inspect endpoint schemas, and execute authenticated requests. Use when listing users, managing organizations, or calling any Clerk API endpoint.

clerk/clerk-billing

Clerk Billing for subscription management - render Clerk's PricingTable and in-app checkout drawer, configure subscription plans, seat-limit plans for B2B, feature entitlements with has(), and billing webhooks. Use for SaaS monetization, plan gating, checkout flows, trials, invoicing, and subscription lifecycle management.

clerk/clerk-chrome-extension-patterns

Chrome Extension auth with @clerk/chrome-extension -- popup/sidepanel setup, syncHost for OAuth/SAML via web app, createClerkClient for service workers and headless extensions, stable CRX ID. Triggers on: Chrome extension auth, Plasmo clerk, popup sign-in, syncHost, background service worker token, createClerkClient, headless extension.

clerk/clerk-custom-ui

Custom authentication flows and component appearance - hooks (useSignIn, useSignUp), themes, colors, fonts, CSS. Use for custom sign-in/sign-up flows, appearance styling, visual customization, branding.

clerk/clerk-expo

Implement Clerk authentication for Expo and React Native apps using @clerk/expo source-guided patterns. Use for prebuilt AuthView/UserButton or custom hook-driven auth flows. Do not use for native iOS/Swift, native Android/Kotlin, or web framework projects.

clerk/clerk-nextjs-patterns

Advanced Next.js patterns - middleware, Server Actions, caching with Clerk.

clerk/clerk-nuxt-patterns

Nuxt 3 auth patterns with @clerk/nuxt - middleware, composables, server API routes, SSR. Triggers on: Nuxt auth, useAuth composable, clerkMiddleware Nuxt, server API Clerk, Nuxt route protection.

clerk/clerk-orgs

Clerk Organizations for B2B SaaS - create multi-tenant apps with org switching, role-based access, verified domains, and enterprise SSO. Use for team workspaces, RBAC, org-based routing, member management.

clerk/clerk-react-patterns

React SPA auth patterns with @clerk/react for Vite/CRA - ClerkProvider setup, useAuth/useUser/useClerk hooks, React Router protected routes, custom sign-in flows. Triggers on: Vite Clerk setup, React Router auth, useAuth hook, protected route, custom sign-in form React.

clerk/clerk-react-router-patterns

React Router v7 patterns with Clerk — rootAuthLoader, getAuth in loaders, clerkMiddleware, protected routes, SSR user data, org switching. Triggers on: react-router auth, rootAuthLoader, getAuth loader, react-router protected route, loader authentication, SSR auth react-router.

clerk/clerk-setup

Add Clerk authentication to any project by following the official quickstart guides.

clerk/clerk-swift

Implement Clerk authentication for native Swift and iOS apps using ClerkKit and ClerkKitUI source-guided patterns. Use for prebuilt AuthView or custom native flows. Do not use for Expo or React Native projects.

clerk/clerk-tanstack-patterns

TanStack React Start auth patterns with @clerk/tanstack-react-start - createServerFn, beforeLoad guards, loaders, Vinxi server. Triggers on: TanStack auth, createServerFn clerk, beforeLoad protection, TanStack Start middleware.

clerk/clerk-testing

E2E testing for Clerk apps. Use with Playwright or Cypress for auth flow tests.

clerk/clerk-vue-patterns

Vue 3 patterns with Clerk — composables (useAuth, useUser, useClerk, useOrganization), Vue Router guards, Pinia auth store integration. Triggers on: vue clerk, useAuth vue, clerk composables, vue router clerk guard, pinia auth clerk. For Nuxt, use clerk-nuxt-patterns instead.

clerk/clerk-webhooks

Clerk webhooks for real-time events and data syncing. Verify with verifyWebhook from the framework-specific package. Handle user, session, organization, billing, and payment events. Build event-driven features like database sync, notifications, and integrations.

相关技能