Open History to see the last commit
1import { createServerFn } from '@tanstack/react-start'
2import {
3 useSession,
4 setResponseStatus,
5 setResponseHeader,
6} from '@tanstack/react-start/server'
7import { redirect } from '@tanstack/react-router'
8async function session() {
9 setResponseHeader('Cache-Control', 'private, no-store')
10 const password = process.env.SESSION_PASSWORD
11 if (!password || password.length < 32) {
12 throw new Error('Set SESSION_PASSWORD to at least 32 characters')
13 }
14 return useSession<{ email: string; saved: boolean }>({
15 name: 'start-migration-session',
16 password,
17 })
18}
19export const getAccount = createServerFn({ method: 'GET' }).handler(
20 async () => {
21 const current = await session()
22 return current.data.email
23 ? { email: current.data.email, saved: current.data.saved ?? false }
24 : null
25 },
26)
27export const signIn = createServerFn({ method: 'POST' })
28 .validator((input: { email: string; password: string }) => {
29 if (typeof input.email !== 'string' || typeof input.password !== 'string') {
30 throw new Error('Invalid credentials')
31 }
32 return input
33 })
34 .handler(async ({ data }) => {
35 if (!process.env.DEMO_PASSWORD) {
36 throw new Error('Set DEMO_PASSWORD before running the example')
37 }
38 if (
39 data.email !== 'reader@example.com' ||
40 data.password !== process.env.DEMO_PASSWORD
41 ) {
42 return { error: 'Invalid credentials' }
43 }
44 const current = await session()
45 await current.update({ email: data.email, saved: false })
46 return { error: '' }
47 })
48export const toggleSaved = createServerFn({ method: 'POST' }).handler(
49 async () => {
50 const current = await session()
51 if (!current.data.email) {
52 setResponseStatus(401)
53 throw new Error('Unauthorized')
54 }
55 await current.update({ saved: !current.data.saved })
56 },
57)
58export const signOut = createServerFn({ method: 'POST' }).handler(async () => {
59 const current = await session()
60 await current.clear()
61 throw redirect({ to: '/login' })
62})