Fix Better-Auth's getSession In TanStack Start

During the process of adding TanStack Start to my SPA application, I came across an error with Better-Auth.

The problematic part was the server function for retrieving the logged-in user's session:

import { createServerFn } from "@tanstack/react-start";
import { getWebRequest } from "@tanstack/react-start/server";
import { authClient } from "../auth-client";

export const fetchUser = createServerFn({ method: "GET" }).handler(async () => {
  const request = getWebRequest();

  const { data } = await authClient.getSession({
    fetchOptions: {
      headers: {
        cookie: request.headers.get("cookie") || "",
      },
    },
  });

  return data;
});

The above code uses the getSession function provided by Better-Auth to fetch the user's session information. However, the function caused an infinite loop, which caused the application to crash.

The culprit was the baseURL property, which was missing from my configuration.

import { createAuthClient } from "better-auth/react";
import { inferAdditionalFields } from "better-auth/client/plugins";

export const authClient = createAuthClient({
  baseURL:
    process.env.NODE_ENV === "development"
      ? "http://localhost:5173"
      : "https://mydomain.com",
  ....
});

export const {
  ....
  getSession,
} = authClient;

export type Session = typeof authClient.$Infer.Session;
export type User = typeof authClient.$Infer.Session.user;

Once I added the baseURL, the getSession function, and implicitly the app, worked fine.

If you want to learn more about Better-Auth, check how to implement authentication with Better-Auth in a monorepo application.

๐Ÿ’ก Found this helpful? ๐Ÿ’ก

This content is completely free and took significant time to create. If it helped you solve a problem or learn something new, consider buying me a coffee โ˜•.

Your support helps me to:

  • Keep writing detailed tutorials
  • Research and test new technologies
  • Build more tools and applications
โ˜• Buy me a coffee - any amount helps!

๐Ÿงก No pressure - sharing this post helps too!