useSession doesn't get session in TanStack Start

I have a TanStack Start SPA web app connected to a separate backend. I have enabled:
export const auth = betterAuth({
basePath: "/auth",
database: drizzleAdapter(db, {
provider: "pg",
usePlural: true,
}),
trustedOrigins: [...],
plugins: [...
reactStartCookies(),
],
});
export const auth = betterAuth({
basePath: "/auth",
database: drizzleAdapter(db, {
provider: "pg",
usePlural: true,
}),
trustedOrigins: [...],
plugins: [...
reactStartCookies(),
],
});
And on my signin page
const signInMutation = useMutation({
mutationFn: async (data: z.infer<typeof signInSchema>) => {
return await auth.signIn.email({
email: data.email,
password: data.password,
});
},
onSuccess: (data) => {
toast.success("Signed in successfully");
// biome-ignore lint/style/noNonNullAssertion: <explanation>
localStorage.setItem("auth-token", data.data?.token!);
navigate({ to: "/app" });
},
onError: (error) => {
toast.error(error.message || "Failed to sign in. Please try again.");
},
});
const signInMutation = useMutation({
mutationFn: async (data: z.infer<typeof signInSchema>) => {
return await auth.signIn.email({
email: data.email,
password: data.password,
});
},
onSuccess: (data) => {
toast.success("Signed in successfully");
// biome-ignore lint/style/noNonNullAssertion: <explanation>
localStorage.setItem("auth-token", data.data?.token!);
navigate({ to: "/app" });
},
onError: (error) => {
toast.error(error.message || "Failed to sign in. Please try again.");
},
});
on the route of the signedin:
export const Route = createFileRoute("/app")({
beforeLoad: async ({ context }) => {
const { data, error } = await context.auth.getSession();
console.log("data", data);
if (
error ||
data === null ||
data?.session === null ||
data?.user === null
) {
throw redirect({ to: "/auth/sign-in" });
}
return {
user: data.user,
session: data.session,
};
},
component: RouteComponent,
});
export const Route = createFileRoute("/app")({
beforeLoad: async ({ context }) => {
const { data, error } = await context.auth.getSession();
console.log("data", data);
if (
error ||
data === null ||
data?.session === null ||
data?.user === null
) {
throw redirect({ to: "/auth/sign-in" });
}
return {
user: data.user,
session: data.session,
};
},
component: RouteComponent,
});
I can see in Chrome devtool, if I see my cookies, that a valid cookie is set under better-auth.session_token, but if I refresh the page after signing in, it gives me null in the getSession, and I am signed out. Did I miss a step?
Solution:
Make sure to pass headers into the getSession call.
Jump to solution
2 Replies
Solution
Ping
Ping3mo ago
Make sure to pass headers into the getSession call.
Winston
WinstonOP3mo ago
doh I realized I had a typo on the isomorphic fn to get the session token out of a cookie

Did you find this page helpful?