diff --git a/docs/start/framework/react/how-to/README.md b/docs/start/framework/react/how-to/README.md
index ad2b1a069e..3807e38bd7 100644
--- a/docs/start/framework/react/how-to/README.md
+++ b/docs/start/framework/react/how-to/README.md
@@ -30,7 +30,7 @@ Core concept that affects every subsequent pattern in TanStack Start.
### **2. How to Create Basic Server Functions**
-**Priority: Foundation** | **Dependencies: #1** | **Status: 📝 Needed**
+**Priority: Foundation** | **Dependencies: #1** | **Status: ✅ Completed**
**GitHub Issues:** [#4533](https://github.com/TanStack/router/issues/4533) (TypeScript issues)
@@ -47,7 +47,7 @@ Core server function concepts before advanced patterns.
### **3. How to Write Type-Safe Server Functions**
-**Priority: Critical** | **Dependencies: #2** | **Status: 🔥 Urgent**
+**Priority: Critical** | **Dependencies: #2** | **Status: ✅ Completed**
**GitHub Issues:** [#4533](https://github.com/TanStack/router/issues/4533) (5 👍)
@@ -456,6 +456,9 @@ Core server function concepts before advanced patterns.
## **Available Guides**
- ✅ [Write Isomorphic, Client-Only, and Server-Only Code](./write-isomorphic-client-server-code.md) - Understand execution boundaries and control where code runs in TanStack Start applications
+- ✅ [Create Basic Server Functions](./create-basic-server-functions.md) - Learn how to create, validate, and use server functions with full type safety
+- ✅ [Write Type-Safe Server Functions](./write-type-safe-server-functions.md) - Optimize TypeScript performance and avoid common type errors in server functions
+- ✅ [Use Server Functions with Forms](./use-server-functions-with-forms.md) - Integrate server functions with forms for validated submissions and file uploads
- ✅ [Use Environment Variables](./use-environment-variables.md) - Set up and use environment variables securely in TanStack Start applications
---
diff --git a/docs/start/framework/react/how-to/create-basic-server-functions.md b/docs/start/framework/react/how-to/create-basic-server-functions.md
new file mode 100644
index 0000000000..6f383b8b82
--- /dev/null
+++ b/docs/start/framework/react/how-to/create-basic-server-functions.md
@@ -0,0 +1,461 @@
+# How to Create Basic Server Functions
+
+Create and use server functions with validation, error handling, and client integration patterns.
+
+## Quick Start
+
+```typescript
+// app/functions/hello.ts
+import { createServerFn } from '@tanstack/start'
+import { z } from 'zod'
+
+export const sayHello = createServerFn()
+ .validator(z.object({ name: z.string() }))
+ .handler(async ({ data }) => {
+ // This runs on the server
+ return { message: `Hello, ${data.name}!` }
+ })
+```
+
+```tsx
+// app/routes/index.tsx
+import { createFileRoute } from '@tanstack/react-router'
+import { useState } from 'react'
+import { sayHello } from '../functions/hello'
+
+export const Route = createFileRoute('/')({
+ component: HomePage,
+})
+
+function HomePage() {
+ const [result, setResult] = useState('')
+
+ const handleSubmit = async () => {
+ try {
+ const response = await sayHello({ data: { name: 'World' } })
+ setResult(response.message)
+ } catch (error) {
+ console.error('Server function failed:', error)
+ }
+ }
+
+ return (
+
+
+ {result &&
{result}
}
+
+ )
+}
+```
+
+## Step-by-Step Implementation
+
+### 1. Create Your First Server Function
+
+Create a new file for your server function:
+
+```typescript
+// app/functions/user.ts
+import { createServerFn } from '@tanstack/start'
+
+// Basic server function without validation
+export const getServerTime = createServerFn()
+ .handler(async () => {
+ return {
+ timestamp: new Date().toISOString(),
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
+ }
+ })
+```
+
+### 2. Add Input Validation
+
+Use validation libraries like Zod or Valibot for type-safe inputs:
+
+#### With Zod
+
+```typescript
+// app/functions/user.ts
+import { createServerFn } from '@tanstack/start'
+import { z } from 'zod'
+
+const CreateUserSchema = z.object({
+ email: z.string().email(),
+ name: z.string().min(2),
+ age: z.number().min(13).optional(),
+})
+
+export const createUser = createServerFn()
+ .validator(CreateUserSchema)
+ .handler(async ({ data }) => {
+ // data is fully typed based on the schema
+ const user = {
+ id: Math.random().toString(36),
+ email: data.email,
+ name: data.name,
+ age: data.age,
+ createdAt: new Date().toISOString(),
+ }
+
+ // Simulate database save
+ console.log('Creating user:', user)
+
+ return user
+ })
+```
+
+#### With Valibot
+
+```typescript
+// app/functions/user.ts
+import { createServerFn } from '@tanstack/start'
+import { object, string, number, email, minLength, minValue, optional } from 'valibot'
+
+const CreateUserSchema = object({
+ email: string([email()]),
+ name: string([minLength(2)]),
+ age: optional(number([minValue(13)])),
+})
+
+export const createUser = createServerFn()
+ .validator(CreateUserSchema)
+ .handler(async ({ data }) => {
+ // Implementation same as above
+ })
+```
+
+### 3. HTTP Methods
+
+Server functions support GET and POST (POST is default):
+
+```typescript
+// POST (default)
+export const createUser = createServerFn()
+ .validator(z.object({ name: z.string() }))
+ .handler(async ({ data }) => {
+ return { id: 1, name: data.name }
+ })
+
+// GET with query parameters
+export const getUserById = createServerFn({ method: 'GET' })
+ .validator(z.object({ id: z.string() }))
+ .handler(async ({ data }) => {
+ return { id: data.id, name: 'John Doe' }
+ })
+```
+
+
+
+### 4. Using Server Functions in Loaders
+
+```tsx
+// app/functions/users.ts
+export const getUsers = createServerFn({ method: 'GET' })
+ .handler(async () => {
+ return await db.users.findMany()
+ })
+
+export const getUserById = createServerFn({ method: 'GET' })
+ .validator(z.object({ id: z.string() }))
+ .handler(async ({ data }) => {
+ const user = await db.users.findById(data.id)
+ if (!user) throw new Error('User not found')
+ return user
+ })
+```
+
+```tsx
+// app/routes/users/index.tsx
+import { createFileRoute } from '@tanstack/react-router'
+import { getUsers } from '../../functions/users'
+
+export const Route = createFileRoute('/users/')({
+ loader: async () => {
+ const users = await getUsers()
+ return { users }
+ },
+ component: UsersPage,
+})
+
+function UsersPage() {
+ const { users } = Route.useLoaderData()
+
+ return (
+
+
Users
+ {users.map(user => (
+
+
{user.name}
+
{user.email}
+
+ ))}
+
+ )
+}
+```
+
+```tsx
+// app/routes/users/$userId.tsx
+import { createFileRoute } from '@tanstack/react-router'
+import { getUserById } from '../../functions/users'
+
+export const Route = createFileRoute('/users/$userId')({
+ loader: async ({ params }) => {
+ const user = await getUserById({ data: { id: params.userId } })
+ return { user }
+ },
+ component: UserDetail,
+})
+
+function UserDetail() {
+ const { user } = Route.useLoaderData()
+
+ return (
+
+
{user.name}
+
Email: {user.email}
+
Created: {new Date(user.createdAt).toLocaleDateString()}
+
+ )
+}
+```
+
+### 5. Using Server Functions in Client Components
+
+```tsx
+import { useState } from 'react'
+import { createUser } from '../functions/users'
+
+function CreateUserForm() {
+ const [loading, setLoading] = useState(false)
+ const [error, setError] = useState('')
+
+ const handleCreateUser = async () => {
+ setLoading(true)
+ setError('')
+
+ try {
+ await createUser({
+ data: { email: 'user@example.com', name: 'New User', age: 25 }
+ })
+ // Optionally refresh or navigate
+ } catch (err) {
+ setError(err.message)
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ return (
+
+
+ {error &&
Error: {error}
}
+
+ )
+}
+```
+
+
+
+### 6. File Organization
+
+```
+app/functions/
+├── auth.ts # Authentication functions
+├── users.ts # User management
+└── posts.ts # Content functions
+```
+
+```typescript
+// app/functions/users.ts
+export const getUsers = createServerFn()...
+export const createUser = createServerFn()...
+export const updateUser = createServerFn()...
+```
+
+## Production Checklist
+
+### Security
+
+- [ ] **Input Validation**: All server functions use proper validation schemas
+- [ ] **Error Handling**: Sensitive information not exposed in error messages
+- [ ] **Authorization**: Access control implemented where needed
+- [ ] **Rate Limiting**: Consider implementing rate limiting for public endpoints
+
+### Performance
+
+- [ ] **Efficient Queries**: Database queries are optimized
+- [ ] **Caching**: Implement caching where appropriate
+- [ ] **Error Boundaries**: Client components handle server function errors gracefully
+- [ ] **Loading States**: UI shows loading indicators during server function calls
+
+### Type Safety
+
+- [ ] **Validation Schemas**: All inputs validated with Zod/Valibot
+- [ ] **Return Types**: Server functions have explicit return types
+- [ ] **Error Types**: Custom error classes for different error scenarios
+- [ ] **Client Integration**: TypeScript correctly infers types in client code
+
+### Testing
+
+- [ ] **Unit Tests**: Server function logic tested in isolation
+- [ ] **Integration Tests**: End-to-end testing of client-server communication
+- [ ] **Error Scenarios**: Error handling paths tested
+- [ ] **Validation Testing**: Input validation edge cases covered
+
+## Common Problems
+
+### Problem: "Cannot read properties of undefined" when calling server functions
+
+**Cause**: Server function not properly imported or called incorrectly.
+
+**Solution**:
+```typescript
+// ❌ Incorrect - missing await
+const result = getUserById({ data: { id: '123' } })
+
+// ✅ Correct - with await
+const result = await getUserById({ data: { id: '123' } })
+
+// ❌ Incorrect - wrong import path
+import { getUserById } from './wrong-path'
+
+// ✅ Correct - proper import path
+import { getUserById } from '../functions/database'
+```
+
+### Problem: Validation errors not being caught properly
+
+**Cause**: Missing error handling or incorrect validation schema.
+
+**Solution**:
+```typescript
+// ❌ Incorrect - validation error not handled
+try {
+ const result = await createUser({ data: { email: 'invalid' } })
+} catch (error) {
+ // This won't catch validation errors properly
+ console.log(error.message)
+}
+
+// ✅ Correct - proper error handling
+try {
+ const result = await createUser({ data: { email: 'invalid' } })
+} catch (error) {
+ if (error.message.includes('validation')) {
+ // Handle validation error
+ setValidationError(error.message)
+ } else {
+ // Handle other errors
+ setGeneralError(error.message)
+ }
+}
+```
+
+### Problem: TypeScript errors with server function types
+
+**Cause**: Missing or incorrect validation schema types.
+
+**Solution**:
+```typescript
+// ❌ Incorrect - schema and handler types don't match
+const updateUser = createServerFn()
+ .validator(z.object({ id: z.string() }))
+ .handler(async ({ data }) => {
+ // TypeScript error: data.id is string but treating as number
+ const userId = parseInt(data.id)
+ return { id: userId }
+ })
+
+// ✅ Correct - consistent types
+const updateUser = createServerFn()
+ .validator(z.object({ id: z.string() }))
+ .handler(async ({ data }) => {
+ const userId = parseInt(data.id, 10)
+ return { id: userId }
+ })
+```
+
+### Problem: Server function errors not reaching client
+
+**Cause**: Errors being swallowed or not properly thrown.
+
+**Solution**:
+```typescript
+// ❌ Incorrect - error swallowed
+export const riskyFunction = createServerFn()
+ .handler(async () => {
+ try {
+ // risky operation
+ return { success: true }
+ } catch (error) {
+ console.error(error) // Error logged but not thrown
+ return { success: false } // Client doesn't know about error
+ }
+ })
+
+// ✅ Correct - error properly propagated
+export const riskyFunction = createServerFn()
+ .handler(async () => {
+ try {
+ // risky operation
+ return { success: true }
+ } catch (error) {
+ console.error('Server function error:', error)
+ throw new Error('Operation failed. Please try again.')
+ }
+ })
+```
+
+### Problem: Performance issues with large payloads
+
+**Cause**: Sending too much data through server functions.
+
+**Solution**:
+```typescript
+// ❌ Incorrect - sending large objects
+export const processLargeData = createServerFn()
+ .validator(z.object({
+ data: z.array(z.object({
+ // Large complex object
+ }))
+ }))
+ .handler(async ({ data }) => {
+ // Processing large payload
+ })
+
+// ✅ Correct - use pagination or streaming
+export const processDataBatch = createServerFn()
+ .validator(z.object({
+ batchId: z.string(),
+ offset: z.number(),
+ limit: z.number().max(100)
+ }))
+ .handler(async ({ data }) => {
+ // Process smaller batches
+ })
+```
+
+## Common Next Steps
+
+After setting up basic server functions, you might want to:
+
+- [Write Type-Safe Server Functions](./write-type-safe-server-functions.md) - Optimize TypeScript performance and avoid common type errors
+- [Use Server Functions with Forms](./use-server-functions-with-forms.md) - Integrate server functions with forms for validated submissions
+
+
+
+## Related Resources
+
+- [TanStack Start Server Functions Documentation](../server-functions.md)
+- [Write Isomorphic, Client-Only, and Server-Only Code](./write-isomorphic-client-server-code.md)
+- [Zod Validation Library](https://zod.dev/)
+- [Valibot Validation Library](https://valibot.dev/)
+- [GitHub Issue #4533: Server Function TypeScript Issues](https://github.com/TanStack/router/issues/4533)
\ No newline at end of file
diff --git a/docs/start/framework/react/how-to/use-server-functions-with-forms.md b/docs/start/framework/react/how-to/use-server-functions-with-forms.md
new file mode 100644
index 0000000000..f897e59537
--- /dev/null
+++ b/docs/start/framework/react/how-to/use-server-functions-with-forms.md
@@ -0,0 +1,700 @@
+# How to Use Server Functions with Forms
+
+Integrate server functions with forms for validated submissions, file uploads, and multi-step workflows.
+
+## Quick Start
+
+```tsx
+// app/functions/contact.ts
+import { createServerFn } from '@tanstack/start'
+import { z } from 'zod'
+
+const ContactFormSchema = z.object({
+ name: z.string().min(2, 'Name must be at least 2 characters'),
+ email: z.string().email('Invalid email address'),
+ message: z.string().min(10, 'Message must be at least 10 characters')
+})
+
+export const submitContactForm = createServerFn()
+ .validator(ContactFormSchema)
+ .handler(async ({ data }) => {
+ // Process form submission
+ console.log('Contact form submitted:', data)
+
+ // Simulate processing delay
+ await new Promise(resolve => setTimeout(resolve, 1000))
+
+ return {
+ success: true,
+ message: 'Thank you for your message!'
+ }
+ })
+```
+
+```tsx
+// app/routes/contact.tsx
+import { createFileRoute } from '@tanstack/react-router'
+import { useState } from 'react'
+import { submitContactForm } from '../functions/contact'
+
+export const Route = createFileRoute('/contact')({
+ component: ContactForm,
+})
+
+function ContactForm() {
+ const [formData, setFormData] = useState({
+ name: '',
+ email: '',
+ message: ''
+ })
+ const [submitting, setSubmitting] = useState(false)
+ const [result, setResult] = useState(null)
+ const [errors, setErrors] = useState({})
+
+ const handleSubmit = async (e) => {
+ e.preventDefault()
+ setSubmitting(true)
+ setErrors({})
+
+ try {
+ const response = await submitContactForm({ data: formData })
+ setResult(response)
+ setFormData({ name: '', email: '', message: '' }) // Reset form
+ } catch (error) {
+ setErrors({ general: error.message })
+ } finally {
+ setSubmitting(false)
+ }
+ }
+
+ return (
+
+ )
+}
+```
+
+## Step-by-Step Implementation
+
+### 1. Create Form Server Functions
+
+Define server functions with proper validation for form data:
+
+```typescript
+// app/functions/user.ts
+import { createServerFn } from '@tanstack/start'
+import { z } from 'zod'
+
+// User registration form
+const RegisterSchema = z.object({
+ username: z.string().min(3).max(20),
+ email: z.string().email(),
+ password: z.string().min(8),
+ confirmPassword: z.string()
+}).refine(data => data.password === data.confirmPassword, {
+ message: "Passwords don't match",
+ path: ["confirmPassword"]
+})
+
+export const registerUser = createServerFn()
+ .validator(RegisterSchema)
+ .handler(async ({ data }) => {
+ // Check if user already exists
+ const existingUser = await checkUserExists(data.email)
+ if (existingUser) {
+ throw new Error('User with this email already exists')
+ }
+
+ // Create user (exclude confirmPassword from stored data)
+ const { confirmPassword, ...userData } = data
+ const user = await createUser(userData)
+
+ return {
+ success: true,
+ userId: user.id,
+ message: 'Account created successfully!'
+ }
+ })
+
+// Profile update form
+const UpdateProfileSchema = z.object({
+ userId: z.string(),
+ firstName: z.string().min(1),
+ lastName: z.string().min(1),
+ bio: z.string().max(500).optional(),
+ website: z.string().url().optional().or(z.literal(''))
+})
+
+export const updateProfile = createServerFn()
+ .validator(UpdateProfileSchema)
+ .handler(async ({ data }) => {
+ const updatedUser = await updateUserProfile(data.userId, {
+ firstName: data.firstName,
+ lastName: data.lastName,
+ bio: data.bio || null,
+ website: data.website || null
+ })
+
+ return {
+ success: true,
+ user: updatedUser,
+ message: 'Profile updated successfully!'
+ }
+ })
+```
+
+### 2. Handle Form Validation
+
+Implement client-side and server-side validation:
+
+```tsx
+// app/routes/register.tsx
+import { createFileRoute } from '@tanstack/react-router'
+import { useState } from 'react'
+import { registerUser } from '../functions/user'
+
+export const Route = createFileRoute('/register')({
+ component: RegisterForm,
+})
+
+function RegisterForm() {
+ const [formData, setFormData] = useState({
+ username: '',
+ email: '',
+ password: '',
+ confirmPassword: ''
+ })
+ const [errors, setErrors] = useState({})
+ const [submitting, setSubmitting] = useState(false)
+
+ // Client-side validation
+ const validateField = (name, value) => {
+ const newErrors = { ...errors }
+
+ switch (name) {
+ case 'username':
+ if (value.length < 3) {
+ newErrors.username = 'Username must be at least 3 characters'
+ } else {
+ delete newErrors.username
+ }
+ break
+ case 'email':
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
+ if (!emailRegex.test(value)) {
+ newErrors.email = 'Invalid email address'
+ } else {
+ delete newErrors.email
+ }
+ break
+ case 'password':
+ if (value.length < 8) {
+ newErrors.password = 'Password must be at least 8 characters'
+ } else {
+ delete newErrors.password
+ }
+ break
+ case 'confirmPassword':
+ if (value !== formData.password) {
+ newErrors.confirmPassword = "Passwords don't match"
+ } else {
+ delete newErrors.confirmPassword
+ }
+ break
+ }
+
+ setErrors(newErrors)
+ }
+
+ const handleChange = (e) => {
+ const { name, value } = e.target
+ setFormData(prev => ({ ...prev, [name]: value }))
+ validateField(name, value)
+ }
+
+ const handleSubmit = async (e) => {
+ e.preventDefault()
+ setSubmitting(true)
+ setErrors({})
+
+ try {
+ const result = await registerUser({ data: formData })
+ alert(result.message)
+ // Redirect to login or dashboard
+ } catch (error) {
+ setErrors({ general: error.message })
+ } finally {
+ setSubmitting(false)
+ }
+ }
+
+ return (
+
+ )
+}
+```
+
+### 3. Handle File Uploads
+
+Integrate file uploads with server functions:
+
+```typescript
+// app/functions/upload.ts
+import { createServerFn } from '@tanstack/start'
+import { z } from 'zod'
+
+const FileUploadSchema = z.object({
+ file: z.instanceof(File),
+ description: z.string().optional()
+})
+
+export const uploadFile = createServerFn()
+ .validator(FileUploadSchema)
+ .handler(async ({ data }) => {
+ const { file, description } = data
+
+ // Validate file type and size
+ const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']
+ if (!allowedTypes.includes(file.type)) {
+ throw new Error('Invalid file type. Only JPEG, PNG, and GIF are allowed.')
+ }
+
+ if (file.size > 5 * 1024 * 1024) { // 5MB limit
+ throw new Error('File size must be less than 5MB')
+ }
+
+ // Process file upload (save to storage, etc.)
+ const fileUrl = await saveFileToStorage(file)
+
+ return {
+ success: true,
+ fileUrl,
+ fileName: file.name,
+ description
+ }
+ })
+```
+
+```tsx
+// app/routes/upload.tsx
+import { createFileRoute } from '@tanstack/react-router'
+import { useState } from 'react'
+import { uploadFile } from '../functions/upload'
+
+export const Route = createFileRoute('/upload')({
+ component: FileUploadForm,
+})
+
+function FileUploadForm() {
+ const [file, setFile] = useState(null)
+ const [description, setDescription] = useState('')
+ const [uploading, setUploading] = useState(false)
+ const [result, setResult] = useState(null)
+ const [error, setError] = useState('')
+
+ const handleFileChange = (e) => {
+ const selectedFile = e.target.files[0]
+ setFile(selectedFile)
+ setError('')
+ }
+
+ const handleSubmit = async (e) => {
+ e.preventDefault()
+
+ if (!file) {
+ setError('Please select a file')
+ return
+ }
+
+ setUploading(true)
+ setError('')
+
+ try {
+ const response = await uploadFile({
+ data: { file, description }
+ })
+ setResult(response)
+ setFile(null)
+ setDescription('')
+ // Reset file input
+ e.target.reset()
+ } catch (error) {
+ setError(error.message)
+ } finally {
+ setUploading(false)
+ }
+ }
+
+ return (
+
+ )
+}
+```
+
+### 4. Multi-Step Forms
+
+Handle complex multi-step forms with server functions:
+
+```typescript
+// app/functions/onboarding.ts
+import { createServerFn } from '@tanstack/start'
+import { z } from 'zod'
+
+// Step 1: Basic info
+const BasicInfoSchema = z.object({
+ sessionId: z.string(),
+ firstName: z.string().min(1),
+ lastName: z.string().min(1),
+ email: z.string().email()
+})
+
+export const saveBasicInfo = createServerFn()
+ .validator(BasicInfoSchema)
+ .handler(async ({ data }) => {
+ await saveOnboardingStep(data.sessionId, 'basicInfo', data)
+ return { success: true, nextStep: 'preferences' }
+ })
+
+// Step 2: Preferences
+const PreferencesSchema = z.object({
+ sessionId: z.string(),
+ theme: z.enum(['light', 'dark']),
+ language: z.string(),
+ notifications: z.boolean()
+})
+
+export const savePreferences = createServerFn()
+ .validator(PreferencesSchema)
+ .handler(async ({ data }) => {
+ await saveOnboardingStep(data.sessionId, 'preferences', data)
+ return { success: true, nextStep: 'complete' }
+ })
+
+// Final step: Complete onboarding
+const CompleteOnboardingSchema = z.object({
+ sessionId: z.string()
+})
+
+export const completeOnboarding = createServerFn()
+ .validator(CompleteOnboardingSchema)
+ .handler(async ({ data }) => {
+ const onboardingData = await getOnboardingData(data.sessionId)
+ const user = await createUserFromOnboarding(onboardingData)
+ await clearOnboardingSession(data.sessionId)
+
+ return {
+ success: true,
+ userId: user.id,
+ message: 'Welcome! Your account has been created.'
+ }
+ })
+```
+
+### 5. Form State Management
+
+Create reusable form utilities:
+
+```tsx
+// app/utils/useForm.ts
+import { useState } from 'react'
+
+export function useForm(initialValues, validationRules = {}) {
+ const [values, setValues] = useState(initialValues)
+ const [errors, setErrors] = useState({})
+ const [submitting, setSubmitting] = useState(false)
+
+ const setValue = (name, value) => {
+ setValues(prev => ({ ...prev, [name]: value }))
+
+ // Clear error when user starts typing
+ if (errors[name]) {
+ setErrors(prev => ({ ...prev, [name]: undefined }))
+ }
+
+ // Run validation if rules exist
+ if (validationRules[name]) {
+ const error = validationRules[name](value, values)
+ if (error) {
+ setErrors(prev => ({ ...prev, [name]: error }))
+ }
+ }
+ }
+
+ const handleChange = (e) => {
+ const { name, value, type, checked } = e.target
+ setValue(name, type === 'checkbox' ? checked : value)
+ }
+
+ const handleSubmit = (serverFn) => async (e) => {
+ e.preventDefault()
+ setSubmitting(true)
+ setErrors({})
+
+ try {
+ const result = await serverFn({ data: values })
+ return result
+ } catch (error) {
+ setErrors({ general: error.message })
+ throw error
+ } finally {
+ setSubmitting(false)
+ }
+ }
+
+ const reset = () => {
+ setValues(initialValues)
+ setErrors({})
+ setSubmitting(false)
+ }
+
+ return {
+ values,
+ errors,
+ submitting,
+ setValue,
+ handleChange,
+ handleSubmit,
+ reset,
+ isValid: Object.keys(errors).length === 0
+ }
+}
+```
+
+```tsx
+// Using the form utility
+import { useForm } from '../utils/useForm'
+import { registerUser } from '../functions/user'
+
+function RegistrationForm() {
+ const form = useForm(
+ { username: '', email: '', password: '', confirmPassword: '' },
+ {
+ username: (value) => value.length < 3 ? 'Username too short' : null,
+ email: (value) => !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value) ? 'Invalid email' : null,
+ password: (value) => value.length < 8 ? 'Password too short' : null,
+ confirmPassword: (value, values) => value !== values.password ? "Passwords don't match" : null
+ }
+ )
+
+ const onSubmit = form.handleSubmit(registerUser)
+
+ return (
+
+ )
+}
+```
+
+## Production Checklist
+
+### Form Security
+- [ ] **Input Validation**: Both client and server-side validation implemented
+- [ ] **CSRF Protection**: Consider implementing CSRF tokens for sensitive forms
+- [ ] **Rate Limiting**: Prevent form spam and abuse
+- [ ] **File Upload Security**: Validate file types, sizes, and scan for malware
+
+### User Experience
+- [ ] **Loading States**: Show loading indicators during form submission
+- [ ] **Error Handling**: Clear, actionable error messages
+- [ ] **Success Feedback**: Confirm successful form submissions
+- [ ] **Form Persistence**: Save form data during navigation (when appropriate)
+
+### Performance
+- [ ] **Debounced Validation**: Avoid excessive validation calls
+- [ ] **Optimistic Updates**: Show immediate feedback when possible
+- [ ] **Form Reset**: Clear sensitive data after submission
+- [ ] **File Size Limits**: Prevent large file uploads from blocking the UI
+
+## Common Problems
+
+### Problem: Form submits multiple times
+
+**Cause**: Missing disabled state or event handling issues.
+
+**Solution**:
+```tsx
+// ❌ Can submit multiple times
+
+
+// ✅ Prevents multiple submissions
+
+```
+
+### Problem: File uploads not working with server functions
+
+**Cause**: Incorrect data handling or missing File validation.
+
+**Solution**:
+```typescript
+// ✅ Proper file handling
+const schema = z.object({
+ file: z.instanceof(File)
+})
+
+export const uploadFile = createServerFn()
+ .validator(schema)
+ .handler(async ({ data }) => {
+ const { file } = data
+ // Process the File object
+ })
+```
+
+### Problem: Form validation out of sync
+
+**Cause**: Client and server validation schemas differ.
+
+**Solution**:
+```typescript
+// ✅ Shared validation schema
+// shared/schemas.ts
+export const ContactFormSchema = z.object({
+ name: z.string().min(2),
+ email: z.string().email(),
+ message: z.string().min(10)
+})
+
+// Use same schema on client and server
+import { ContactFormSchema } from '../shared/schemas'
+```
+
+## Related Resources
+
+- [Create Basic Server Functions](./create-basic-server-functions.md) - Foundation concepts
+- [Write Type-Safe Server Functions](./write-type-safe-server-functions.md) - Advanced TypeScript patterns
+- [Zod Validation Documentation](https://zod.dev/)
+- [HTML Form Validation](https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation)
\ No newline at end of file
diff --git a/docs/start/framework/react/how-to/write-isomorphic-client-server-code.md b/docs/start/framework/react/how-to/write-isomorphic-client-server-code.md
index 452760464f..61546acea4 100644
--- a/docs/start/framework/react/how-to/write-isomorphic-client-server-code.md
+++ b/docs/start/framework/react/how-to/write-isomorphic-client-server-code.md
@@ -1,13 +1,13 @@
# How to Write Isomorphic, Client-Only, and Server-Only Code
-This guide covers TanStack Start's execution model and APIs for controlling where code runs.
+Learn TanStack Start's execution model and when to constrain code to specific environments.
-## Core Principle: Isomorphic by Default
+## Execution Model: Isomorphic by Default
-**All code in TanStack Start is isomorphic by default** - it runs and is included in both server and client bundles unless explicitly constrained.
+**All code runs on both server and client unless explicitly constrained.**
```tsx
-// ✅ This runs on BOTH server and client
+// ✅ Isomorphic - runs everywhere
function formatPrice(price: number) {
return new Intl.NumberFormat('en-US', {
style: 'currency',
@@ -15,238 +15,145 @@ function formatPrice(price: number) {
}).format(price)
}
-// ✅ Route loaders are ISOMORPHIC
+// ✅ Route loaders are isomorphic (server during SSR, client during navigation)
export const Route = createFileRoute('/products')({
loader: async () => {
- // This runs on server during SSR AND on client during navigation
const response = await fetch('/api/products')
return response.json()
}
})
```
-**Important**: Route `loader`s are isomorphic - they run on both server and client.
+## Execution Constraint APIs
----
-
-## When You Need Execution Constraints
-
-### Server-Only APIs
-
-| API | Use Case | Client Behavior |
-|-----|----------|-----------------|
+| API | Use Case | Opposite Environment |
+|-----|----------|---------------------|
| `createServerFn()` | RPC calls, data mutations | Network request to server |
-| `serverOnly(fn)` | Utility functions | Throws error |
+| `serverOnly(fn)` | Secrets, server utilities | Throws error |
+| `clientOnly(fn)` | Browser APIs, DOM | Throws error |
+| `` | Hydration-safe components | Renders fallback |
+## When to Use Each Pattern
+
+### Server Functions (RPC Pattern)
```tsx
-import { createServerFn, serverOnly } from '@tanstack/react-start'
+import { createServerFn } from '@tanstack/start'
-// RPC: Server execution, callable from client
-const updateUser = createServerFn({ method: 'POST' })
- .validator((data: UserData) => data)
+// Client can call this via network request
+const updateUser = createServerFn()
+ .validator(z.object({ id: z.string(), name: z.string() }))
.handler(async ({ data }) => {
- // Only runs on server, but client can call it
- return await db.users.update(data)
+ return await db.users.update(data.id, { name: data.name })
})
-// Utility: Server-only, client crashes if called
-const getEnvVar = serverOnly(() => process.env.DATABASE_URL)
+// Usage from client
+const result = await updateUser({ data: { id: '1', name: 'John' } })
```
-### Client-Only APIs
-
-| API | Use Case | Server Behavior |
-|-----|----------|-----------------|
-| `clientOnly(fn)` | Browser utilities | Throws error |
-| `` | Components needing browser APIs | Renders fallback |
-
+### Server-Only Utilities
```tsx
-import { clientOnly } from '@tanstack/react-start'
+import { serverOnly } from '@tanstack/start'
+
+// Crashes if called from client
+const getSecret = serverOnly(() => process.env.SECRET_KEY)
+
+// Use in server functions, loaders, or server components
+const secret = getSecret() // ✅ Works in server contexts only
+```
+
+### Client-Only Code
+```tsx
+import { clientOnly } from '@tanstack/start'
import { ClientOnly } from '@tanstack/react-router'
-// Utility: Client-only, server crashes if called
-const saveToStorage = clientOnly((key: string, value: any) => {
- localStorage.setItem(key, JSON.stringify(value))
+// Crashes if called from server
+const saveToStorage = clientOnly((key: string, value: string) => {
+ localStorage.setItem(key, value)
})
-// Component: Only renders children after hydration
-function Analytics() {
+// Component that only renders after hydration
+function BrowserOnlyFeature() {
return (
-
-
+ Loading...}>
+
)
}
```
-### Environment-Specific Implementations
-
+### Manual Environment Detection
```tsx
-import { createIsomorphicFn } from '@tanstack/react-start'
-
-// Different implementation per environment
-const getDeviceInfo = createIsomorphicFn()
- .server(() => ({ type: 'server', platform: process.platform }))
- .client(() => ({ type: 'client', userAgent: navigator.userAgent }))
+// When you need custom logic for each environment
+function logEvent(event: string) {
+ if (typeof window !== 'undefined') {
+ // Client: Analytics
+ gtag('event', event)
+ } else {
+ // Server: Logging
+ console.log(`Server event: ${event}`)
+ }
+}
```
----
-
## Key Distinctions
### `createServerFn()` vs `serverOnly()`
```tsx
-// createServerFn: RPC pattern - server execution, client callable
+// createServerFn: Client can call via network
const fetchUser = createServerFn()
.handler(async () => await db.users.find())
-// Usage from client component:
-const user = await fetchUser() // ✅ Network request
+const user = await fetchUser() // ✅ Works from client (network request)
-// serverOnly: Crashes if called from client
+// serverOnly: Pure server constraint
const getSecret = serverOnly(() => process.env.SECRET)
-// Usage from client:
-const secret = getSecret() // ❌ Throws error
+const secret = getSecret() // ❌ Crashes if called from client
```
-### Manual Environment Detection vs APIs
+### `clientOnly()` vs ``
```tsx
-// Manual: You handle the logic
-function logMessage(msg: string) {
- if (typeof window === 'undefined') {
- console.log(`[SERVER]: ${msg}`)
- } else {
- console.log(`[CLIENT]: ${msg}`)
- }
-}
+// clientOnly: Function constraint
+const analytics = clientOnly(() => gtag('event', 'click'))
-// API: Framework handles it
-const logMessage = createIsomorphicFn()
- .server((msg) => console.log(`[SERVER]: ${msg}`))
- .client((msg) => console.log(`[CLIENT]: ${msg}`))
+// ClientOnly: Component constraint (handles hydration)
+}>
+
+
```
----
-
-## Common Patterns
-
-### Progressive Enhancement
-
-```tsx
-// Component works without JS, enhanced with JS
-function SearchForm() {
- const [query, setQuery] = useState('')
-
- return (
-
- )
-}
-```
-
-### Environment-Aware Storage
-
-```tsx
-const storage = createIsomorphicFn()
- .server((key: string) => {
- // Server: File-based cache
- const fs = require('node:fs')
- return JSON.parse(fs.readFileSync('.cache', 'utf-8'))[key]
- })
- .client((key: string) => {
- // Client: localStorage
- return JSON.parse(localStorage.getItem(key) || 'null')
- })
-```
-
----
-
-## Common Problems
-
-### Environment Variable Exposure
-
-```tsx
-// ❌ Exposes to client bundle
-const apiKey = process.env.SECRET_KEY
-
-// ✅ Server-only access
-const apiKey = serverOnly(() => process.env.SECRET_KEY)
-```
-
-### Incorrect Loader Assumptions
-
-```tsx
-// ❌ Assuming loader is server-only
-export const Route = createFileRoute('/users')({
- loader: () => {
- // This runs on BOTH server and client!
- const secret = process.env.SECRET // Exposed to client
- return fetch(`/api/users?key=${secret}`)
- }
-})
-
-// ✅ Use server function for server-only operations
-const getUsersSecurely = createServerFn().handler(() => {
- const secret = process.env.SECRET // Server-only
- return fetch(`/api/users?key=${secret}`)
-})
-
-export const Route = createFileRoute('/users')({
- loader: () => getUsersSecurely() // Isomorphic call to server function
-})
-```
-
-### Hydration Mismatches
-
-```tsx
-// ❌ Different content server vs client
-function CurrentTime() {
- return {new Date().toLocaleString()}
-}
-
-// ✅ Consistent rendering
-function CurrentTime() {
- const [time, setTime] = useState()
-
- useEffect(() => {
- setTime(new Date().toLocaleString())
- }, [])
-
- return {time || 'Loading...'}
-}
-```
-
----
-
## Production Checklist
-- [ ] **Bundle Analysis**: Verify server-only code isn't in client bundle
-- [ ] **Environment Variables**: Ensure secrets use `serverOnly()` or `createServerFn()`
-- [ ] **Loader Logic**: Remember loaders are isomorphic, not server-only
-- [ ] **ClientOnly Fallbacks**: Provide appropriate fallbacks to prevent layout shift
-- [ ] **Error Boundaries**: Handle server/client execution errors gracefully
+### Security
+- [ ] **Secrets**: Use `serverOnly()` for environment variables and sensitive data
+- [ ] **Validation**: Server functions validate all inputs
+- [ ] **Client Code**: No sensitive logic in client-accessible code
----
+### Performance
+- [ ] **Bundle Size**: Use constraints to exclude code from appropriate bundles
+- [ ] **Hydration**: Use `` for components requiring browser APIs
+- [ ] **Network**: Minimize server function call frequency
+
+### Type Safety
+- [ ] **Server Functions**: Proper validation schemas
+- [ ] **Environment Detection**: Consistent patterns across codebase
+- [ ] **Error Handling**: Graceful degradation when constraints are violated
+
+## Common Next Steps
+
+After understanding isomorphic code patterns, you might want to:
+
+- [Create Basic Server Functions](./create-basic-server-functions.md) - Learn how to create server functions with validation and error handling
+
+
## Related Resources
- [TanStack Start Server Functions Guide](../server-functions.md)
- [TanStack Start Middleware Guide](../middleware.md)
-- [TanStack Router SSR Guide](../../../router/framework/react/how-to/setup-ssr.md)
-
-
\ No newline at end of file
+- [TanStack Router SSR Guide](../../../router/framework/react/how-to/setup-ssr.md)
\ No newline at end of file
diff --git a/docs/start/framework/react/how-to/write-type-safe-server-functions.md b/docs/start/framework/react/how-to/write-type-safe-server-functions.md
new file mode 100644
index 0000000000..ceef011281
--- /dev/null
+++ b/docs/start/framework/react/how-to/write-type-safe-server-functions.md
@@ -0,0 +1,219 @@
+# How to Write Type-Safe Server Functions
+
+Ensure type safety in server functions using TanStack Start's validation APIs and TypeScript inference.
+
+## Quick Start
+
+```typescript
+// ✅ Type-safe with validation
+import { createServerFn } from '@tanstack/start'
+import { z } from 'zod'
+
+const CreateUserSchema = z.object({
+ email: z.string().email(),
+ name: z.string().min(2),
+ age: z.number().min(13).optional()
+})
+
+export const createUser = createServerFn()
+ .validator(CreateUserSchema)
+ .handler(async ({ data }) => {
+ // data is fully typed based on schema
+ const user = await db.users.create({
+ email: data.email,
+ name: data.name,
+ age: data.age
+ })
+ return user // TypeScript infers return type
+ })
+```
+
+## Input Validation
+
+### Zod Integration
+
+```typescript
+import { z } from 'zod'
+
+const UpdateProfileSchema = z.object({
+ userId: z.string(),
+ profile: z.object({
+ firstName: z.string().min(1),
+ lastName: z.string().min(1),
+ bio: z.string().max(500).optional()
+ })
+})
+
+export const updateProfile = createServerFn()
+ .validator(UpdateProfileSchema)
+ .handler(async ({ data }) => {
+ // data.userId is string
+ // data.profile.firstName is string
+ // data.profile.bio is string | undefined
+ return await db.profiles.update(data.userId, data.profile)
+ })
+```
+
+### Valibot Integration
+
+```typescript
+import { object, string, number, email, minLength, minValue, optional } from 'valibot'
+
+const CreateUserSchema = object({
+ email: string([email()]),
+ name: string([minLength(2)]),
+ age: optional(number([minValue(13)]))
+})
+
+export const createUser = createServerFn()
+ .validator(CreateUserSchema)
+ .handler(async ({ data }) => {
+ // Fully typed based on Valibot schema
+ return await db.users.create(data)
+ })
+```
+
+## Error Handling
+
+```typescript
+export const getUserById = createServerFn()
+ .validator(z.object({ id: z.string() }))
+ .handler(async ({ data }) => {
+ const user = await db.users.findById(data.id)
+
+ if (!user) {
+ throw new Error('User not found')
+ }
+
+ return user
+ })
+
+// Client usage with type safety
+try {
+ const user = await getUserById({ data: { id: 'user-123' } })
+ // user is fully typed
+} catch (error) {
+ // Handle validation or runtime errors
+ console.error(error.message)
+}
+```
+
+## Schema Composition
+
+```typescript
+// Reusable schemas
+const UserIdSchema = z.object({
+ userId: z.string()
+})
+
+const ProfileDataSchema = z.object({
+ firstName: z.string(),
+ lastName: z.string(),
+ email: z.string().email()
+})
+
+// Compose schemas
+const UpdateUserSchema = UserIdSchema.merge(
+ z.object({
+ profile: ProfileDataSchema
+ })
+)
+
+export const updateUser = createServerFn()
+ .validator(UpdateUserSchema)
+ .handler(async ({ data }) => {
+ return await db.users.update(data.userId, data.profile)
+ })
+```
+
+## File Validation
+
+```typescript
+const FileUploadSchema = z.object({
+ file: z.instanceof(File),
+ category: z.enum(['image', 'document'])
+})
+
+export const uploadFile = createServerFn()
+ .validator(FileUploadSchema)
+ .handler(async ({ data }) => {
+ const { file, category } = data
+
+ // Validate file type
+ if (category === 'image' && !file.type.startsWith('image/')) {
+ throw new Error('Invalid file type for image category')
+ }
+
+ const url = await storage.upload(file)
+ return { url, category }
+ })
+```
+
+## Production Checklist
+
+### Validation
+- [ ] **Input Validation**: All server functions use validation schemas
+- [ ] **Schema Composition**: Reuse common schemas across functions
+- [ ] **Error Messages**: Validation errors provide clear feedback
+
+### Type Safety
+- [ ] **Schema Inference**: Let TypeScript infer types from validation schemas
+- [ ] **Runtime Safety**: Validation catches invalid data at runtime
+- [ ] **Client Types**: Server function calls are fully typed on the client
+
+## Common Problems
+
+### Problem: Validation schema and usage out of sync
+
+**Solution**: Use `z.infer` to derive types from schemas
+```typescript
+const UserSchema = z.object({
+ id: z.string(),
+ name: z.string()
+})
+
+type User = z.infer
+
+// Use the same schema for validation and typing
+export const createUser = createServerFn()
+ .validator(UserSchema)
+ .handler(async ({ data }): Promise => {
+ return data // data already matches User type
+ })
+```
+
+### Problem: Complex nested validation
+
+**Solution**: Break down complex schemas
+```typescript
+// ❌ Hard to manage
+const ComplexSchema = z.object({
+ user: z.object({
+ profile: z.object({
+ contact: z.object({
+ email: z.string().email()
+ })
+ })
+ })
+})
+
+// ✅ Composed schemas
+const ContactSchema = z.object({
+ email: z.string().email()
+})
+
+const ProfileSchema = z.object({
+ contact: ContactSchema
+})
+
+const UserSchema = z.object({
+ profile: ProfileSchema
+})
+```
+
+## Related Resources
+
+- [Create Basic Server Functions](./create-basic-server-functions.md) - Foundation concepts
+- [Use Server Functions with Forms](./use-server-functions-with-forms.md) - Form validation patterns
+- [Zod Documentation](https://zod.dev/)
+- [Valibot Documentation](https://valibot.dev/)
\ No newline at end of file
diff --git a/how-to-guides-implementation-plan.md b/how-to-guides-implementation-plan.md
index 3ebb7a7ea8..f77dd64780 100644
--- a/how-to-guides-implementation-plan.md
+++ b/how-to-guides-implementation-plan.md
@@ -14,6 +14,9 @@ This document outlines the multi-PR process for implementing the remaining how-t
- ✅ **Guide #8: Setup Testing** - COMPLETED
- ✅ **Environment Variables: TanStack Router** - COMPLETED in docs/router/framework/react/how-to/use-environment-variables.md
- ✅ **Environment Variables: TanStack Start** - COMPLETED in docs/start/framework/react/how-to/use-environment-variables.md
+- ✅ **Create Basic Server Functions: TanStack Start** - COMPLETED in docs/start/framework/react/how-to/create-basic-server-functions.md
+- ✅ **Write Type-Safe Server Functions: TanStack Start** - COMPLETED in docs/start/framework/react/how-to/write-type-safe-server-functions.md
+- ✅ **Use Server Functions with Forms: TanStack Start** - COMPLETED in docs/start/framework/react/how-to/use-server-functions-with-forms.md
- 🔄 **Progressive Search Params Series** - IN PROGRESS
### 🔄 Progressive Search Params How-To Series (Replaces Guide #10)