Open History to see the last commit
1import { createServerFn } from '@tanstack/react-start'
2import { redirect } from '@tanstack/react-router'
3import { useSession } from '@tanstack/react-start/server'
4β
5function getSession() {
6 return useSession<{ email?: string }>({
7 name: 'auth-docs-test',
8 password: 'authentication-docs-browser-test-secret-only-2026',
9 })
10}
11β
12export const getCurrentUserFn = createServerFn({ method: 'GET' }).handler(
13 async () => {
14 const session = await getSession()
15 return session.data.email ? { email: session.data.email } : null
16 },
17)
18β
19export const loginFn = createServerFn({ method: 'POST' })
20 .validator((data: { email: string; password: string }) => data)
21 .handler(async ({ data }) => {
22 // Fixed credentials belong only to this browser-test fixture.
23 if (
24 data.email !== 'reader@example.com' ||
25 data.password !== 'test-password'
26 ) {
27 return { error: 'Invalid credentials' }
28 }
29 const session = await getSession()
30 await session.update({ email: data.email })
31 throw redirect({ to: '/auth-docs/private' })
32 })
33β
34export const logoutFn = createServerFn({ method: 'POST' }).handler(async () => {
35 const session = await getSession()
36 await session.clear()
37 throw redirect({ to: '/auth-docs' })
38})
39β
40export const getPrivateDataFn = createServerFn({ method: 'GET' }).handler(
41 async () => {
42 const session = await getSession()
43 if (!session.data.email) {
44 throw new Error('Unauthorized')
45 }
46 return 'Private account data'
47 },
48)