hydration issues with ssr handler

Hi there,

I am trying to create a better-auth ssr handler similar to clerk's

But I am having issues hydrating the user session and query client... at this time I do the following:

import type { AnyRouter } from "@tanstack/react-router";
import type { EventHandler } from "@tanstack/react-start/server";
import { getSession } from "@/lib/server/auth";
import type { QueryClient } from "@tanstack/react-query";

export type HandlerCallback<TRouter extends AnyRouter> = (ctx: {
    request: Request;
    router: TRouter;
    responseHeaders: Headers;
}) => Response | Promise<Response>;

export type CustomizeStartHandler<TRouter extends AnyRouter> = (
    cb: HandlerCallback<TRouter>,
) => EventHandler;

export function createBetterAuthHandler<TRouter extends AnyRouter>(
    startHandler: CustomizeStartHandler<TRouter>,
) {
    return (cb: HandlerCallback<TRouter>): EventHandler =>
        startHandler(async ({ request, router, responseHeaders }) => {
            const qc = router.options.context.queryClient as QueryClient;

            const session = await getSession();

            qc.setQueryData(["session"], session);

            // 4) stash session into router context
            router.update({
                context: {
                    ...router.options.context,
                    session,
                },
            });

            // 5) run through all loaders / beforeLoad
            await router.load();

            // 6) hand back to your normal handler (e.g. defaultStreamHandler)
            return cb({ request, router, responseHeaders });
        });
}

//ssr.tsx
export default createBetterAuthHandler(
    createStartHandler({
        createRouter,
        getRouterManifest,
    }),
)(defaultStreamHandler);


It seems like my issue is that the session is not being hydrated into the client. I noticed because in my terminal - when console logging it shows all the session information but in the browser logs it doesn't...

Is there anything else that needs to be done?
GitHub
Official JavaScript repository for Clerk authentication - clerk/javascript
javascript/packages/tanstack-react-start/src/server/middlewareHandl...
Was this page helpful?