The useAuth() hook provides access to the current user's authentication state and methods to manage the active session. You can use this hook to get the user's authentication and organization information, like their ID, session ID, session token, organization ID, and organization role, and to check if the user is authenticated or authorized to access a specific resource.
An object containing options for the useAuth() hook. treatPendingAsSignedOut is a boolean that indicates whether pending sessions are considered as signed out or not. Defaults to true.
A function that retrieves the current user's session token or a custom JWT template. Returns a promise that resolves to the token. See the reference doc.
A function that retrieves the current user's session token or a custom JWT template. Returns a promise that resolves to the token. See the reference doc.
A function that retrieves the current user's session token or a custom JWT template. Returns a promise that resolves to the token. See the reference doc.
A function that retrieves the current user's session token or a custom JWT template. Returns a promise that resolves to the token. See the reference doc.
The following example demonstrates how to use the useAuth() hook to access the current auth state, like whether the user is signed in or not. It also includes a basic example for using the getToken() method to retrieve a session token for fetching data from an external resource.
app/routes/index.tsx
import { useAuth } from'@clerk/tanstack-react-start'import { createFileRoute } from'@tanstack/react-router'exportconstRoute=createFileRoute('/')({ component: ExternalDataPage,})functionExternalDataPage() {const { userId,sessionId,getToken,isLoaded,isSignedIn } =useAuth()constfetchExternalData=async () => {consttoken=awaitgetToken()// Fetch data from an external APIconstresponse=awaitfetch('https://api.example.com/data', { headers: { Authorization:`Bearer ${token}`, }, })returnresponse.json() }// Handle loading stateif (!isLoaded) return <div>Loading...</div>// Protect the page from unauthenticated usersif (!isSignedIn) return <div>Sign in to view this page</div>return ( <div> <p> Hello, {userId}! Your current active session is {sessionId}. </p> <buttononClick={fetchExternalData}>Fetch Data</button> </div> )}