# TanStack React Start Quickstart

1. ## 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](https://tanstack.com/start/latest/docs/framework/react/getting-started).

   ```npm
   npm create @tanstack/start@latest clerk-tanstack-react-start
   cd clerk-tanstack-react-start
   ```
2. ## Install `@clerk/tanstack-react-start`

   The [Clerk TanStack React Start SDK](https://clerk.com/docs/tanstack-react-start/reference/overview.md) gives you access to prebuilt components, hooks, and helpers to make user authentication easier.

   Run the following command to install the SDK:

   filename: terminal

   ```npm
   npm install @clerk/tanstack-react-start
   ```
3. ## Set your Clerk API keys

   Add the following keys to your `.env` file. These keys can always be retrieved from the [**API keys**](https://dashboard.clerk.com/~/api-keys) page in the Clerk Dashboard.

   If you haven't already, create a new Clerk application in the [Clerk Dashboard](https://dashboard.clerk.com/). For more information, see the [setup guide](https://clerk.com/docs/getting-started/quickstart/setup-clerk.md?sdk=tanstack-react-start).

   1. In the Clerk Dashboard, navigate to the [**API keys**](https://dashboard.clerk.com/~/api-keys) page.
   2. In the **Quick Copy** section, copy your Clerk Publishable Key and Secret Key.
   3. Paste your keys into your `.env` file.

   The final result should resemble the following:

   filename: .env

   ```env
   VITE_CLERK_PUBLISHABLE_KEY={{pub_key}}
   CLERK_SECRET_KEY={{secret}}
   ```
4. ## Add `clerkMiddleware()` to your app

   [clerkMiddleware()](https://clerk.com/docs/tanstack-react-start/reference/clerk-middleware.md) grants you access to user authentication state throughout your app. To add `clerkMiddleware()` to your app, follow these steps:

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

      filename: src/start.ts

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

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

   2. `clerkMiddleware()` does not protect routes by itself. All routes are public until you add route-level protection. See the [server-side route protection example](https://clerk.com/docs/tanstack-react-start/getting-started/quickstart.md#server-side) to learn how.
5. ## Add `<ClerkProvider>` to your app

   The [<ClerkProvider>](https://clerk.com/docs/tanstack-react-start/reference/components/clerk-provider.md) 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](https://clerk.com/docs/tanstack-react-start/reference/components/clerk-provider.md) for other configuration options.

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

   filename: src/routes/\_\_root.tsx

   ```tsx
   import { ClerkProvider } from '@clerk/tanstack-react-start'
   import { HeadContent, Scripts, createRootRoute } from '@tanstack/react-router'
   import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'

   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>{children}</ClerkProvider>
           <TanStackRouterDevtools />
           <Scripts />
         </body>
       </html>
     )
   }
   ```
6. ## Protect your pages
7. ### Client-side

   To protect your pages on the client-side, you can use Clerk's [prebuilt control components](https://clerk.com/docs/tanstack-react-start/reference/components/overview.md#control-components) that control the visibility of content based on the user's authentication state.

   The following example uses the following components:

   - [<Show when="signed-in">](https://clerk.com/docs/tanstack-react-start/reference/components/control/show.md): Children of this component can only be seen while **signed in**.
   - [<Show when="signed-out">](https://clerk.com/docs/tanstack-react-start/reference/components/control/show.md): Children of this component can only be seen while **signed out**.
   - [<UserButton />](https://clerk.com/docs/tanstack-react-start/reference/components/user/user-button.md): Shows the signed-in user's avatar. Selecting it opens a dropdown menu with account management options.
   - [<SignInButton />](https://clerk.com/docs/tanstack-react-start/reference/components/unstyled/sign-in-button.md): An unstyled component that links to the sign-in page. In this example, since no props or [environment variables](https://clerk.com/docs/guides/development/clerk-environment-variables.md?sdk=tanstack-react-start) are set for the sign-in URL, this component links to the [Account Portal sign-in page](https://clerk.com/docs/guides/account-portal/overview.md?sdk=tanstack-react-start#sign-in).
   - [<SignUpButton />](https://clerk.com/docs/tanstack-react-start/reference/components/unstyled/sign-up-button.md): An unstyled component that links to the sign-up page. In this example, since no props or [environment variables](https://clerk.com/docs/guides/development/clerk-environment-variables.md?sdk=tanstack-react-start) are set for the sign-up URL, this component links to the [Account Portal sign-up page](https://clerk.com/docs/guides/account-portal/overview.md?sdk=tanstack-react-start#sign-up).

   filename: src/routes/index.tsx

   ```tsx
   import { UserButton, Show, 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>
         <Show when="signed-in">
           <UserButton />
         </Show>
         <Show when="signed-out">
           <SignInButton />
           <SignUpButton />
         </Show>
       </div>
     )
   }
   ```
8. ### Server-side

   To protect your routes, create a [server function](https://tanstack.com/start/latest/docs/framework/react/guide/server-functions) that checks the user's authentication state via the [auth()](https://clerk.com/docs/tanstack-react-start/reference/auth.md) 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()`](https://tanstack.com/router/latest/docs/framework/react/api/router/RouteOptionsType#beforeload-method) method ensures authentication is checked before loading the page, and the [`loader()`](https://tanstack.com/router/latest/docs/framework/react/api/router/RouteOptionsType#loader-method) method returns the user data for use in the component.

   > Ensure that your app has the [TanStack Start server handler](https://tanstack.com/start/latest/docs/framework/react/guide/server-routes#handling-server-route-requests) configured in order for your server routes to work.

   filename: src/routes/index.tsx

   ```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>
   }
   ```
9. ## Run your project

   Run your project with the following command:

   ```npm
   npm run dev
   ```
10. ## 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

Explore the most relevant next steps for your SDK using the following guides.

- [Prebuilt components](https://clerk.com/docs/reference/components/overview.md?sdk=tanstack-react-start): Learn how to add Clerk's prebuilt authentication and user-management UI to your app.
- [Build custom flows](https://clerk.com/docs/guides/development/custom-flows/overview.md?sdk=tanstack-react-start): Learn how to build custom user interfaces entirely from scratch using the Clerk API.
- [Read user data](https://clerk.com/docs/guides/users/reading.md?sdk=tanstack-react-start): Learn how to use Clerk's helpers to read user data in your app.
- [Customization & localization](https://clerk.com/docs/guides/customizing-clerk/appearance-prop/overview.md?sdk=tanstack-react-start): Learn how to customize and localize Clerk components.

## More to explore

Explore additional Clerk features that help you build, manage, and grow your application.

- [**Organizations**](https://clerk.com/docs/guides/organizations/overview.md?sdk=tanstack-react-start) - Organizations are shared accounts that let teams collaborate, manage members and roles, and control access to shared resources.
- [**Billing**](https://clerk.com/docs/guides/billing/overview.md?sdk=tanstack-react-start) - Billing enables you to manage subscriptions, free trials, payments, plans, and billing-related webhook events for B2C and B2B applications.
- [**Waitlist**](https://clerk.com/docs/guides/secure/restricting-access.md?sdk=tanstack-react-start#waitlist) - Waitlist lets you collect signups and control access to new products or features before launch through a simple, integrated workflow.

---

## Sitemap

[Overview of all docs pages](https://clerk.com/docs/llms.txt)
