Skip to Content
Clerk logo

Clerk Docs

Ctrl + K
Go to clerkstage.dev

useAuth()

The useAuth() hook is a convenient way to access the current auth state. This hook provides the minimal information needed for data-loading and helper methods to manage the current active session.

Usage

/app/pageWithData/clientComponent.tsx
"use client"; import * as React from "react"; import { useAuth } from "@clerk/nextjs"; export default function ExternalDataPage() { const [data, setData] = React.useState<object>({}); const { getToken, isLoaded, isSignedIn } = useAuth(); // In this case, /api/example is a Next.js Route Handler const fetchData = async () => { fetch("/api/example", { headers: { Authorization: `Bearer ${await getToken()}` }, }) .then((response) => response.json()) .then((data) => { console.log("data", data); setData(data); }); return; }; React.useEffect(() => { if (!isLoaded || !isSignedIn) { // You can handle the loading or signed state separately } fetchData(); }, []); return <pre>{JSON.stringify(data, null, 2)}</pre>; }
pages/index.tsx
import { useAuth } from '@clerk/nextjs'; export default function ExternalDataPage() { const { getToken, isLoaded, isSignedIn } = useAuth(); if (!isLoaded || !isSignedIn) { // You can handle the loading or signed state separately return null; } const fetchDataFromExternalResource = async () => { const token = await getToken(); // fetch your data return data; }; return <div>...</div>; }

Returns

VariablesDescription
isSignedInA boolean that returns true if the user is signed in.
isLoadedA boolean that until Clerk loads and initializes, will be set to false. Once Clerk loads, isLoaded will be set to true.
userIdThe current user's ID.
sessionIdThe current user's session ID.
signOutA function that signs the user out.
getTokenA function that returns a promise that resolves to the current user's session token. Can also be used to retrieve a custom JWT template.
orgIdThe current user's organization ID.
orgRoleThe current user's organization role.
orgSlugThe current user's organization slug.

What did you think of this content?

Clerk © 2023