Skip to main content

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

Use createServerFn() to define a server function:

HTTP Methods

Server functions support two HTTP methods:

GET Requests

Use GET for read operations and data fetching:

POST Requests

Use POST 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:
From the client:

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

  1. Choose the Right HTTP Method
    • Use GET for read operations that can be cached
    • Use POST for mutations or operations with side effects
  2. Validate All Inputs
    • Always use input validators to ensure data integrity
    • Prefer schema validation libraries like Zod for complex types
  3. Keep Functions Focused
    • Each server function should do one thing well
    • Compose smaller functions for complex operations
  4. Handle Errors Gracefully
    • Throw appropriate errors for different scenarios
    • Use router utilities like notFound() and redirect()
  5. Avoid Over-fetching
    • Only return data that the client needs
    • Use projection/selection in database queries
  6. Consider Performance
    • Use deferred loading for slow operations
    • Implement caching strategies for frequently accessed data
  7. 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