Is it possible to get clerk token without using server side function or client hook? #2203
Replies: 2 comments 5 replies
-
the only solution I have for now is this, if you have something better let me know import { auth } from '@clerk/nextjs'
import Clerk from '@clerk/clerk-js'
export async function getAuthToken() {
const isServer = typeof window === 'undefined'
if (isServer) {
const { getToken } = auth()
return await getToken()
}
const clerk = new Clerk(process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY!)
await clerk.load()
return await clerk.session?.getToken()
} and import { getAuthToken } from './get-auth-token'
export async function authFetch(
url: string,
options?: RequestInit,
): Promise<Response> {
const token = await getAuthToken()
if (token) {
options = {
...(options || {}),
headers: {
...(options?.headers || {}),
Authorization: `Bearer ${token}`,
},
}
}
return await fetch(url, options)
} |
Beta Was this translation helpful? Give feedback.
5 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I have a case where I use a nextjs app, but I do not fetch data from next api, I have an external server protected by clerk, and I have a page that is 'use client', but the data is prefetched by a server component, and I wanted an easier way to get clerk token for this use case.
example case:
I have getUsers function that will be used to dehydrate data from server component and also fetch data from client side
now I have my server component that use this function to pre fetch data
and now I have my client component to render client page
since it is called from both client side and server side, I can't use hooks or the server functions provided by clerk, I also tried
@clerk/clerk-js
but no success, the only approach I found so far was to create a higher order function to get token from client or server side and pass as param togetUsers
function, but honestly there most be something better...Beta Was this translation helpful? Give feedback.
All reactions