Server Functions
Server functions are the core primitive for executing code on the server in TanStack Start. They provide a type-safe way to define server-side logic that can be called from your React components.Creating Server Functions
UsecreateServerFn to define a server function:
Basic Usage
GET Requests
For simple data fetching, use GET requests:POST Requests
For mutations and data that requires validation, use POST requests:Input Validation
Validate input data before it reaches your handler:Using Validation Adapters
TanStack Start provides adapters for popular validation libraries:Server Function Context
Access request metadata and shared context in your handlers:Calling Server Functions
From Loaders
The most common pattern is calling server functions from route loaders:From Components with useServerFn
For client-side calls (mutations, refetching), useuseServerFn:
Direct Calls
You can also call server functions directly:Middleware
Add middleware to server functions for cross-cutting concerns:Error Handling
Server functions propagate errors to the client:Redirects
Redirect users from server functions:Streaming Responses
Stream data back to the client usingRawStream:
Server-Only Imports
Mark modules as server-only to prevent them from being bundled for the client:Client-Only Imports
Mark modules as client-only:Type Safety
Server functions are fully type-safe:Best Practices
Co-locate with Features
Keep server functions close to where they’re used:Reuse Across Routes
Define server functions once and import them across multiple routes:Validate All Inputs
Always validate POST request data:Handle Errors Gracefully
Provide meaningful error messages:API Reference
createServerFn(options?)
Creates a new server function builder. Parameters:options.method:'GET' | 'POST'- HTTP method (default:'GET')
ServerFnBuilder
ServerFnBuilder Methods
.inputValidator(validator)
Adds input validation to the server function. Parameters:validator: Function or adapter that validates input data
ServerFnAfterValidator
.middleware(middlewares)
Adds middleware to the server function. Parameters:middlewares: Array of middleware functions
ServerFnAfterMiddleware
.handler(fn)
Defines the server function implementation. Parameters:fn:(ctx: ServerFnCtx) => Promise<T>- Handler function
Fetcher<T> - Callable server function
ServerFnCtx
Context object passed to handler functions:Related
- Client Functions - Client-side only functions
- Components - React Start components
- Middleware - Request and function middleware