clerkMiddleware()Tanstack Start Icon 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:
Create a src/start.ts file with the following code:
By default, clerkMiddleware() will not protect any routes. All routes are public and you must opt-in to protection for routes. See the clerkMiddleware() referenceTanstack Start Icon to learn how to require authentication for specific routes.
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:
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:
<SignedIn>: Children of this component can only be seen while signed in.
<SignedOut>: Children of this component can only be seen while signed out.
<UserButton />: Shows the signed-in user's avatar. Selecting it opens a dropdown menu with account management options.
import { SignedIn, UserButton, SignedOut, SignInButton, SignUpButton,} from'@clerk/tanstack-react-start'import { createFileRoute } from'@tanstack/react-router'exportconstRoute=createFileRoute('/')({ component: Home,})functionHome() {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> )}
To protect your routes, create a server function that checks the user's authentication state via the auth()Tanstack Start Icon 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.