Server Functions
Server functions are a core feature of TanStack Start that allow you to write server-side code that can be called directly from your client components. They provide type-safe, serializable communication between client and server.What are Server Functions?
Server functions enable you to:- Execute code exclusively on the server
- Access server-only resources (databases, file systems, APIs)
- Maintain type safety across client-server boundaries
- Avoid exposing sensitive logic or credentials to the client
Creating a Server Function
UsecreateServerFn() to define a server function:
HTTP Methods
Server functions support two HTTP methods:GET Requests
UseGET for read operations and data fetching:
POST Requests
UsePOST for mutations, form submissions, or when sending complex data:
Input Validation
Validate and transform input data using validators:Function Validators
Zod Validators
Calling Server Functions
From Client Components
In Route Loaders
With Custom Options
Server Function Context
Access server-only context in your handlers:Working with FormData
Server functions can handle FormData directly:Error Handling
Throwing Errors
Catching Errors
Advanced Patterns
Composing Server Functions
Streaming Responses
Server functions support streaming for large datasets:Deferred Data Loading
Defer slow data fetching to improve initial page load:Best Practices
-
Choose the Right HTTP Method
- Use
GETfor read operations that can be cached - Use
POSTfor mutations or operations with side effects
- Use
-
Validate All Inputs
- Always use input validators to ensure data integrity
- Prefer schema validation libraries like Zod for complex types
-
Keep Functions Focused
- Each server function should do one thing well
- Compose smaller functions for complex operations
-
Handle Errors Gracefully
- Throw appropriate errors for different scenarios
- Use router utilities like
notFound()andredirect()
-
Avoid Over-fetching
- Only return data that the client needs
- Use projection/selection in database queries
-
Consider Performance
- Use deferred loading for slow operations
- Implement caching strategies for frequently accessed data
-
Security First
- Never expose sensitive data or credentials
- Validate and sanitize all inputs
- Use authentication and authorization checks
Type Safety
Server functions maintain full type safety:Next Steps
- Learn about Data Fetching strategies
- Add Middleware to your server functions
- Explore API Routes for REST endpoints