Getting session from external server on a different server
Basically I have two backends here: one for TanStack Start's SSR, and one for Better Auth and the site's API (using Hono).
Before this change, I got the user's session on the Start backend like so:
However, since the Hono backend is the Better Auth server, I don't have access to
auth
. Is there a way to do this on the Start backend?Solution:Jump to solution
//middleware to get the user and session and add them to the context
app.use("*", async (c, next) => {
const session = await auth.api.getSession({ headers: c.req.raw.headers });
if (!session) {...
11 Replies
Bumping this please!
Do you mean that your hono js backend is NOT the better auth server?
What I have done in the past is use the better auth client for this.
You can use CreateAuthClient and point the url to your Better Auth server. The client will work on the “backend” hono js as long as you setup cors and trusted origins correctly.
On Hono you can use middleware to add the session cookie headers to the context and use them in other routes as well.
My setup uses middleware to validate the session with authClient.getSession() (passing the session cookie as a header) and then add it to the hono context.
Solution
//middleware to get the user and session and add them to the context
app.use("*", async (c, next) => {
const session = await auth.api.getSession({ headers: c.req.raw.headers });
if (!session) {
c.set("user", null);
c.set("session", null);
return next();
}
c.set("user", session.user);
c.set("session", session.session);
return next();
});
In your case you would replace auth.api.getSession with the authClient.getSession
Make sense?
If the api does not return any information you know the session is invalid
Also if you are calling the hono backend from your front end or elsewhere you will need to be sure to include the cookie in the headers for each request so it’s possible to validate the session at all.
Got it! Thanks for your help:)
No worries!
This is my exact issue!!!
did this solve your issue? i am having trouble with hydration where my SSR version does not see me logged in, causing issues with protected routes
Can't help you I'm afraid, I ended up just folding the external server into my main app (for unrelated reasons)
did doing that resolve the issue?
Yep!
Hey, I'm too working with a separate backend like hono and unable to validate the session like cookie is being set in the browser and not get into the headers of the tanstackstart, are you able to solve this issue of fetching the user session with a separate backend? @!skyfall @Raz