Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

auth-docs.ts

60 lines1.7 KB

1import { createServerFn } from '@tanstack/react-start'
2import { redirect } from '@tanstack/react-router'
3import { getCookie, setCookie } from '@tanstack/react-start/server'
4import { getIronSession } from 'iron-session'
5​
6function getSession() {
7 return getIronSession<{ email: string }>(
8 { read: getCookie, write: setCookie },
9 {
10 cookieName: 'auth-docs-test',
11 password: 'authentication-docs-browser-test-secret-only-2026',
12 ttl: 60 * 60,
13 cookieOptions: {
14 httpOnly: true,
15 secure: false,
16 sameSite: 'lax',
17 path: '/',
18 },
19 },
20 )
22​
23export const getCurrentUserFn = createServerFn({ method: 'GET' }).handler(
24 async () => {
25 const session = await getSession()
26 return session.email ? { email: session.email } : null
27 },
29​
30export const loginFn = createServerFn({ method: 'POST' })
31 .validator((data: { email: string; password: string }) => data)
32 .handler(async ({ data }) => {
33 // Fixed credentials belong only to this browser-test fixture.
34 if (
35 data.email !== 'reader@example.com' ||
36 data.password !== 'test-password'
37 ) {
38 return { error: 'Invalid credentials' }
39 }
40 const session = await getSession()
41 session.email = data.email
42 await session.save()
43 throw redirect({ to: '/auth-docs/private' })
44 })
45​
46export const logoutFn = createServerFn({ method: 'POST' }).handler(async () => {
47 const session = await getSession()
48 session.destroy()
49 throw redirect({ to: '/auth-docs' })
50})
51​
52export const getPrivateDataFn = createServerFn({ method: 'GET' }).handler(
53 async () => {
54 const session = await getSession()
55 if (!session.email) {
56 throw new Error('Unauthorized')
57 }
58 return 'Private account data'
59 },