clerk-react-patterns

tarafından clerk

React SPA auth kalıpları, Vite/CRA için @clerk/react ile - ClerkProvider

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

React SPA Patterns

This skill covers @clerk/react for Vite/CRA SPAs. For Next.js use clerk-nextjs-patterns. For TanStack Start use clerk-tanstack-patterns.

What Do You Need?

TaskReference
useAuth / useUser / useClerk hooksreferences/hooks.md
Protected routes with React Routerreferences/protected-routes.md
Custom sign-in / sign-up formsreferences/custom-flows.md
React Router v6/v7 integrationreferences/router-integration.md

References

ReferenceDescription
references/hooks.mduseAuth, isLoaded guard
references/protected-routes.mdProtectedRoute pattern
references/custom-flows.mduseSignIn, useSignUp flows
references/router-integration.mdReact Router v6/v7 setup

Setup

npm install @clerk/react

.env:

VITE_CLERK_PUBLISHABLE_KEY=pk_...

src/main.tsx:

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { ClerkProvider } from '@clerk/react'
import App from './App.tsx'

const PUBLISHABLE_KEY = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <ClerkProvider publishableKey={PUBLISHABLE_KEY}>
      <App />
    </ClerkProvider>
  </StrictMode>,
)

Mental Model

@clerk/react is client-only — there is no server-side auth(). All auth state comes from hooks.

  • isLoaded must be true before trusting isSignedIn — always guard on isLoaded
  • useClerk() gives access to signOut, openSignIn, openUserProfile and other methods
  • getToken() from useAuth() fetches the session JWT for API calls

Minimal Pattern

import { useAuth } from '@clerk/react'

export function Dashboard() {
  const { isLoaded, isSignedIn, userId } = useAuth()

  if (!isLoaded) return <div>Loading...</div>
  if (!isSignedIn) return <div>Please sign in</div>

  return <div>Hello {userId}</div>
}

Protected Route (React Router v6/v7)

import { Navigate, Outlet } from 'react-router-dom'
import { useAuth } from '@clerk/react'

export function ProtectedRoute() {
  const { isLoaded, isSignedIn } = useAuth()

  if (!isLoaded) return <div>Loading...</div>
  if (!isSignedIn) return <Navigate to="/sign-in" replace />

  return <Outlet />
}
<Routes>
  <Route element={<ProtectedRoute />}>
    <Route path="/dashboard" element={<Dashboard />} />
    <Route path="/settings" element={<Settings />} />
  </Route>
  <Route path="/sign-in" element={<SignIn />} />
</Routes>

Token for API Calls

import { useAuth } from '@clerk/react'

export function DataFetcher() {
  const { getToken } = useAuth()

  async function fetchData() {
    const token = await getToken()
    if (!token) return

    const res = await fetch('/api/data', {
      headers: { Authorization: `Bearer ${token}` },
    })
    return res.json()
  }

  return <button onClick={fetchData}>Load</button>
}

Common Pitfalls

SymptomCauseFix
isSignedIn is undefinedisLoaded is still falseAlways check isLoaded first
ClerkProvider missingProvider not at rootWrap <App> in main.tsx
Env var undefinedWrong Vite prefixUse VITE_CLERK_PUBLISHABLE_KEY, access via import.meta.env
Token is nullUser not signed inNull-check getToken() result
Sign-in component shows blankNo publishableKey on providerPass publishableKey explicitly

See Also

  • clerk-setup - Initial Clerk install
  • clerk-custom-ui - Custom flows & appearance
  • clerk-orgs - B2B organizations

Docs

React SDK

clerk tarafından daha fazla skill

mosaic
clerk
Work on Mosaic UI: styling a component with slot recipes (`defineSlotRecipe` / `useRecipe` / slots / variants), or building a flow — authoring a state machine…
clerk-billing
clerk
Abonelik yönetimi için Clerk Billing - Clerk'in PricingTable'ını render eder
clerk-nextjs-patterns
clerk
We need to translate the given English text into Turkish, preserving the name "clerk-nextjs-patterns" if it appears. The text is a description of an agent skill. We must not add any extra commentary, labels, or formatting. The translation should be accurate and natural in Turkish, keeping technical terms like "Next.js", "Clerk", "auth()", "useAuth()", "unstable_cache", "Server Actions", "API route", "HTTP status codes", "401", "403", "Core 2" as is. Also preserve "middleware", "authentication", "user-scoped caching", etc. but translate the surrounding words. The text: "Advanced Next.js patterns for authentication, middleware, Server Actions, and user-scoped caching with Clerk. Distinguishes server-side await auth() from client-side useAuth() hook; mixing them is a common breaking mistake Covers middleware strategies (public-first vs protected-first), API route protection, and proper HTTP status codes (401 vs 403) Includes user-scoped caching patterns with unstable_cache
clerk-expo-patterns
clerk
Expo / React Native desenleri Clerk ile — SecureStore token önbelleği, OAuth
changesets
clerk
Create or refresh a `.changeset/<slug>.md` for the current branch, or report that none is required. Triggers on "/changesets create", "add a changeset",…
clerk
clerk
clerk ikili dosyası, Clerk'in Arka Uç API'si ve Platform API'sine önceden kimlik doğrulaması yapılmış bir ağ geçididir ve ayrıca proje düzeyinde araçlar (kimlik doğrulama, bağlantı, ortam çekmeleri, örnek yapılandırması) içerir. Kullanıcı Clerk kaynağına dokunan bir şey sorduğunda, elle curl yazmak yerine önce clerk'ı kullanın.
clerk-cli
clerk
clerk binary, Clerk'in Backend API ve Platform API'sine önceden kimlik doğrulaması yapılmış bir ağ geçididir ve ayrıca proje düzeyinde araçlar (kimlik doğrulama, bağlantı, env çekme, örnek yapılandırması) içerir. Kullanıcı bir Clerk kaynağına dokunan herhangi bir şey sorduğunda, elle curl yazmak yerine önce clerk'a başvurun.
clerk-astro-patterns
clerk
Clerk ile Astro desenleri — middleware, SSR sayfaları, ada bileşenleri,