Docs

Read session and user data in your React Router 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 React Router 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:

app/routes/use-auth.tsx
import { useAuth } from '@clerk/react-router'

export default function UseAuthPage() {
  const { isLoaded, userId } = useAuth()

  // Return null if the user signs out while on the page
  // or if the auth state is still loading
  if (!isLoaded || !userId) {
    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.

app/routes/use-user.tsx
import { useUser } from '@clerk/react-router'

export default function UseUserPage() {
  const { isLoaded, isSignedIn, user } = useUser()

  // Return null if the user signs out while on the page
  // or if the auth state is still loading
  if (!isLoaded || !isSignedIn) {
    return null
  }

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

Feedback

What did you think of this content?

Last updated on