Server Functions
Server functions are the primary way to execute server-side code from your client components in TanStack Start. They provide type-safe, RPC-like functionality with automatic serialization and validation.What are Server Functions?
Server functions are functions that:- Run only on the server - Never bundled into client code
- Type-safe - Full TypeScript support from client to server
- Automatically serialized - Handle complex data types seamlessly
- HTTP-based - Use standard HTTP methods (GET, POST)
- Middleware-enabled - Support authentication, validation, and more
Creating Server Functions
UsecreateServerFn to define a server function:
packages/start-client-core/src/createServerFn.ts:53-196
HTTP Methods
Server functions support GET and POST methods:GET Requests
Ideal for data fetching without side effects:- Serialize data in the URL query string
- Can be cached by browsers and CDNs
- Have size limitations (~1MB)
packages/start-server-core/src/server-functions-handler.ts:131-146
POST Requests
Use for mutations and large payloads:- Send data in the request body
- Support larger payloads
- Can handle FormData for file uploads
packages/start-server-core/src/server-functions-handler.ts:38-65
Input Validation
Validate inputs before they reach your handler:With Zod
With Custom Validators
packages/start-client-core/src/createServerFn.ts:749-773
Middleware
Add middleware to server functions for cross-cutting concerns:packages/start-client-core/src/createServerFn.ts:68-90
Context Sharing
Share data between middleware and handlers:packages/start-client-core/src/createServerFn.ts:256-286
Error Handling
Handle errors gracefully:packages/start-server-core/src/server-functions-handler.ts:316-360
FormData Support
Handle file uploads and form submissions:packages/start-server-core/src/server-functions-handler.ts:85-128
Streaming Responses
Return streaming data from server functions:examples/react/start-streaming-data-from-server-functions/src/routes/index.tsx:58-89
Calling Server Functions
From Loaders
From Components
From Effects
Server-to-Server Calls
When calling a server function from another server function, use SSR RPC:packages/start-server-core/src/createSsrRpc.ts:8-26
Advanced Patterns
Composable Middleware
Custom Fetch Options
Response Customization
packages/start-server-core/src/request-response.ts
Security Best Practices
1. Validate All Inputs
2. Check Authentication
3. Never Expose Secrets
4. Rate Limiting
Performance Tips
1. Use GET for Cacheable Data
2. Batch Requests
3. Avoid Unnecessary Serialization
Next Steps
- Explore Full-Stack Architecture to understand the complete picture
- Learn about SSR to render on the server
- Discover Streaming for progressive data loading
- Review Deployment for production considerations