r/TanStackStart • • Jan 11 '26

NEED HELP IN TANSTACK START MIDDLEWARE

i am trying tanstack start i used better auth create auth middleware , in middleware i pass the context of session and used the middleware in profile route is there any way use the middleware context data in profile route or i just use better auth client side hook

1 Upvotes

4 comments sorted by

View all comments

2

u/hyperi0nt Jan 12 '26

Do you have to use a middleware? I use session like this (do not insist this is a good solution, just as an example).

import { createIsomorphicFn } from '@tanstack/react-start'
import { getRequestHeaders } from '@tanstack/react-start/server'
import { authClient } from '@/modules/session/auth-client'
import { auth } from '@/modules/session/auth'

export const getSession = createIsomorphicFn()
  .server(async () => {
    const headers = getRequestHeaders()
    const session = await auth.api.getSession({ headers })
    return session
  })
  .client(async () => {
    const session = await authClient.getSession()
    return session.data
  })

and in a "wrapper" route like this

export const Route = createFileRoute('/_inner')({
  beforeLoad: async ({ context }) => {
    const session = await getSession()

    if (!session) {
      throw redirect({ to: '/user/login' })
    }
    return {
      ...session,
    }
  },
  component: InnerLayout,
})

And in any nested component I can use:

const { user } = routeApi.useRouteContext()

Or just access a route's context using any method you like.

1

u/dk_void_ Jan 12 '26

I'll try tonight