Better AuthBA
Better Auth6mo ago
2 replies
Ankit

cookies in ssr mode

I am using better auth with tanstack start (as my frontend) and hono as my separate backend for now, while every thing works fine without ssr mode when i switched ssr mode it becomes difficult to get the cookie in the ssr mode with better auth, i am using the below code snippet to fetch the user session but its not getting the cookie properly
export const getSessionServer = createServerFn({
  method: 'GET'
})
  .validator(() => ({}))
  .handler(async () => {
    try {
      const headers: any = getRequestHeaders();

      const cookies = parseCookies();
      // const authToken = getCookie('better-auth.session_token');
      // console.log("authtoken", authToken)

      if (!cookies || Object.keys(cookies).length === 0) {
        console.warn('No cookies found in request, skipping session fetch');
        return null;
      }

      const session = await authClient.getSession({
        fetchOptions: {
          headers,
        }
      });

      console.log("session", session)

      return {
        user: session?.data?.user || null,
        session: session?.data?.session || null,
      };

    } catch (error) {
      console.error('Failed to get session:', error);
      return {
        user: null,
        session: null,
      };
    }
  });

Also need to know the use of reactstartcookies as my backend is separate from the tanstackstart frontend
Was this page helpful?