Better AuthBA
Better Auth•7mo ago
.jsonp

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.

"server-only"
// ...
export const verifySession = cache(async () => {
  const { headers } = await import("next/headers");

  const headersList = await headers();
  const cookieHeader = headersList.get("cookie");

  const response = await fetch(
    `${env.NEXT_PUBLIC_API_URL}/api/auth/get-session`,
    {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        ...(cookieHeader && { Cookie: cookieHeader }),
      },
      credentials: "include",
    }
  );

  if (!response.ok) {
    return null;
  }

  const session = await response.json();
  return session;
});
Solution
Found the solution. Seems obvious in retrospect! Simply pass headers manually using fetchOptions.

export const verifySession = cache(async (): Promise<Session | null> => {
  const session = await authClient.getSession({
    fetchOptions: {
      headers: await headers(),
    },
  });
  return session.data;
});
Was this page helpful?