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.
By default, Next.js opts all routes into static rendering. If you need to opt a route or routes into dynamic rendering because you need to access the authentication data at request time, you can create a boundary by passing the dynamic prop to <ClerkProvider>. See the guide on rendering modes for more information, including code examples.
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/external-data/page.tsx
'use client'import { useAuth } from'@clerk/nextjs'exportdefaultfunctionPage() {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> )}