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.