fix: redirect to login on first load without session
This commit is contained in:
@@ -1,33 +1,40 @@
|
||||
import { createFileRoute, Navigate, Outlet, useRouterState } from '@tanstack/react-router'
|
||||
import { createFileRoute, Outlet, redirect } from '@tanstack/react-router'
|
||||
import { InstallPrompt } from '@/components/install-prompt'
|
||||
import { AppHeader } from '@/components/layout/app-header'
|
||||
import { AppSidebar } from '@/components/layout/app-sidebar'
|
||||
import { BottomNav } from '@/components/layout/bottom-nav'
|
||||
import { SidebarInset, SidebarProvider } from '@/components/ui/sidebar'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { useSession } from '@/lib/auth-client'
|
||||
import { authClient, useSession } from '@/lib/auth-client'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated')({
|
||||
// Guard before anything renders or loads: without a session we bounce the
|
||||
// user to `/sign-in`, keeping the current URL so we can return after login.
|
||||
// Redirecting here (instead of rendering <Navigate>) also keeps child loaders
|
||||
// from firing API calls that would only answer 401.
|
||||
beforeLoad: async ({ location }) => {
|
||||
const { data: session } = await authClient.getSession()
|
||||
|
||||
if (!session) {
|
||||
throw redirect({ to: '/sign-in', search: { redirect: location.href }, replace: true })
|
||||
}
|
||||
},
|
||||
component: AuthenticatedLayout,
|
||||
})
|
||||
|
||||
/**
|
||||
* Layout for every authenticated page. The session lives in BetterAuth (Hono
|
||||
* API); while it resolves we render a loader, and without a session we bounce
|
||||
* the user to `/sign-in`, keeping the current URL so we can return after login.
|
||||
* API); `beforeLoad` already guarantees one, so while the reactive session
|
||||
* resolves (or right after signing out, before navigating away) we render a
|
||||
* loader.
|
||||
*/
|
||||
function AuthenticatedLayout() {
|
||||
const { data: session, isPending } = useSession()
|
||||
const href = useRouterState({ select: (state) => state.location.href })
|
||||
|
||||
if (isPending) {
|
||||
if (isPending || !session) {
|
||||
return <SessionLoading />
|
||||
}
|
||||
|
||||
if (!session) {
|
||||
return <Navigate to="/sign-in" search={{ redirect: href }} replace />
|
||||
}
|
||||
|
||||
return (
|
||||
<SidebarProvider>
|
||||
<AppSidebar />
|
||||
|
||||
Reference in New Issue
Block a user