Skip to main content

Server Functions

Server functions are the primary way to execute server-side code from your client components in TanStack Start. They provide type-safe, RPC-like functionality with automatic serialization and validation.

What are Server Functions?

Server functions are functions that:
  • Run only on the server - Never bundled into client code
  • Type-safe - Full TypeScript support from client to server
  • Automatically serialized - Handle complex data types seamlessly
  • HTTP-based - Use standard HTTP methods (GET, POST)
  • Middleware-enabled - Support authentication, validation, and more

Creating Server Functions

Use createServerFn to define a server function:
Reference: packages/start-client-core/src/createServerFn.ts:53-196

HTTP Methods

Server functions support GET and POST methods:

GET Requests

Ideal for data fetching without side effects:
GET requests:
  • Serialize data in the URL query string
  • Can be cached by browsers and CDNs
  • Have size limitations (~1MB)
Reference: packages/start-server-core/src/server-functions-handler.ts:131-146

POST Requests

Use for mutations and large payloads:
POST requests:
  • Send data in the request body
  • Support larger payloads
  • Can handle FormData for file uploads
Reference: packages/start-server-core/src/server-functions-handler.ts:38-65

Input Validation

Validate inputs before they reach your handler:

With Zod

With Custom Validators

Reference: packages/start-client-core/src/createServerFn.ts:749-773

Middleware

Add middleware to server functions for cross-cutting concerns:
Reference: packages/start-client-core/src/createServerFn.ts:68-90

Context Sharing

Share data between middleware and handlers:
Reference: packages/start-client-core/src/createServerFn.ts:256-286

Error Handling

Handle errors gracefully:
Reference: packages/start-server-core/src/server-functions-handler.ts:316-360

FormData Support

Handle file uploads and form submissions:
Reference: packages/start-server-core/src/server-functions-handler.ts:85-128

Streaming Responses

Return streaming data from server functions:
Reference: examples/react/start-streaming-data-from-server-functions/src/routes/index.tsx:58-89

Calling Server Functions

From Loaders

From Components

From Effects

Server-to-Server Calls

When calling a server function from another server function, use SSR RPC:
Reference: packages/start-server-core/src/createSsrRpc.ts:8-26

Advanced Patterns

Composable Middleware

Custom Fetch Options

Response Customization

Reference: packages/start-server-core/src/request-response.ts

Security Best Practices

1. Validate All Inputs

2. Check Authentication

3. Never Expose Secrets

4. Rate Limiting

Performance Tips

1. Use GET for Cacheable Data

2. Batch Requests

3. Avoid Unnecessary Serialization

Next Steps