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,
};
}
});
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
1 Reply
Ankit
AnkitOP4w ago
Also the thing is it works totally fine when i am on localhost and on production it won't (might be because of separate origins)

Did you find this page helpful?