Docs

useAuth()

The useAuth() hook provides access to the current user's authentication state and methods to manage the active session.

Returns

  • Name
    isLoaded
    Type
    boolean
    Description
  • Name
    isSignedIn
    Type
    boolean
    Description

    A boolean that indicates whether a user is currently signed in.

  • Name
    userId
    Type
    string
    Description

    The ID of the current user.

  • Name
    sessionId
    Type
    string
    Description

    The ID for the current session.

  • Name
    orgId
    Type
    string
    Description

    The ID of the user's active organization.

  • Name
    orgRole
    Type
    string
    Description

    The current user's role in their active organization.

  • Name
    orgSlug
    Type
    string
    Description

    The URL-friendly identifier of the user's active organization.

  • Name
    signOut()
    Type
    (options?: SignOutOptions) => Promise<void>
    Description

    A function that signs out the current user. Returns a promise that resolves when complete. See the reference doc.

    • getToken()
    • (options?: GetTokenOptions) => Promise<string | null>

    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.

  • Name
    has()
    Type
    (isAuthorizedParams: CheckAuthorizationParamsWithCustomPermissions) => boolean
    Description

    A function that checks if the user has specific permissions or roles. See the reference doc.

Note

For Next.js applications, it's recommended to use the auth() helper instead of useAuth(). Since auth() must be used in Server Components, you'll need to pass auth data to Client Components as needed. If you prefer useAuth(), you must pass the dynamic prop to <ClerkProvider>, but be aware this switches the app to dynamic rendering. Learn more here.

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.

src/pages/ExternalDataPage.tsx
import { useAuth } from '@clerk/clerk-react'

export default function ExternalDataPage() {
  const { getToken, isLoaded, isSignedIn } = useAuth()

  const fetchExternalData = async () => {
    const token = await getToken()

    // Fetch data from an external API
    const response = await fetch('https://api.example.com/data', {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    })

    return response.json()
  }

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

  if (!isSignedIn) {
    return <div>Sign in to view this page</div>
  }

  return (
    <div>
      <button onClick={fetchExternalData}>Fetch Data</button>
    </div>
  )
}

Feedback

What did you think of this content?

Last updated on