Access the Clerk object outside of components
The Clerk
object is accessible using the useClerk()
hook. However, if you need to access the Clerk
object outside of React components, such as in utility functions or background tasks, you can use the getClerkInstance()
function.
import { getClerkInstance } from '@clerk/clerk-expo'
export async function fetchFoo() {
const clerkInstance = getClerkInstance()
// Use `getToken()` to get the current session token
const token = await clerkInstance.session?.getToken()
const response = await fetch('/api/foo', {
headers: {
// Include the session token as a Bearer token in the Authorization header
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
})
if (!response.ok) {
// Include status code and status text in error message
throw new Error(`API Error: ${response.status} ${response.statusText}`)
}
return response.json()
}
Feedback
Last updated on