Gate UI on authentication readiness
A page must wait for Clerk initialization before deciding what to render.
Clerk · Hook
useAuth() gives React components access to Clerk’s current authentication and active-session state. It also provides organization context and helpers such as getToken() and signOut().
Call useAuth() inside a React component to read loading and sign-in state, inspect the active user or organization context, sign out, and obtain a session token or custom JWT through getToken().
const { isLoaded, isSignedIn, getToken, signOut } = useAuth(options?)| Name | Type | Description |
|---|---|---|
options | { treatPendingAsSignedOut?: boolean } | Optional options object. treatPendingAsSignedOut controls whether pending sessions are treated as signed out; it defaults to true. |
An object containing authentication and organization state plus session helpers, including getToken(): (options?: GetTokenOptions) => Promise<null | string>.
import { useAuth } from '@clerk/nextjs'
export default function Account() {
const { isLoaded, isSignedIn, getToken } = useAuth()
if (!isLoaded) return <p>Loading...</p>
if (!isSignedIn) return <p>Sign in to continue.</p>
async function loadData() {
const token = await getToken()
const response = await fetch('/api/data', {
headers: token ? { Authorization: `Bearer ${token}` } : {},
})
return response.json()
}
return <button onClick={loadData}>Load protected data</button>
}Use the hook after Clerk loads, gate signed-out users, and retrieve a session token for an authenticated request.
A page must wait for Clerk initialization before deciding what to render.
A frontend request needs Clerk credentials for a protected backend resource.
A dashboard displays content based on the active organization and role.
useAuth() exposes the current authentication state and helpers for the active session. It can provide loading and signed-in status, identifiers such as user and session IDs, organization context, sign-out behavior, and getToken().
Follow-up: How should a component avoid rendering the wrong state during initialization? Check isLoaded first, then branch on isSignedIn before rendering signed-in or signed-out content.
getToken() returns a promise for the current session token or a custom JWT template. The result can be used to authenticate requests to an external resource, and it may resolve to null.
Follow-up: How would you make a request robustly? Await getToken(), omit or reject the authorization header when the result is null, and handle the API response normally.
The hook accepts an options object with treatPendingAsSignedOut. That option determines whether pending sessions count as signed out, and its documented default is true.
Follow-up: When might you change it? When the UI must distinguish a pending session from a definite signed-out state, preserve that distinction rather than applying the default behavior.
getTokenisLoadedisSignedInuserIdsessionIdorgIdorgRolesignOut