Tanstack Start how to handle session cookie

First the stack, im using Tanstack Start, Hono and Better-Auth

The issue is when I hard reload or enter the URL manually, the cookie will not be read..
If its by client navigation it works correctly...

In order to have the cookie in the authenticated route i did the following function

export const getSession = createServerFn({ method: "GET" }).handler(
  async () => {
    const { headers } = getWebRequest()!;
    const session = await auth.api.getSession({ headers });

    return session || null;
  }
);


This way even if I hard reload or enter manually the session will be returned
 beforeLoad: async ({ context }) => {
    const session = await context.queryClient.ensureQueryData({
      queryKey: ["session"],
      queryFn: getSession,
      gcTime: 5 * 60 * 1000,
    });

    if (!session) {
      return {
        redirect: {
          to: "/auth/login",
        },
      };
    }

    return session;
  },

This is working as intended but now when im on a nested route inside the authenticated route, the issue persist.

On server I have reactStartCoookies as suggested in the docs and last item of the array...
export const auth = betterAuth({
  plugins: [openAPI(), reactStartCookies()],
  session: {
    cookieCache: {
      enabled: true,
      maxAge: 5 * 60,
    },
  },


For data fetching im using Hono RPC
export const client = hc<ApiRoutes>(import.meta.env.VITE_CLIENT_URL, {
  fetch: (input: RequestInfo | URL, init?: RequestInit) =>
    fetch(input, {
      ...init,
      credentials: "include",
    }),
}).api;

How I deal with this scenario?
Was this page helpful?