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.

Create a new Tanstack React Start app

If you don't already have a Tanstack React Start app, run the following commands to create a new one.

terminal
npm create @tanstack/start@latest clerk-tanstack-react-start
cd clerk-tanstack-react-start
npm install
terminal
pnpm create @tanstack/start clerk-tanstack-react-start
cd clerk-tanstack-react-start
pnpm install
terminal
yarn create @tanstack/start clerk-tanstack-react-start
cd clerk-tanstack-react-start
yarn install
terminal
bunx @tanstack/create-start@latest clerk-tanstack-react-start
cd clerk-tanstack-react-start
bun install

Install @clerk/tanstack-react-start

The Clerk TanStack React Start SDK gives you access to prebuilt components, 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. It also allows you to protect specific routes from unauthenticated users. To add clerkMiddleware() to your app, follow these steps:

  1. 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()],
      }
    })
  2. By default, clerkMiddleware() will not protect any routes. All routes are public and you must opt-in to protection for routes. See the clerkMiddleware() reference to learn how to require authentication for specific routes.

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'
32 lines collapsedimport { HeadContent, Scripts, createRootRoute } from '@tanstack/react-router' import { TanStackRouterDevtools } from '@tanstack/react-router-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 ( <html lang="en"> <head> <HeadContent /> </head> <body> <ClerkProvider> <Header /> {children} </ClerkProvider> <TanStackRouterDevtools /> <Scripts /> </body> </html> ) }

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,
  SignUpButton,
} 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>
      <header>
        {/* Show the sign-in and sign-up buttons when the user is signed out */}
        <SignedOut>
          <SignInButton />
          <SignUpButton />
        </SignedOut>
        {/* Show the user button when the user is signed in */}
        <SignedIn>
          <UserButton />
        </SignedIn>
      </header>
    </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().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>
}

Run your project

Run your project with the following command:

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

Create your first user

  1. Visit your app's homepage at http://localhost:3000.
  2. Select "Sign up" on the page and authenticate to create your first user.

Next steps

Learn more about Clerk components, how to customize them, and how to use protect routes and access user data using the following guides.

Prebuilt components

Learn more about Clerk's suite of components that let you quickly add authentication to your app.

Customization & localization

Learn how to customize and localize Clerk components.

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.

Feedback

What did you think of this content?

Last updated on

GitHubEdit on GitHub