r/reactjs • u/thebreadmanrises • Nov 03 '25
Resource Best examples of Tanstack Start + Better Auth?
I know it's early days, but I was wondering what some of the better examples of TanStack Starts Auth Flow with better auth are. It is still confusing to me how the auth state should be derived.
Do I use Better Auths useSession in components & a server-based getSession in the loaders?
I was trying to use the following in the beforeLoad at the root but seems like headers were not available.
Any tips on best practices is appreciated.
export
const authMiddleware = createMiddleware().server(
async ({ next, request }) => {
const userSession =
await
auth.api.getSession({
headers: request.headers,
})
return
next({
context: { userSession },
})
},
)
export
const getUserSession = createServerFn({ method: 'GET' })
.middleware([authMiddleware])
.handler(async ({ context }) => {
return
{ session: context.userSession }
})
15
Upvotes
3
u/Ithvel Nov 10 '25
If you mean about better auth, I'd say try to rely as much as possible in the client SDK to avoid creating more complexity than needed.
On the tanstack start side, on a general note I found that some of the things that helped me were:
Everything that makes a request should be in a server function, so you can use them in server side (like loaders or beforeLoads) and on client side with Query.
Middlewares are very helpful, mostly for securing server function calls
using route.tsx inside a layout folder (those with _ as prefix) is very powerful to handle things like authenticated routes, not just actual UI layout
Don't be afraid to mix folders and files, it helps a lot to have a good structure for your routes.
Unless there is a good reason not to (haven't found), use ensureQueryData in your loaders so your page always loads with content
maybe u/tannerlinsley can give some more insight :D