#passing session from middleware to page?

17 messages · Page 1 of 1 (latest)

dusky nacelle
#

And how do you access it?

#

page does not use middleware by the way

rancid scaffold
#

use beforeLoad in createRoute method instead

hollow saddle
#

I think you are using better auth. I have a similar project. I put it inside beforeLoad block in __root.tsx. and wrap it with tanstack query

hollow saddle
#

sure, but take a note. Im using a separate setup. tanstack start and nestjs. So withhin your code, I see that you are importing the betterAuth instance. But for my code, im using client betterAuth.

this is my __root.tsx

  beforeLoad: async ({ context }) => {
    const session = await context.queryClient.ensureQueryData(
      queryOptions({
        queryKey: AUTH_QUERY_KEY,
        queryFn: () => getSessionFn(),
        staleTime: Infinity, //forever, will be recheck on pages loader
      }),
    )
    return {
      session,
    }
  },

getSessionFn:

import { createServerFn } from '@tanstack/react-start'
import { getRequestHeaders } from '@tanstack/react-start/server'
import { getSession } from '@/lib/auth-client'

export const getSessionFn = createServerFn({ method: 'GET' }).handler(
  async () => {
    const headers = getRequestHeaders()
    return await getSession({
      fetchOptions: {
        headers,
      },
    })
  },
)
#

then in the component you can access it like this:

function RootDocument({ children }: { children: ReactNode }) {
  const { session } = Route.useRouteContext()
  return (
    <html lang="en">
      <head>
        <HeadContent />
      </head>
      <body>
...
#

you can try to use (dashboard)/route.tsx

#

in my case, I just use __root.tsx for the shell.

I have something like this (attach). one for home, one for auth

#

so you use the homepage layout in the public

hollow saddle
#

Im also new tanstack start, but has been 1 month. createRootRoute is only for __root.tsx, it contains the shell, whole html structure. But technically you can put it in the createRootRoute, but the layout will be rendered in authenticated user and guess user.

For a dashboard, I believe you have sign in page. And the layout will be rendered there as well. So I recommend you to use separate route.tsx for the layout.

#

this part using route.tsx

#

haha glad it works out well

hollow saddle
#

For authorization i fetch in the root layout only, inner layouts can just use the session passed from root layout

#

Yea true, i only fetch it from root layout😆

#

Sorry haha. Im not sure it's exist in the docs. But i build it on my own. You can just fetch from __root.tsx. then if exist redirect to dashboard. If its not redirect to login page.

You can access the session throuh context. Everything you return at beforeLoad can be access anywhere in child component through the context

#

Use this one to access it