clerk-tanstack-patterns

por clerk

Patrones de autenticación de TanStack React Start con @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 Vinxi + clerkMiddlewarereferences/vinxi-server.md

References

ReferenceDescription
references/router-guards.mdbeforeLoad auth redirect
references/server-functions.mdcreateServerFn with auth()
references/loaders.mdAuth context in loaders
references/vinxi-server.mdclerkMiddleware() setup

Setup

npm install @clerk/tanstack-react-start

.env:

CLERK_PUBLISHABLE_KEY=pk_...
CLERK_SECRET_KEY=sk_...

src/start.ts (Vinxi entry):

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

export const startInstance = createStart(() => {
  return {
    requestMiddleware: [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 runs on Vinxi. Auth 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() returns emptyMissing clerkMiddleware in start.tsAdd to requestMiddleware array
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

Más skills de clerk

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
Clerk Billing para la gestión de suscripciones - renderiza la PricingTable de Clerk
clerk-nextjs-patterns
clerk
Patrones avanzados de Next.js para autenticación, middleware, Server Actions y almacenamiento en caché con ámbito de usuario usando Clerk. Distingue entre auth() del lado del servidor y el hook useAuth() del lado del cliente; mezclarlos es un error común que causa fallos. Cubre estrategias de middleware (primero público vs primero protegido), protección de rutas de API y códigos de estado HTTP adecuados (401 vs 403). Incluye patrones de almacenamiento en caché con ámbito de usuario usando unstable_cache y protección de Server Actions contra mutaciones no autorizadas. Proporciona compatibilidad con Core 2...
clerk-expo-patterns
clerk
Patrones de Expo / React Native con Clerk — caché 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
clerk
El binario clerk es una puerta de enlace preautenticada hacia la API de Backend y la API de Plataforma de Clerk, además de herramientas a nivel de proyecto (autenticación, vinculación, extracción de variables de entorno, configuración de instancias). Cuando el usuario pregunte algo que involucre un recurso de Clerk, usa clerk primero en lugar de hacer un curl manual.
clerk-cli
clerk
El binario clerk es una puerta de enlace preautenticada hacia la API de Backend y la API de Plataforma de Clerk, además de herramientas a nivel de proyecto (autenticación, vinculación, extracción de entornos, configuración de instancias). Cuando el usuario pregunte algo que involucre un recurso de Clerk, recurre a clerk primero en lugar de improvisar con curl.
clerk-astro-patterns
clerk
Patrones de Astro con Clerk — middleware, páginas SSR, componentes isla,