From e004786eddc25ec706d26f58b3fd5eb2f21c4edf Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Tue, 29 Jul 2025 17:59:04 +0000 Subject: [PATCH 1/9] Add server functions guide for TanStack Start Co-authored-by: tannerlinsley --- docs/start/framework/react/how-to/README.md | 3 +- .../how-to/create-basic-server-functions.md | 574 ++++++++++++++++++ .../write-isomorphic-client-server-code.md | 19 +- how-to-guides-implementation-plan.md | 1 + 4 files changed, 589 insertions(+), 8 deletions(-) create mode 100644 docs/start/framework/react/how-to/create-basic-server-functions.md diff --git a/docs/start/framework/react/how-to/README.md b/docs/start/framework/react/how-to/README.md index ad2b1a069e..ce20ed97ae 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) @@ -456,6 +456,7 @@ 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 - ✅ [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..350ca99706 --- /dev/null +++ b/docs/start/framework/react/how-to/create-basic-server-functions.md @@ -0,0 +1,574 @@ +# How to Create Basic Server Functions + +Learn how to create, validate, and use server functions in TanStack Start applications. Server functions allow you to run backend logic while maintaining full type safety between client and server. + +## 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. Handle Different HTTP Methods + +Server functions support different HTTP methods: + +```typescript +// app/functions/api.ts +import { createServerFn } from '@tanstack/start' +import { z } from 'zod' + +// GET request (default) +export const getUsers = createServerFn({ method: 'GET' }) + .handler(async () => { + return { users: [] } + }) + +// POST request +export const createUser = createServerFn({ method: 'POST' }) + .validator(z.object({ name: z.string() })) + .handler(async ({ data }) => { + return { id: 1, name: data.name } + }) + +// PUT request +export const updateUser = createServerFn({ method: 'PUT' }) + .validator(z.object({ + id: z.number(), + name: z.string() + })) + .handler(async ({ data }) => { + return { id: data.id, name: data.name, updated: true } + }) + +// DELETE request +export const deleteUser = createServerFn({ method: 'DELETE' }) + .validator(z.object({ id: z.number() })) + .handler(async ({ data }) => { + return { success: true, deletedId: data.id } + }) +``` + +### 4. Implement Proper Error Handling + +Handle errors gracefully in your server functions: + +```typescript +// app/functions/database.ts +import { createServerFn } from '@tanstack/start' +import { z } from 'zod' + +export class DatabaseError extends Error { + constructor(message: string, public code: string) { + super(message) + this.name = 'DatabaseError' + } +} + +export const getUserById = createServerFn() + .validator(z.object({ id: z.string() })) + .handler(async ({ data }) => { + try { + // Simulate database lookup + if (data.id === 'not-found') { + throw new DatabaseError('User not found', 'USER_NOT_FOUND') + } + + if (data.id === 'server-error') { + throw new DatabaseError('Database connection failed', 'DB_CONNECTION_ERROR') + } + + return { + id: data.id, + name: 'John Doe', + email: 'john@example.com', + } + } catch (error) { + if (error instanceof DatabaseError) { + // Re-throw custom errors with additional context + throw new Error(`Database error: ${error.message} (${error.code})`) + } + + // Handle unexpected errors + console.error('Unexpected error in getUserById:', error) + throw new Error('Internal server error') + } + }) +``` + +### 5. Call Server Functions from Client Components + +#### Basic Usage + +```tsx +// app/routes/users.tsx +import { createFileRoute } from '@tanstack/react-router' +import { useState } from 'react' +import { createUser, getUserById } from '../functions/database' + +export const Route = createFileRoute('/users')({ + component: UsersPage, +}) + +function UsersPage() { + const [user, setUser] = useState(null) + const [loading, setLoading] = useState(false) + const [error, setError] = useState('') + + const handleCreateUser = async () => { + setLoading(true) + setError('') + + try { + const newUser = await createUser({ + data: { + email: 'user@example.com', + name: 'New User', + age: 25, + } + }) + setUser(newUser) + } catch (err) { + setError(err.message) + } finally { + setLoading(false) + } + } + + return ( +
+ + + {error &&
Error: {error}
} + {user &&
{JSON.stringify(user, null, 2)}
} +
+ ) +} +``` + +#### With Form Handling + +```tsx +// app/routes/users/new.tsx +import { createFileRoute } from '@tanstack/react-router' +import { useState } from 'react' +import { createUser } from '../../functions/user' + +export const Route = createFileRoute('/users/new')({ + component: NewUserForm, +}) + +function NewUserForm() { + const [formData, setFormData] = useState({ + email: '', + name: '', + age: '', + }) + const [submitting, setSubmitting] = useState(false) + const [result, setResult] = useState(null) + + const handleSubmit = async (e) => { + e.preventDefault() + setSubmitting(true) + + try { + const user = await createUser({ + data: { + email: formData.email, + name: formData.name, + age: formData.age ? parseInt(formData.age) : undefined, + } + }) + setResult(user) + setFormData({ email: '', name: '', age: '' }) + } catch (error) { + alert(`Error: ${error.message}`) + } finally { + setSubmitting(false) + } + } + + return ( +
+
+ +
+ +
+ +
+ +
+ +
+ + + + {result && ( +
+

User Created:

+
{JSON.stringify(result, null, 2)}
+
+ )} +
+ ) +} +``` + +### 6. File Organization Best Practices + +Organize your server functions in a logical structure: + +``` +app/ +├── functions/ # Server functions directory +│ ├── auth.ts # Authentication functions +│ ├── users.ts # User management functions +│ ├── posts.ts # Content functions +│ └── utils.ts # Shared utilities +├── routes/ # Route components +└── utils/ # Client-side utilities +``` + +Example organized structure: + +```typescript +// app/functions/auth.ts +export const login = createServerFn()... +export const logout = createServerFn()... +export const register = createServerFn()... + +// app/functions/users.ts +export const getUsers = createServerFn()... +export const createUser = createServerFn()... +export const updateUser = createServerFn()... +export const deleteUser = createServerFn()... + +// app/functions/posts.ts +export const getPosts = createServerFn()... +export const createPost = 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 + }) +``` + + + +## 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/write-isomorphic-client-server-code.md b/docs/start/framework/react/how-to/write-isomorphic-client-server-code.md index 452760464f..cb420bbca9 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 @@ -239,14 +239,19 @@ function CurrentTime() { --- +## 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/how-to-guides-implementation-plan.md b/how-to-guides-implementation-plan.md index 3ebb7a7ea8..fc4b844921 100644 --- a/how-to-guides-implementation-plan.md +++ b/how-to-guides-implementation-plan.md @@ -14,6 +14,7 @@ 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 - 🔄 **Progressive Search Params Series** - IN PROGRESS ### 🔄 Progressive Search Params How-To Series (Replaces Guide #10) From e145b25b2bd945fc95f217c6697d81c5416e6ee5 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Tue, 29 Jul 2025 18:09:11 +0000 Subject: [PATCH 2/9] Add guide for writing type-safe server functions in TanStack Start Co-authored-by: tannerlinsley --- docs/start/framework/react/how-to/README.md | 3 +- .../how-to/create-basic-server-functions.md | 9 +- .../write-type-safe-server-functions.md | 663 ++++++++++++++++++ how-to-guides-implementation-plan.md | 1 + 4 files changed, 672 insertions(+), 4 deletions(-) create mode 100644 docs/start/framework/react/how-to/write-type-safe-server-functions.md diff --git a/docs/start/framework/react/how-to/README.md b/docs/start/framework/react/how-to/README.md index ce20ed97ae..4421260545 100644 --- a/docs/start/framework/react/how-to/README.md +++ b/docs/start/framework/react/how-to/README.md @@ -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 👍) @@ -457,6 +457,7 @@ Core server function concepts before advanced patterns. - ✅ [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 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 index 350ca99706..04bb718342 100644 --- a/docs/start/framework/react/how-to/create-basic-server-functions.md +++ b/docs/start/framework/react/how-to/create-basic-server-functions.md @@ -555,15 +555,18 @@ export const processDataBatch = createServerFn() }) ``` - +- [Handle redirects in server functions](./handle-redirects-server-functions.md) +--> ## Related Resources 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..d4e442b607 --- /dev/null +++ b/docs/start/framework/react/how-to/write-type-safe-server-functions.md @@ -0,0 +1,663 @@ +# How to Write Type-Safe Server Functions + +Optimize TypeScript performance and avoid common type errors when building server functions in TanStack Start. This guide focuses on advanced TypeScript patterns and performance optimizations. + +## Quick Start + +```typescript +// ❌ Problematic - causes "Type instantiation is excessively deep" +export const processComplexData = createServerFn() + .validator(z.object({ + data: z.array(z.object({ + nested: z.object({ + deep: z.object({ + value: z.string() + }) + }) + })) + })) + .handler(async ({ data }) => { + return data.map(item => ({ + ...item, + processed: true + })) + }) + +// ✅ Optimized - flattened types and explicit interfaces +interface ProcessedItem { + id: string + value: string + processed: boolean +} + +const ItemSchema = z.object({ + id: z.string(), + value: z.string() +}) + +export const processComplexData = createServerFn() + .validator(z.object({ + items: z.array(ItemSchema).max(100) + })) + .handler(async ({ data }): Promise => { + return data.items.map(item => ({ + id: item.id, + value: item.value, + processed: true + })) + }) +``` + +## TypeScript Performance Patterns + +### 1. Flatten Nested Type Structures + +Deeply nested types cause TypeScript performance issues: + +```typescript +// ❌ Avoid deep nesting +const DeepSchema = z.object({ + level1: z.object({ + level2: z.object({ + level3: z.object({ + level4: z.object({ + data: z.string() + }) + }) + }) + }) +}) + +// ✅ Use flat interfaces instead +interface UserPreferences { + theme: 'light' | 'dark' + language: string + notifications: boolean +} + +interface UserProfile { + id: string + email: string + preferences: UserPreferences +} + +const UserPreferencesSchema = z.object({ + theme: z.enum(['light', 'dark']), + language: z.string(), + notifications: z.boolean() +}) + +const UserProfileSchema = z.object({ + id: z.string(), + email: z.string().email(), + preferences: UserPreferencesSchema +}) + +export const updateUserProfile = createServerFn() + .validator(UserProfileSchema) + .handler(async ({ data }): Promise => { + return data + }) +``` + +### 2. Use Explicit Return Types + +Always specify return types to avoid inference overhead: + +```typescript +// ❌ TypeScript infers complex return type +export const getComplexData = createServerFn() + .handler(async ({ data }) => { + return { + users: await fetchUsers(), + posts: await fetchPosts(), + comments: await fetchComments() + } + }) + +// ✅ Explicit return type +interface DashboardData { + users: User[] + posts: Post[] + comments: Comment[] +} + +export const getDashboardData = createServerFn() + .handler(async (): Promise => { + return { + users: await fetchUsers(), + posts: await fetchPosts(), + comments: await fetchComments() + } + }) +``` + +### 3. Optimize Array and Object Schemas + +Limit array sizes and use discriminated unions: + +```typescript +// ❌ Unbounded arrays cause performance issues +const ProblematicSchema = z.object({ + items: z.array(z.object({ + data: z.any() // Also avoid 'any' + })) +}) + +// ✅ Bounded arrays with specific types +type ItemType = 'text' | 'image' | 'video' + +interface BaseItem { + id: string + type: ItemType + createdAt: string +} + +interface TextItem extends BaseItem { + type: 'text' + content: string +} + +interface ImageItem extends BaseItem { + type: 'image' + url: string + alt: string +} + +const TextItemSchema = z.object({ + id: z.string(), + type: z.literal('text'), + content: z.string(), + createdAt: z.string() +}) + +const ImageItemSchema = z.object({ + id: z.string(), + type: z.literal('image'), + url: z.string().url(), + alt: z.string(), + createdAt: z.string() +}) + +const ItemSchema = z.discriminatedUnion('type', [ + TextItemSchema, + ImageItemSchema +]) + +export const processItems = createServerFn() + .validator(z.object({ + items: z.array(ItemSchema).max(50) + })) + .handler(async ({ data }): Promise => { + return data.items + }) +``` + +## Advanced Type Safety Patterns + +### 1. Input/Output Type Separation + +Separate input validation from internal processing types: + +```typescript +// Input validation schema +const CreatePostInputSchema = z.object({ + title: z.string().min(1).max(200), + content: z.string().min(1), + tags: z.array(z.string()).max(10).optional(), + publishAt: z.string().datetime().optional() +}) + +type CreatePostInput = z.infer + +// Internal domain types +interface Post { + id: string + title: string + content: string + tags: string[] + publishAt: Date | null + createdAt: Date + updatedAt: Date + authorId: string +} + +// Output type (what gets sent to client) +interface PostResponse { + id: string + title: string + content: string + tags: string[] + publishAt: string | null + createdAt: string +} + +export const createPost = createServerFn() + .validator(CreatePostInputSchema) + .handler(async ({ data }): Promise => { + const post: Post = { + id: generateId(), + title: data.title, + content: data.content, + tags: data.tags || [], + publishAt: data.publishAt ? new Date(data.publishAt) : null, + createdAt: new Date(), + updatedAt: new Date(), + authorId: getCurrentUserId() + } + + await savePost(post) + + return { + id: post.id, + title: post.title, + content: post.content, + tags: post.tags, + publishAt: post.publishAt?.toISOString() || null, + createdAt: post.createdAt.toISOString() + } + }) +``` + +### 2. Generic Type Utilities + +Create reusable type utilities for common patterns: + +```typescript +// Utility types for consistent API responses +type ApiResponse = { + data: T + success: true +} | { + error: string + success: false +} + +type PaginatedResponse = ApiResponse<{ + items: T[] + pagination: { + page: number + limit: number + total: number + hasNext: boolean + } +}> + +// Generic pagination schema +const createPaginationSchema = (itemSchema: T) => { + return z.object({ + page: z.number().min(1).default(1), + limit: z.number().min(1).max(100).default(20), + filters: itemSchema.partial().optional() + }) +} + +// Usage +const UserFiltersSchema = z.object({ + email: z.string().email(), + role: z.enum(['admin', 'user']), + active: z.boolean() +}) + +export const getUsers = createServerFn() + .validator(createPaginationSchema(UserFiltersSchema)) + .handler(async ({ data }): Promise> => { + try { + const result = await fetchPaginatedUsers(data) + return { + success: true, + data: { + items: result.users, + pagination: result.pagination + } + } + } catch (error) { + return { + success: false, + error: 'Failed to fetch users' + } + } + }) +``` + +### 3. Type-Safe Error Handling + +Create typed error hierarchies: + +```typescript +// Base error classes with proper typing +abstract class AppError extends Error { + abstract readonly code: string + abstract readonly statusCode: number +} + +class ValidationError extends AppError { + readonly code = 'VALIDATION_ERROR' + readonly statusCode = 400 + + constructor( + message: string, + public readonly field: string + ) { + super(message) + this.name = 'ValidationError' + } +} + +class NotFoundError extends AppError { + readonly code = 'NOT_FOUND' + readonly statusCode = 404 + + constructor(resource: string, id: string) { + super(`${resource} with id ${id} not found`) + this.name = 'NotFoundError' + } +} + +// Type-safe error response +type ErrorResponse = { + code: string + message: string + field?: string +} + +export const getUserById = createServerFn() + .validator(z.object({ id: z.string().uuid() })) + .handler(async ({ data }): Promise> => { + try { + const user = await findUserById(data.id) + if (!user) { + throw new NotFoundError('User', data.id) + } + + return { + success: true, + data: user + } + } catch (error) { + if (error instanceof AppError) { + return { + success: false, + error: error.message + } + } + + // Log unexpected errors but don't expose details + console.error('Unexpected error:', error) + return { + success: false, + error: 'Internal server error' + } + } + }) +``` + +## Performance Optimization Strategies + +### 1. Schema Caching + +Cache validation schemas to improve performance: + +```typescript +// Schema cache to avoid recreation +const schemaCache = new Map() + +function createCachedSchema( + key: string, + schemaFactory: () => T +): T { + if (!schemaCache.has(key)) { + schemaCache.set(key, schemaFactory()) + } + return schemaCache.get(key) as T +} + +// Usage +const getUsersSchema = createCachedSchema('getUsers', () => + z.object({ + page: z.number().min(1), + limit: z.number().min(1).max(100) + }) +) + +export const getUsers = createServerFn() + .validator(getUsersSchema) + .handler(async ({ data }) => { + // Handler implementation + }) +``` + +### 2. Lazy Type Loading + +Use dynamic imports for complex type definitions: + +```typescript +// types/user.ts - Separate file for complex types +export interface UserWithRelations { + id: string + email: string + profile: UserProfile + posts: Post[] + comments: Comment[] + permissions: Permission[] +} + +// server function with lazy loading +export const getUserWithRelations = createServerFn() + .validator(z.object({ id: z.string() })) + .handler(async ({ data }): Promise => { + // Dynamic import delays type loading until needed + const { UserWithRelations } = await import('../types/user') + + const user = await fetchUserWithRelations(data.id) + return user + }) +``` + +### 3. Selective Type Inference + +Control TypeScript inference to improve performance: + +```typescript +// Use const assertions to limit inference +const USER_ROLES = ['admin', 'user', 'moderator'] as const +type UserRole = typeof USER_ROLES[number] + +// Instead of letting TypeScript infer everything +const createUserSchema = z.object({ + email: z.string().email(), + role: z.enum(USER_ROLES), // Explicit enum from const + preferences: z.object({ + theme: z.literal('light').or(z.literal('dark')), + language: z.string().length(2) + }) +}) satisfies z.ZodType<{ + email: string + role: UserRole + preferences: { + theme: 'light' | 'dark' + language: string + } +}> +``` + +## Testing Type Safety + +### 1. Type-Only Tests + +Test your types without runtime overhead: + +```typescript +// types.test.ts +import { expectType } from 'tsd' +import { createUser } from '../functions/users' + +// Test input types +expectType<{ + email: string + name: string + age?: number +}>(await createUser({ + data: { + email: 'test@example.com', + name: 'Test User' + } +})) + +// Test that invalid inputs are rejected +// @ts-expect-error - Should fail with invalid email +createUser({ + data: { + email: 'invalid-email', + name: 'Test' + } +}) +``` + +### 2. Runtime Type Validation Tests + +```typescript +// functions.test.ts +import { describe, it, expect } from 'vitest' +import { createUser } from '../functions/users' + +describe('Type-safe server functions', () => { + it('validates input correctly', async () => { + await expect( + createUser({ + data: { + email: 'invalid-email', + name: 'Test' + } + }) + ).rejects.toThrow('Invalid email') + }) + + it('returns correctly typed output', async () => { + const result = await createUser({ + data: { + email: 'test@example.com', + name: 'Test User' + } + }) + + expect(result).toHaveProperty('id') + expect(result).toHaveProperty('email', 'test@example.com') + expect(result).toHaveProperty('createdAt') + }) +}) +``` + +## Production Checklist + +### TypeScript Configuration + +- [ ] **Strict Mode**: `"strict": true` in tsconfig.json +- [ ] **No Unchecked Indexed Access**: `"noUncheckedIndexedAccess": true` +- [ ] **Exact Optional Property Types**: `"exactOptionalPropertyTypes": true` +- [ ] **Skip Lib Check**: `"skipLibCheck": true` for performance + +### Schema Optimization + +- [ ] **Array Limits**: All array schemas have `.max()` constraints +- [ ] **String Limits**: String schemas have reasonable length limits +- [ ] **Union Types**: Use discriminated unions instead of large unions +- [ ] **Schema Caching**: Frequently used schemas are cached + +### Error Handling + +- [ ] **Typed Errors**: Custom error classes with proper typing +- [ ] **Error Boundaries**: Client components handle typed errors +- [ ] **Validation Errors**: Clear, actionable validation messages +- [ ] **Production Errors**: Sensitive details not exposed in production + +## Common Problems + +### Problem: "Type instantiation is excessively deep and possibly infinite" + +**Cause**: Deeply nested or recursive type structures. + +**Solution**: +```typescript +// ❌ Problematic +type DeepNested = { + level1: { + level2: { + level3: { + data: string + } + } + } +} + +// ✅ Flattened +interface Config { + theme: string + language: string +} + +interface UserSettings { + config: Config + userId: string +} +``` + +### Problem: Slow TypeScript compilation with server functions + +**Cause**: Complex type inference or large union types. + +**Solution**: +```typescript +// ❌ Slow inference +const complexHandler = createServerFn() + .handler(async ({ data }) => { + // TypeScript struggles to infer this + return data.items.map(item => ({ + ...item, + ...processItem(item), + ...addMetadata(item) + })) + }) + +// ✅ Explicit types +interface ProcessedItem { + id: string + processed: boolean + metadata: ItemMetadata +} + +const optimizedHandler = createServerFn() + .handler(async ({ data }): Promise => { + return data.items.map(item => processItemToType(item)) + }) +``` + +### Problem: Validation schema and TypeScript types out of sync + +**Cause**: Manually maintaining both schema and types. + +**Solution**: +```typescript +// ✅ Single source of truth +const UserSchema = z.object({ + id: z.string(), + email: z.string().email(), + name: z.string() +}) + +type User = z.infer + +// Use the inferred type everywhere +export const createUser = createServerFn() + .validator(UserSchema) + .handler(async ({ data }): Promise => { + return data + }) +``` + +## Related Resources + +- [Create Basic Server Functions](./create-basic-server-functions.md) - Foundation concepts +- [Zod Performance Tips](https://zod.dev/?id=performance) +- [TypeScript Performance Guidelines](https://github.com/microsoft/TypeScript/wiki/Performance) +- [GitHub Issue #4533: Server Function TypeScript Issues](https://github.com/TanStack/router/issues/4533) \ No newline at end of file diff --git a/how-to-guides-implementation-plan.md b/how-to-guides-implementation-plan.md index fc4b844921..861cbb05e8 100644 --- a/how-to-guides-implementation-plan.md +++ b/how-to-guides-implementation-plan.md @@ -15,6 +15,7 @@ This document outlines the multi-PR process for implementing the remaining how-t - ✅ **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 - 🔄 **Progressive Search Params Series** - IN PROGRESS ### 🔄 Progressive Search Params How-To Series (Replaces Guide #10) From 2f45f4d6411f0b559ad7935e099817064b8d72b8 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 30 Jul 2025 17:10:35 +0000 Subject: [PATCH 3/9] Checkpoint before follow-up message --- .../how-to/create-basic-server-functions.md | 31 ++++++++++--------- 1 file changed, 16 insertions(+), 15 deletions(-) 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 index 04bb718342..c3250c54c3 100644 --- a/docs/start/framework/react/how-to/create-basic-server-functions.md +++ b/docs/start/framework/react/how-to/create-basic-server-functions.md @@ -126,28 +126,22 @@ export const createUser = createServerFn() ### 3. Handle Different HTTP Methods -Server functions support different HTTP methods: +Server functions support GET and POST methods (POST is the default): ```typescript // app/functions/api.ts import { createServerFn } from '@tanstack/start' import { z } from 'zod' -// GET request (default) -export const getUsers = createServerFn({ method: 'GET' }) - .handler(async () => { - return { users: [] } - }) - -// POST request -export const createUser = createServerFn({ method: 'POST' }) +// POST request (default - no need to specify) +export const createUser = createServerFn() .validator(z.object({ name: z.string() })) .handler(async ({ data }) => { return { id: 1, name: data.name } }) -// PUT request -export const updateUser = createServerFn({ method: 'PUT' }) +// POST request (explicit) +export const updateUser = createServerFn({ method: 'POST' }) .validator(z.object({ id: z.number(), name: z.string() @@ -156,11 +150,18 @@ export const updateUser = createServerFn({ method: 'PUT' }) return { id: data.id, name: data.name, updated: true } }) -// DELETE request -export const deleteUser = createServerFn({ method: 'DELETE' }) - .validator(z.object({ id: z.number() })) +// GET request +export const getUsers = createServerFn({ method: 'GET' }) + .handler(async () => { + return { users: [] } + }) + +// GET request with query parameters +export const getUserById = createServerFn({ method: 'GET' }) + .validator(z.object({ id: z.string() })) .handler(async ({ data }) => { - return { success: true, deletedId: data.id } + // data comes from query parameters for GET requests + return { id: data.id, name: 'John Doe' } }) ``` From 1fb3bdd9cdf62b1653adb4249138c5b6f851c9a7 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 30 Jul 2025 17:11:11 +0000 Subject: [PATCH 4/9] Remove error handling section and update import in users route Co-authored-by: tannerlinsley --- .../how-to/create-basic-server-functions.md | 51 ++----------------- 1 file changed, 3 insertions(+), 48 deletions(-) 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 index c3250c54c3..1cc2fcbf51 100644 --- a/docs/start/framework/react/how-to/create-basic-server-functions.md +++ b/docs/start/framework/react/how-to/create-basic-server-functions.md @@ -165,54 +165,9 @@ export const getUserById = createServerFn({ method: 'GET' }) }) ``` -### 4. Implement Proper Error Handling -Handle errors gracefully in your server functions: -```typescript -// app/functions/database.ts -import { createServerFn } from '@tanstack/start' -import { z } from 'zod' - -export class DatabaseError extends Error { - constructor(message: string, public code: string) { - super(message) - this.name = 'DatabaseError' - } -} - -export const getUserById = createServerFn() - .validator(z.object({ id: z.string() })) - .handler(async ({ data }) => { - try { - // Simulate database lookup - if (data.id === 'not-found') { - throw new DatabaseError('User not found', 'USER_NOT_FOUND') - } - - if (data.id === 'server-error') { - throw new DatabaseError('Database connection failed', 'DB_CONNECTION_ERROR') - } - - return { - id: data.id, - name: 'John Doe', - email: 'john@example.com', - } - } catch (error) { - if (error instanceof DatabaseError) { - // Re-throw custom errors with additional context - throw new Error(`Database error: ${error.message} (${error.code})`) - } - - // Handle unexpected errors - console.error('Unexpected error in getUserById:', error) - throw new Error('Internal server error') - } - }) -``` - -### 5. Call Server Functions from Client Components +### 4. Call Server Functions from Client Components #### Basic Usage @@ -220,7 +175,7 @@ export const getUserById = createServerFn() // app/routes/users.tsx import { createFileRoute } from '@tanstack/react-router' import { useState } from 'react' -import { createUser, getUserById } from '../functions/database' +import { createUser } from '../functions/user' export const Route = createFileRoute('/users')({ component: UsersPage, @@ -359,7 +314,7 @@ function NewUserForm() { } ``` -### 6. File Organization Best Practices +### 5. File Organization Best Practices Organize your server functions in a logical structure: From 54c733da0ae487af1c3d7188cd29d4497dda8560 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 30 Jul 2025 17:14:40 +0000 Subject: [PATCH 5/9] Add guide for using server functions with forms in TanStack Start Co-authored-by: tannerlinsley --- docs/start/framework/react/how-to/README.md | 1 + .../how-to/create-basic-server-functions.md | 94 +-- .../how-to/use-server-functions-with-forms.md | 700 ++++++++++++++++++ how-to-guides-implementation-plan.md | 1 + 4 files changed, 703 insertions(+), 93 deletions(-) create mode 100644 docs/start/framework/react/how-to/use-server-functions-with-forms.md diff --git a/docs/start/framework/react/how-to/README.md b/docs/start/framework/react/how-to/README.md index 4421260545..3807e38bd7 100644 --- a/docs/start/framework/react/how-to/README.md +++ b/docs/start/framework/react/how-to/README.md @@ -458,6 +458,7 @@ Core server function concepts before advanced patterns. - ✅ [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 index 1cc2fcbf51..06baf18a5b 100644 --- a/docs/start/framework/react/how-to/create-basic-server-functions.md +++ b/docs/start/framework/react/how-to/create-basic-server-functions.md @@ -219,100 +219,7 @@ function UsersPage() { } ``` -#### With Form Handling -```tsx -// app/routes/users/new.tsx -import { createFileRoute } from '@tanstack/react-router' -import { useState } from 'react' -import { createUser } from '../../functions/user' - -export const Route = createFileRoute('/users/new')({ - component: NewUserForm, -}) - -function NewUserForm() { - const [formData, setFormData] = useState({ - email: '', - name: '', - age: '', - }) - const [submitting, setSubmitting] = useState(false) - const [result, setResult] = useState(null) - - const handleSubmit = async (e) => { - e.preventDefault() - setSubmitting(true) - - try { - const user = await createUser({ - data: { - email: formData.email, - name: formData.name, - age: formData.age ? parseInt(formData.age) : undefined, - } - }) - setResult(user) - setFormData({ email: '', name: '', age: '' }) - } catch (error) { - alert(`Error: ${error.message}`) - } finally { - setSubmitting(false) - } - } - - return ( -
-
- -
- -
- -
- -
- -
- - - - {result && ( -
-

User Created:

-
{JSON.stringify(result, null, 2)}
-
- )} -
- ) -} -``` ### 5. File Organization Best Practices @@ -516,6 +423,7 @@ export const processDataBatch = createServerFn() 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