How to check for auth with Clerk and Tanstack Start?
Hello,
I followed the guide from Clerk: https://clerk.com/docs/references/tanstack-start/get-auth
The way they are creating createServerFn, seems to be outdated now, and I'm not quite sure how to get the request:
import { createFileRoute, useRouter, redirect } from '@tanstack/react-router'
import { createServerFn } from '@tanstack/start'
import { getAuth } from '@clerk/tanstack-start/server'
const authStateFn = createServerFn('GET', async (_, { request }) => {
const { userId } = await getAuth(request)
if (!userId) {
// This might error if you're redirecting to a path that doesn't exist yet
// You can create a sign-in route to handle this
throw redirect({
to: '/sign-in/$',
})
}
return { userId }
})
export const Route = createFileRoute('/')({
component: Home,
beforeLoad: () => authStateFn(),
loader: async ({ context }) => {
return { userId: context.userId }
},
})
function Home() {
const state = Route.useLoaderData()
return <h1>Welcome! Your ID is {state.userId}!</h1>
}
Looking at the Tanstack documentation, it looks like we need to add handler and/or validation.
https://tanstack.com/router/latest/docs/framework/react/start/server-functions
How can I get the request into the new way of creating server functions?
I followed the guide from Clerk: https://clerk.com/docs/references/tanstack-start/get-auth
The way they are creating createServerFn, seems to be outdated now, and I'm not quite sure how to get the request:
import { createFileRoute, useRouter, redirect } from '@tanstack/react-router'
import { createServerFn } from '@tanstack/start'
import { getAuth } from '@clerk/tanstack-start/server'
const authStateFn = createServerFn('GET', async (_, { request }) => {
const { userId } = await getAuth(request)
if (!userId) {
// This might error if you're redirecting to a path that doesn't exist yet
// You can create a sign-in route to handle this
throw redirect({
to: '/sign-in/$',
})
}
return { userId }
})
export const Route = createFileRoute('/')({
component: Home,
beforeLoad: () => authStateFn(),
loader: async ({ context }) => {
return { userId: context.userId }
},
})
function Home() {
const state = Route.useLoaderData()
return <h1>Welcome! Your ID is {state.userId}!</h1>
}
Looking at the Tanstack documentation, it looks like we need to add handler and/or validation.
https://tanstack.com/router/latest/docs/framework/react/start/server-functions
How can I get the request into the new way of creating server functions?
The getAuth() helper retrieves the authentication state allowing you to protect your API routes or gather relevant data.
Headless, type-safe, powerful utilities for complex workflows like Data Management, Data Visualization, Charts, Tables, and UI Components.

