Best way to get session data server-side when using separate backend?
Hey there 👋 I'm using Next.js in a monorepo setup, so my
betterAuth
instance is not in my Next.js project. I could import this instance since I am using a monorepo setup, but I do not want duplicate instances. Typically on the server, we merely call auth.api.getSession({ headers: headers() })
. Client-side, we call authClient.getSession()
and we're good. But what if we want to call getSession
server-side when we don't have the betterAuth
instance? I have tried using the authClient
instance, but it only returns null. An LLM conveniently solved this problem for me, but I suspect this is the incorrect solution and perhaps the authClient
is supposed to be used here.
Anyone recommend a better solution?
PS: I think it would be convenient to reuse authClient
and just manually specify the headers as we usually do server-side.
Solution:Jump to solution
Found the solution. Seems obvious in retrospect! Simply pass headers manually using
fetchOptions
.
```TS
export const verifySession = cache(async (): Promise<Session | null> => {
const session = await authClient.getSession({...5 Replies
What backend are you using?
Hono
Unfortunately not. I am able to fetch the session using the
betterAuth
/auth
instance. I am also able to fetch it using the client-side instance. I am only not able to reuse the client-side instance on the server, yet I can't use the server-side instance because it isn't in the same project and I don't want duplicate instances.https://github.com/ga1az/nextjs-hono-prisma-better-auth/tree/main
This may be of use
Thanks, I'll check it out.
In this setup, the server-side auth instance (
auth
or betterAuth
) lives in the same project. In my setup, this instance is not in the same project. So, the question is: in this case, do we reuse the client-side instance on the server somehow? I haven't gotten this to work, and I suspect this is not recommended/possible.
Edit: an alt solution is to merely reuse my server-side instance, but this would result in instance duplication.Solution
Found the solution. Seems obvious in retrospect! Simply pass headers manually using
fetchOptions
.