Skip to main content

createServerFn

Creates a type-safe server function that can be called from the client with automatic serialization and middleware support.

Basic Usage

API Reference

'GET' | 'POST'
default:"'GET'"
The HTTP method to use for the server function. GET requests serialize data in the URL query string, while POST requests send data in the request body.

Builder Methods

The createServerFn() function returns a builder with chainable methods:

.middleware()

Adds middleware to the server function for request/response processing.
Array<Middleware>
required
Array of middleware functions or middleware instances to apply to this server function.

.inputValidator()

Validates and transforms input data using a validator (Zod, Valibot, ArkType, or custom function).
Validator
required
A validation schema or function that validates the input data. Supports Standard Schema validators like Zod, Valibot, and ArkType.

.handler()

Defines the server-side handler function that executes when the server function is called.
ServerFn
required
The server-side function to execute. Receives a context object with data, context, method, and serverFnMeta.

Handler Context

The handler function receives a context object with the following properties:
any
The validated input data. Type is inferred from the inputValidator if provided.
object
Context object accumulated from middleware. Contains values added by middleware and global context.
'GET' | 'POST'
The HTTP method used for this server function.
ServerFnMeta
Metadata about the server function including:
  • id: Unique function identifier
  • name: Function name
  • filename: Source file path

Calling Server Functions

Server functions can be called with optional configuration:

Call Options

any
The input data to send to the server. Required if inputValidator requires input.
HeadersInit
Custom headers to include in the request.
AbortSignal
AbortSignal for cancelling the request.
typeof fetch
Custom fetch implementation to use instead of global fetch.

Method Selection

GET Requests

  • Data is serialized in URL query parameters
  • Suitable for idempotent operations
  • Limited payload size
  • Cacheable by browsers and CDNs

POST Requests

  • Data sent in request body
  • Supports larger payloads
  • Supports FormData for file uploads
  • Not cached by default

Advanced Examples

Chaining Multiple Middleware

Returning Responses

Error Handling

Type Safety

Server functions are fully type-safe:
  • Input types are inferred from validators
  • Context types are inferred from middleware
  • Return types are preserved across the network
  • Serialization is automatically validated