Best way to protect routes in TanStack Start?

What's the best way to protect all private routes like /dashboard*, so they redirect to /login if no session exists? I don't see this aspect in the example: https://github.com/better-auth/better-auth/tree/main/examples/tanstack-example

Below is my attempt, but session is always
null
, even if the user is authenticated.

// /routes/(authenticated)/route.tsx -- a layout despite the weird name.
import { createFileRoute, Outlet, redirect } from "@tanstack/react-router";
import { authClient } from "@/lib/auth-client";

export const Route = createFileRoute("/(authenticated)")({
  component: AuthenticatedLayout,
  beforeLoad: async ({ location }) => {
    const { data: session } = await authClient.getSession();

    if (!session) {
      throw redirect({
        to: "/login",
        search: {
          redirect: location.pathname,
        },
      });
    }

    return { session };
  },
});

function AuthenticatedLayout() {
  return (
    <div className="min-h-screen">
      <Outlet />
    </div>
  );
}


I'm using authClient.getSession() b/c I believe this needs to work for both SSR and in the client.

CC @daveycodez Looking through the msg history, it appears you contributed the TanStack Start example, but I don't see this aspect in the example. Maybe you know?
GitHub
The most comprehensive authentication framework for TypeScript - better-auth/better-auth
Was this page helpful?