mcpField
C
clerk-expo-patterns

clerk-expo-patterns

github.com/clerk開発896.8k 回インストール今日更新
リポジトリ

clerk-expo-patterns について

Clerk を使う Expo 開発者向けの実装パターン集です。トークンの永続化、OAuth ディープリンク、画面保護、組織切り替えなどを扱います。

主な機能

  1. 01安全なトークンキャッシュ設定
  2. 02OAuth ディープリンク設定
  3. 03Expo Router の画面保護
  4. 04プッシュ通知のユーザーデータパターン
  5. 05認証・組織コンポーザブル

活用シーン

  1. 01アプリ再起動後のセッション維持
  2. 02Google、Apple、GitHub OAuth の設定
  3. 03サインイン必須画面へのアクセス制限
  4. 04アプリ内での組織切り替え

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/clerk/skills --skill clerk-expo-patterns

インストール後、Claude Code で/clerk-expo-patternsを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

evals/
evals.json
references/
oauth-deep-linking.md
protected-routes.md
push-notifications.md
token-storage.md
templates/expo-basic-auth/
app.json
package.json
tsconfig.json
templates/expo-basic-auth/app/
_layout.tsx
templates/expo-basic-auth/app/(auth)/
_layout.tsx
templates/expo-basic-auth/app/(home)/
_layout.tsx
index.tsx

詳細

Expo パターン

SDK:@clerk/expo v3 以降。Expo 53 以降、React Native 0.73 以降が必要です。

必要な情報は?

タスクリファレンス
SecureStore でトークンを永続化するreferences/token-storage.md
OAuth(Google、Apple、GitHub)references/oauth-deep-linking.md
Expo Router で画面を保護するreferences/protected-routes.md
ユーザーデータを含むプッシュ通知references/push-notifications.md

基本的な考え方

Clerk はデフォルトでセッショントークンをメモリに保存します。ネイティブアプリでは、次のようになります。

  • SecureStore — デバイスのキーチェーンでトークンを暗号化します(本番環境での使用を推奨)
  • tokenCache — カスタムストレージを提供する<ClerkProvider>のプロパティです
  • useAuth — Web と同じ API で、どのコンポーネントでも使用できます
  • OAuth — useSSOと、app.jsonで設定したディープリンクスキームが必要です

最小限のセットアップ

app/_layout.tsx
import { ClerkProvider } from '@clerk/expo'
import { tokenCache } from '@clerk/expo/token-cache'
import { Stack } from 'expo-router'

const publishableKey = process.env.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY!

export default function RootLayout() {
  return (
    <ClerkProvider publishableKey={publishableKey} tokenCache={tokenCache}>
      <Stack />
    </ClerkProvider>
  )
}

重要:NEXT_PUBLIC_ではなく、EXPO_PUBLIC_CLERK_PUBLISHABLE_KEYを使用してください。node_modules内の環境変数は本番ビルドにインライン化されません。必ずpublishableKeyを明示的に渡してください。

組み込みトークンキャッシュ

import { tokenCache } from '@clerk/expo/token-cache'

これはkeychainAccessible: AFTER_FIRST_UNLOCKを指定してexpo-secure-storeを使用します。ピア依存関係をインストールしてください。

npx expo install expo-secure-store

認証フック

import { useAuth, useUser, useSignIn, useSignUp, useClerk } from '@clerk/expo'

export function ProfileScreen() {
  const { isSignedIn, userId, signOut } = useAuth()
  const { user } = useUser()

  if (!isSignedIn) return <Redirect href="/sign-in" />
  return (
    <View>
      <Text>{user?.fullName}</Text>
      <Button title="Sign Out" onPress={() => signOut()} />
    </View>
  )
}

OAuth フロー(Google)

import { useSSO } from '@clerk/expo'
import * as WebBrowser from 'expo-web-browser'

WebBrowser.maybeCompleteAuthSession()

export function GoogleSignIn() {
  const { startSSOFlow } = useSSO()

  const handlePress = async () => {
    try {
      const { createdSessionId, setActive } = await startSSOFlow({
        strategy: 'oauth_google',
        redirectUrl: 'myapp://oauth-callback',
      })
      if (createdSessionId) await setActive!({ session: createdSessionId })
    } catch (err) {
      console.error(err)
    }
  }

  return <Button title="Continue with Google" onPress={handlePress} />
}

組織の切り替え

import { useOrganization, useOrganizationList } from '@clerk/expo'

export function OrgSwitcher() {
  const { organization } = useOrganization()
  const { setActive, userMemberships } = useOrganizationList()

  return (
    <View>
      <Text>Current: {organization?.name ?? 'Personal'}</Text>
      {userMemberships.data?.map(mem => (
        <Button
          key={mem.organization.id}
          title={mem.organization.name}
          onPress={() => setActive({ organization: mem.organization.id })}
        />
      ))}
    </View>
  )
}

よくある問題

症状原因解決方法
本番環境でpublishableKeyが未定義EXPO_PUBLIC_なしで環境変数を使用しているEXPO_PUBLIC_CLERK_PUBLISHABLE_KEYに名前を変更する
アプリの再起動後にトークンが失われるtokenCacheがない@clerk/expo/token-cacheのtokenCacheを渡す
OAuth リダイレクトが機能しないapp.jsonにスキームがない"scheme": "myapp"をapp.jsonに追加する
WebBrowser.maybeCompleteAuthSession呼び出されていないOAuth コールバックスクリーンのトップレベルで呼び出す
useSSOが見つからない古いバージョンの@clerk/expov3 以降ではuseOAuthがuseSSOに置き換えられました

インポート一覧

項目インポート元
ClerkProvider@clerk/expo
tokenCache@clerk/expo/token-cache
useAuth、useUser、useSignIn@clerk/expo
useSSO@clerk/expo
useOrganization、useOrganizationList@clerk/expo

関連項目

  • clerk-setup - Clerk の初期インストール
  • clerk-custom-ui - カスタムフローと外観
  • clerk-orgs - B2B 組織

ドキュメント

Expo SDK

コメント