Skip to main content
Docs

TanStack React Start Quickstart (beta)

Warning

The TanStack React Start SDK is currently in beta. It is not yet recommended for production use.

Install @clerk/tanstack-react-start

The Clerk TanStack React Start SDK gives you access to prebuilt components, React hooks, and helpers to make user authentication easier.

Run the following command to install the SDK:

terminal
npm install @clerk/tanstack-react-start
terminal
pnpm add @clerk/tanstack-react-start
terminal
yarn add @clerk/tanstack-react-start
terminal
bun add @clerk/tanstack-react-start
.env
VITE_CLERK_PUBLISHABLE_KEY=YOUR_PUBLISHABLE_KEY
CLERK_SECRET_KEY=YOUR_SECRET_KEY

Add clerkMiddleware() to your app

clerkMiddleware() grants you access to user authentication state throughout your app, on any server function or route.

Create a src/start.ts file with the following code:

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

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

Add <ClerkProvider> to your app

The <ClerkProvider> component provides session and user context to Clerk's hooks and components. It's recommended to wrap your entire app at the entry point with <ClerkProvider> to make authentication globally accessible. See the reference docs for other configuration options.

Add the <ClerkProvider> component to your app's root route, as shown in the following example:

src/routes/__root.tsx
import { ClerkProvider } from '@clerk/tanstack-react-start'
33 lines collapsedimport { HeadContent, Scripts, createRootRoute } from '@tanstack/react-router' import { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools' import { TanStackDevtools } from '@tanstack/react-devtools' import Header from '../components/Header' import appCss from '../styles.css?url' export const Route = createRootRoute({ head: () => ({ meta: [ { charSet: 'utf-8', }, { name: 'viewport', content: 'width=device-width, initial-scale=1', }, { title: 'TanStack Start Starter', }, ], links: [ { rel: 'stylesheet', href: appCss, }, ], }), shellComponent: RootDocument, })
function RootDocument({ children }: { children: React.ReactNode }) { return ( <ClerkProvider> <html lang="en"> <head> <HeadContent /> </head> <body> <Header /> {children} <TanStackDevtools config={{ position: 'bottom-right', }} plugins={[ { name: 'Tanstack Router', render: <TanStackRouterDevtoolsPanel />, }, ]} /> <Scripts /> </body> </html> </ClerkProvider> ) }

Protect your pages

Client-side

To protect your pages on the client-side, you can use Clerk's prebuilt control components that control the visibility of content based on the user's authentication state.

The following example uses the following components:

src/routes/index.tsx
import { SignedIn, UserButton, SignedOut, SignInButton } from '@clerk/tanstack-react-start'
import { createFileRoute } from '@tanstack/react-router'

export const Route = createFileRoute('/')({
  component: Home,
})

function Home() {
  return (
    <div>
      <h1>Index Route</h1>
      <SignedIn>
        <p>You are signed in</p>
        <UserButton />
      </SignedIn>
      <SignedOut>
        <p>You are signed out</p>
        <SignInButton />
      </SignedOut>
    </div>
  )
}

Server-side

To protect your routes, create a server function that checks the user's authentication state via the auth() method. If the user is not authenticated, they are redirected to a sign-in page. If authenticated, the user's userId is passed to the route, allowing access to the <Home /> component, which welcomes the user and displays their userId. The beforeLoad() method ensures authentication is checked before loading the page, and the loader() method returns the user data for use in the component.

Tip

Ensure that your app has the TanStack Start server handler configured in order for your server routes to work.

src/routes/index.tsx
import { createFileRoute, redirect } from '@tanstack/react-router'
import { createServerFn } from '@tanstack/react-start'
import { auth } from '@clerk/tanstack-react-start/server'

const authStateFn = createServerFn({ method: 'GET' }).handler(async () => {
  const { isAuthenticated, userId } = await auth()

  if (!isAuthenticated) {
    // This will error because you're redirecting to a path that doesn't exist yet
    // You can create a sign-in route to handle this
    // See https://clerk.com/docs/tanstack-react-start/guides/development/custom-sign-in-or-up-page
    throw redirect({
      to: '/sign-in',
    })
  }

  return { userId }
})

export const Route = createFileRoute('/')({
  component: Home,
  beforeLoad: async () => await authStateFn(),
  loader: async ({ context }) => {
    return { userId: context.userId }
  },
})

function Home() {
  const state = Route.useLoaderData()

  return <h1>Welcome! Your ID is {state.userId}!</h1>
}

Create your first user

Run your project with the following command:

terminal
npm run dev
terminal
yarn dev
terminal
pnpm dev
terminal
bun dev

Visit your app's homepage at http://localhost:3000. Sign up to create your first user.

Core concepts

Before building your application, it's important to understand the core concepts and objects that drive Clerk's powerful authentication and user management system.

Add a custom sign-in-or-up page

Learn how to create a custom sign-in-or-up page using Clerk's prebuilt components.

Protect content and read user data

Learn how to use Clerk's hooks and helpers to protect content and read session and user data.

Clerk components

Learn more about Clerk's prebuilt components.

Feedback

What did you think of this content?

Last updated on