Skip to main content

Server Functions

Server Functions are the primary way to execute server-side code in TanStack Start. They enable type-safe, secure communication between client and server with automatic serialization and built-in middleware support.

What are Server Functions?

Server Functions are functions that run exclusively on the server but can be called from anywhere in your application. They provide:
  • Type Safety: Full TypeScript inference from input to output
  • Automatic Serialization: Built-in handling of complex data types
  • Secure by Default: Server code never ships to the client
  • Middleware Support: Composable middleware for auth, validation, and more
  • HTTP Method Control: Choose GET or POST for each function

Creating Server Functions

1

Basic Server Function

Create a server function using createServerFn():
2

POST Server Function with Input

Use POST for mutations and when passing data:
3

Input Validation with Zod

Use schema validation for type-safe inputs:
4

Access Server Context

Access request information and server-only resources:

Server Function Middleware

Compose reusable logic with middleware:

Using useServerFn Hook

For better integration with router navigation:

Streaming Responses

Return ReadableStream for progressive data loading:

Advanced Patterns

FormData Support

Handle file uploads and form submissions:

Error Handling

Best Practices

  • Use GET for reads: GET requests are cached by default and support URL parameters
  • Use POST for mutations: POST requests are never cached and support larger payloads
  • Validate inputs: Always use input validators for type safety and security
  • Keep functions focused: Each server function should do one thing well
  • Use middleware for cross-cutting concerns: Auth, logging, rate limiting, etc.
  • Handle errors gracefully: Return meaningful error messages to the client
  • Type everything: Leverage TypeScript for end-to-end type safety

Learn More