clerk-tanstack-patterns

por clerk

Padrões de autenticação TanStack React Start com @clerk/tanstack-react-start

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

TanStack React Start Patterns

What Do You Need?

TaskReference
Protect routes with beforeLoadreferences/router-guards.md
Auth in createServerFnreferences/server-functions.md
Pass auth to loadersreferences/loaders.md
Configure Vite + Clerk middlewarereferences/server-setup.md

References

ReferenceDescription
references/router-guards.mdbeforeLoad auth redirect
references/server-functions.mdcreateServerFn with auth()
references/loaders.mdAuth context in loaders
references/server-setup.mdVite and request middleware setup

Setup

npm install @clerk/tanstack-react-start

.env:

VITE_CLERK_PUBLISHABLE_KEY=pk_...
CLERK_SECRET_KEY=sk_...

src/start.ts (request middleware):

import { clerkMiddleware } from '@clerk/tanstack-react-start/server'
import { createCsrfMiddleware, createStart } from '@tanstack/react-start'

const csrfMiddleware = createCsrfMiddleware({
  filter: (ctx) => ctx.handlerType === 'serverFn',
})

export const startInstance = createStart(() => {
  return {
    requestMiddleware: [csrfMiddleware, clerkMiddleware()],
  }
})

src/routes/__root.tsx — wrap with <ClerkProvider>:

import { ClerkProvider } from '@clerk/tanstack-react-start'

function RootDocument({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <ClerkProvider>{children}</ClerkProvider>
      </body>
    </html>
  )
}

Mental Model

TanStack Start uses the tanstackStart() Vite plugin. Register CSRF protection before Clerk request middleware in src/start.ts; auth then flows through two layers:

  1. Server layer — createServerFn + auth() from @clerk/tanstack-react-start/server
  2. Router layer — beforeLoad on route definitions, throws redirect for unauthenticated

Both layers are server-executed. Client hooks (useAuth, useUser) are React hooks for the browser side.

Minimal Pattern

import { createFileRoute, redirect } from '@tanstack/react-router'
import { createServerFn } from '@tanstack/react-start'
import { auth } from '@clerk/tanstack-react-start/server'

const authStateFn = createServerFn().handler(async () => {
  const { isAuthenticated, userId } = await auth()
  if (!isAuthenticated) {
    throw redirect({ to: '/sign-in' })
  }
  return { userId }
})

export const Route = createFileRoute('/dashboard')({
  beforeLoad: async () => await authStateFn(),
})

Common Pitfalls

SymptomCauseFix
auth() throws "without configuring the middleware"Missing clerkMiddleware in start.tsAdd it after CSRF middleware in requestMiddleware
redirect not thrownUsing return instead of throwthrow redirect(...) in TanStack
Wrong import for authMixing client/server importsServer: @clerk/tanstack-react-start/server
Loader context missing userIdNot passing from beforeLoadReturn from beforeLoad, access via context
ClerkProvider missingForgot root wrappingAdd to __root.tsx shell component

See Also

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

Docs

TanStack React Start SDK

Mais skills de clerk

clerk-testing
clerk
Utilitários de teste E2E para fluxos de autenticação do Clerk no Playwright e Cypress. Suporta ambos os frameworks Playwright e Cypress com padrões de configuração específicos (globalSetup para Playwright, comandos personalizados para Cypress). Fornece as utilidades clerkSetup() e setupClerkTestingToken() para inicializar ambientes de teste e ignorar a detecção de bots. Inclui persistência de storageState para reutilizar sessões autenticadas entre testes, reduzindo o tempo de execução. Requer chaves de API de teste ( pk_test_* ,...
clerk-swift
clerk
We need to translate the given text from English to Brazilian Portuguese. The text describes a skill called "clerk-swift" but the instruction says to not include the name unless it appears in the source text. The name "clerk-swift" does not appear in the source text, so we don't include it. The source text is: "Native Swift/iOS authentication using ClerkKit with prebuilt or custom auth flows. Supports two implementation modes: prebuilt AuthView components or fully custom native flows, selected based on project requirements Requires direct wiring of a valid Clerk publishable key in app configuration; does not use plist or environment file indirection by default Mandatory /v1/environment call after package install to determine feature availability (for example Apple Sign In support) based on..." We need to preserve product names, protocol names, URLs, numbers, technical terms. So "ClerkKit", "AuthView", "Clerk", "Apple Sign In", "/v1/environment" should remain as is. Also "plist" and "environment file" are
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
Gerenciamento de assinaturas do Clerk Billing - renderizar a PricingTable do Clerk
clerk-nextjs-patterns
clerk
Padrões avançados de Next.js para autenticação, middleware, Server Actions e cache com escopo de usuário usando Clerk. Diferencia o await auth() no lado do servidor do hook useAuth() no lado do cliente; misturá-los é um erro comum que quebra a aplicação. Aborda estratégias de middleware (público-primeiro vs protegido-primeiro), proteção de rotas de API e códigos de status HTTP adequados (401 vs 403). Inclui padrões de cache com escopo de usuário usando unstable_cache e proteção de Server Actions contra mutações não autorizadas. Fornece compatibilidade com Core 2...
clerk-expo-patterns
clerk
Padrões Expo / React Native com Clerk — cache de tokens SecureStore, 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-astro-patterns
clerk
Padrões Astro com Clerk — middleware, páginas SSR, componentes ilha,