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.tsximport { 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>; }
external-data-page.tsximport { useAuth } from '@clerk/clerk-react'; 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
Variables | Description |
---|---|
isSignedIn | A boolean that returns true if the user is signed in. |
isLoaded | A boolean that until Clerk loads and initializes, will be set to false . Once Clerk loads, isLoaded will be set to true . |
userId | The current user's ID. |
sessionId | The current user's session ID. |
signOut | A function that signs the user out. |
getToken | A function that returns a promise that resolves to the current user's session token. Can also be used to retrieve a custom JWT template. |
orgId | The current user's organization ID. |
orgRole | The current user's organization role. |
orgSlug | The current user's organization slug. |
Last updated on November 21, 2023