Docs

Read session and user data in your TanStack Start app with Clerk

Clerk provides a set of hooks and helpers that you can use to access the active session and user data in your TanStack Start application. Here are examples of how to use these helpers in both the client and server side to get you started.

Server side

To access active session and user data on the server side, use the getAuth() helper. See the reference documentation for more information, including code examples.

Client side

To access active session and user data on the client side, use Clerk's useAuth() and useUser() hooks.

useAuth()

The useAuth() hook provides information about the current auth state, as well as helper methods to manage the current active session. The hook returns userId, which can be used to protect your routes, as shown in the following example:

routes/example.tsx
import { useAuth } from '@clerk/tanstack-start'
import { createFileRoute } from '@tanstack/react-router'

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

function Example() {
  const { isLoaded, userId } = useAuth()

  if (!isLoaded) {
    return <p>Loading...</p>
  }

  if (!userId) {
    // You could also add a redirect to the sign-in page here
    return null
  }

  return <div>Hello, {userId}!</div>
}

useUser()

The useUser() hook provides the current user's User object, which holds all of the information for a user of your application and provides a set of methods to manage their account.

routes/example.tsx
import { useUser } from '@clerk/tanstack-start'
import { createFileRoute } from '@tanstack/react-router'

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

function Example() {
  const { isLoaded, isSignedIn, user } = useUser()

  if (!isLoaded) {
    return <p>Loading...</p>
  }

  if (!isSignedIn) {
    // You could also add a redirect to the sign-in page here
    return null
  }

  return <div>Hello, {user.firstName}!</div>
}

Feedback

What did you think of this content?

Last updated on