Open History to see the last commit
1---
2id: server-functions
3title: Server Functions
4---
5β
6## What are Server Functions?
7β
8Server functions let you define server-only logic that can be called from anywhere in your application - loaders, components, hooks, or other server functions. They run on the server but can be invoked from client code seamlessly.
9β
10```tsx
11import { createServerFn } from '@tanstack/react-start'
12β
13export const getServerTime = createServerFn().handler(async () => {
14 // This runs only on the server
15 return new Date().toISOString()
16})
17β
18// Call from anywhere - components, loaders, hooks, etc.
19const time = await getServerTime()
20```
21β
22Server functions provide server capabilities (database access, environment variables, file system) while maintaining type safety across the network boundary.
23β
24> [!NOTE]
25> Server functions are meant to be called by your TanStack Start application. They are easy to use from your app code, and Start handles serialization across the client/server boundary. If you need an endpoint that can be called from outside your Start app, use [server routes](./server-routes) instead.
26β
27## Same-Origin Requests
28β
29Server functions are same-origin RPC endpoints for your application. Browser requests to server functions should come from the same origin, verified with Fetch Metadata (`Sec-Fetch-Site`), `Origin`, or `Referer` headers. Use server routes for public APIs or endpoints that intentionally support cross-origin requests.
30β
31TanStack Start provides `createCsrfMiddleware()` to protect server functions from cross-site requests. If your app does not define `src/start.ts`, Start installs this middleware automatically for server functions. If you define `src/start.ts`, add the middleware explicitly:
32β
33```tsx
34// src/start.ts
35import { createStart, createCsrfMiddleware } from '@tanstack/react-start'
36β
37const csrfMiddleware = createCsrfMiddleware({
38 filter: (ctx) => ctx.handlerType === 'serverFn',
39})
40β
41export const startInstance = createStart(() => ({
42 requestMiddleware: [csrfMiddleware],
43}))
44```
45β
46By default, `Origin` and `Referer` checks compare against the incoming request URL origin. If your deployment needs to allow a different public origin, configure it on the CSRF middleware with `createCsrfMiddleware({ origin: 'https://app.example.com' })`.
47β
48> [!TIP]
49> Requests without any of these headers (`Sec-Fetch-Site`, `Origin`, or `Referer`) are rejected by default. If your deployment strips these headers and you have another layer that guarantees same-origin server function requests, you can opt in with `createCsrfMiddleware({ filter: (ctx) => ctx.handlerType === 'serverFn', allowRequestsWithoutOriginCheck: true })`.
50β
51## Basic Usage
52β
53Server functions are created with `createServerFn()` and can specify HTTP method:
54β
55```tsx
56import { createServerFn } from '@tanstack/react-start'
57β
58// GET request (default)
59export const getData = createServerFn().handler(async () => {
60 return { message: 'Hello from server!' }
61})
62β
63// POST request
64export const saveData = createServerFn({ method: 'POST' }).handler(async () => {
65 // Server-only logic
66 return { success: true }
67})
68```
69β
70## Where to Call Server Functions
71β
72Call server functions from:
73β
74- **Route loaders** - Perfect for data fetching
75- **Components** - Use with `useServerFn()` hook
76- **Other server functions** - Compose server logic
77- **Event handlers** - Handle form submissions, clicks, etc.
78β
79```tsx
80// In a route loader
81export const Route = createFileRoute('/posts')({
82 loader: () => getServerPosts(),
83})
84β
85// In a component
86function PostList() {
87 const getPosts = useServerFn(getServerPosts)
88β
89 const { data } = useQuery({
90 queryKey: ['posts'],
91 queryFn: () => getPosts(),
92 })
93}
94```
95β
96## File Organization
97β
98For larger applications, consider organizing server-side code into separate files. Here's one approach:
99β
100```
101src/utils/
102βββ users.functions.ts # Server function wrappers (createServerFn)
103βββ users.server.ts # Server-only helpers (DB queries, internal logic)
104βββ schemas.ts # Shared validation schemas (client-safe)
105```
106β
107- **`.functions.ts`** - Export `createServerFn` wrappers, safe to import anywhere
108- **`.server.ts`** - Server-only code, only imported inside server function handlers
109- **`.ts`** (no suffix) - Client-safe code (types, schemas, constants)
110β
111### Example
112β
113```tsx
114// users.server.ts - Server-only helpers
115import { db } from '~/db'
116β
117export async function findUserById(id: string) {
118 return db.query.users.findFirst({ where: eq(users.id, id) })
119}
120```
121β
122```tsx
123// users.functions.ts - Server functions
124import { createServerFn } from '@tanstack/react-start'
125import { findUserById } from './users.server'
126β
127export const getUser = createServerFn({ method: 'GET' })
128 .validator((data: { id: string }) => data)
129 .handler(async ({ data }) => {
130 return findUserById(data.id)
131 })
132```
133β
134### Static Imports Are Safe
135β
136Server functions can be statically imported in any file, including client components:
137β
138```tsx
139// β
Safe - build process handles environment shaking
140import { getUser } from '~/utils/users.functions'
141β
142function UserProfile({ id }) {
143 const { data } = useQuery({
144 queryKey: ['user', id],
145 queryFn: () => getUser({ data: { id } }),
146 })
147}
148```
149β
150The build process replaces server function implementations with RPC stubs in client bundles. The actual server code never reaches the browser.
151β
152> [!WARNING]
153> Avoid dynamic imports for server functions:
154>
155> ```tsx
156> // β Can cause bundler issues
157> const { getUser } = await import('~/utils/users.functions')
158> ```
159β
160## Parameters & Validation
161β
162Server functions accept a single `data` parameter. Since they cross the network boundary, validation ensures type safety and runtime correctness.
163β
164### Basic Parameters
165β
166```tsx
167import { createServerFn } from '@tanstack/react-start'
168β
169export const greetUser = createServerFn({ method: 'GET' })
170 .validator((data: { name: string }) => data)
171 .handler(async ({ data }) => {
172 return `Hello, ${data.name}!`
173 })
174β
175await greetUser({ data: { name: 'John' } })
176```
177β
178### Validation with Zod
179β
180For robust validation, use schema libraries like Zod:
181β
182```tsx
183import { createServerFn } from '@tanstack/react-start'
184import { z } from 'zod'
185β
186const UserSchema = z.object({
187 name: z.string().min(1),
188 age: z.number().min(0),
189})
190β
191export const createUser = createServerFn({ method: 'POST' })
192 .validator(UserSchema)
193 .handler(async ({ data }) => {
194 // data is fully typed and validated
195 return `Created user: ${data.name}, age ${data.age}`
196 })
197```
198β
199### Form Data
200β
201Handle form submissions with FormData:
202β
203```tsx
204export const submitForm = createServerFn({ method: 'POST' })
205 .validator((data) => {
206 if (!(data instanceof FormData)) {
207 throw new Error('Expected FormData')
208 }
209β
210 return {
211 name: data.get('name')?.toString() || '',
212 email: data.get('email')?.toString() || '',
213 }
214 })
215 .handler(async ({ data }) => {
216 // Process form data
217 return { success: true }
218 })
219```
220β
221### Serialization Type Checking
222β
223Server function inputs and outputs cross the network boundary, so TypeScript checks that they are serializable:
224β
225- Validator input types must be serializable. `FormData` is also allowed for `POST` server functions.
226- Handler return types must be serializable. `Response` objects are allowed.
227β
228This default behavior is called `strict` mode. If you intentionally need to opt out of these type-level serialization checks, pass the `strict` option to `createServerFn`:
229β
230```tsx
231// Disable input and output serialization type checks
232export const looseServerFn = createServerFn({ strict: false })
233 .validator((data: { value: unknown }) => data)
234 .handler(async ({ data }) => {
235 return data.value
236 })
237β
238// Disable only input serialization type checks
239export const looseInputServerFn = createServerFn({
240 strict: { input: false },
241})
242 .validator((data: { value: unknown }) => data)
243 .handler(async () => {
244 return { ok: true }
245 })
246β
247// Disable only output serialization type checks
248export const looseOutputServerFn = createServerFn({
249 strict: { output: false },
250}).handler(async () => {
251 return getCustomSerializedValue()
252})
253```
254β
255> [!WARNING]
256> `strict: false` only relaxes TypeScript's serialization checks. Values still need to be handled correctly by the runtime serialization layer when they are sent between the client and server. Prefer the default `strict: true` unless you know why the default serializability rules are too restrictive for a specific server function.
257β
258## Error Handling & Redirects
259β
260Server functions can throw errors, redirects, and not-found responses that are handled automatically when called from route lifecycles or components using `useServerFn()`.
261β
262### Basic Errors
263β
264```tsx
265import { createServerFn } from '@tanstack/react-start'
266β
267export const riskyFunction = createServerFn().handler(async () => {
268 if (Math.random() > 0.5) {
269 throw new Error('Something went wrong!')
270 }
271 return { success: true }
272})
273β
274// Errors are serialized to the client
275try {
276 await riskyFunction()
277} catch (error) {
278 console.log(error.message) // "Something went wrong!"
279}
280```
281β
282### Redirects
283β
284Use redirects for authentication, navigation, etc:
285β
286```tsx
287import { createServerFn } from '@tanstack/react-start'
288import { redirect } from '@tanstack/react-router'
289β
290export const requireAuth = createServerFn().handler(async () => {
291 const user = await getCurrentUser()
292β
293 if (!user) {
294 throw redirect({ to: '/login' })
295 }
296β
297 return user
298})
299```
300β
301### Not Found
302β
303Throw not-found errors for missing resources:
304β
305```tsx
306import { createServerFn } from '@tanstack/react-start'
307import { notFound } from '@tanstack/react-router'
308β
309export const getPost = createServerFn()
310 .validator((data: { id: string }) => data)
311 .handler(async ({ data }) => {
312 const post = await db.findPost(data.id)
313β
314 if (!post) {
315 throw notFound()
316 }
317β
318 return post
319 })
320```
321β
322## Advanced Topics
323β
324For more advanced server function patterns and features, see these dedicated guides:
325β
326### Server Context & Request Handling
327β
328Access request headers, cookies, and customize responses:
329β
330```tsx
331import { createServerFn } from '@tanstack/react-start'
332import {
333 getRequest,
334 getRequestHeader,
335 setResponseHeaders,
336 setResponseStatus,
337} from '@tanstack/react-start/server'
338β
339// Public, non-personalized data β safe to cache shared across users.
340export const getPublicData = createServerFn({ method: 'GET' }).handler(
341 async () => {
342 setResponseHeaders(
343 new Headers({
344 // 'public' is correct ONLY when the response does not depend on identity.
345 // For anything tied to a session/user/tenant, see the authenticated example below.
346 'Cache-Control': 'public, max-age=300',
347 'CDN-Cache-Control': 'max-age=3600, stale-while-revalidate=600',
348 }),
349 )
350 setResponseStatus(200)
351 return fetchPublicData()
352 },
353)
354```
355β
356> **Cache-Control safety:** `public` tells every CDN/proxy between you and the user that the response can be served to anyone. If the handler reads a session, cookie, or auth header β or branches on identity at all β using `public` will cache one user's response and replay it to the next user (cross-tenant data leak). For authenticated responses, use `private`:
357β
358```tsx
359// Authenticated data β must NOT be 'public'.
360export const getMyOrders = createServerFn({ method: 'GET' }).handler(
361 async () => {
362 const session = await requireSession()
363 setResponseHeaders(
364 new Headers({
365 // 'private' = only the user-agent may cache. Vary by Cookie/Authorization
366 // so any intermediary that does cache keys by identity, not URL alone.
367 'Cache-Control': 'private, max-age=60',
368 Vary: 'Cookie, Authorization',
369 }),
370 )
371 return db.orders.findMany({ where: { userId: session.userId } })
372 },
373)
374β
375// For sensitive data, opt out entirely:
376// setResponseHeaders(new Headers({ 'Cache-Control': 'no-store' }))
377```
378β
379Available utilities:
380β
381- `getRequest()` - Access the full Request object
382- `getRequestHeader(name)` - Read a specific request header
383- `setResponseHeader(name, value)` - Set a single response header
384- `setResponseHeaders(headers)` - Set multiple response headers via Headers object
385- `setResponseStatus(code)` - Set the HTTP status code
386β
387### Streaming
388β
389Stream typed data from server functions to the client. See the [Streaming Data from Server Functions guide](./streaming-data-from-server-functions).
390β
391### Raw Responses
392β
393Return a `Response` for binary data or custom content types, and the call resolves with it. Throw a `Response` instead to reject the call with it. Either way, the caller receives its body and headers, and its status unless a response helper set one. The browser follows a `Response` with a redirect status and a `Location` header before the caller sees it, so use `redirect()` to send the user elsewhere.
394β
395### Progressive Enhancement
396β
397Use server functions without JavaScript by leveraging the `.url` property with HTML forms.
398β
399### Middleware
400β
401Compose server functions with middleware for authentication, logging, and shared logic. See the [Middleware guide](./middleware.md).
402β
403> **Protect data in the endpoint that serves it.** Server functions are API endpoints reachable independently of whichever route renders the calling UI. Apply `authMiddleware` or an equivalent in-handler check to every server function that reads or writes private data. `beforeLoad` is useful route UX, but it is not the data boundary. See [Authentication Server Primitives](./authentication-server-primitives.md).
404β
405### Static Server Functions
406β
407Cache server function results at build time for static generation. See [Static Server Functions](./static-server-functions).
408β
409### Server Components
410β
411Server functions can return Server Components - server-rendered React components that the client can compose. See [Server Components](./server-components.md).
412β
413### Request Cancellation
414β
415Handle request cancellation with `AbortSignal` for long-running operations.
416β
417### Function ID generation for production build
418β
419Server functions are addressed by a generated, stable function ID under the hood. These IDs are embedded into the client/SSR builds and used by the server to locate and import the correct module at runtime.
420β
421By default, IDs are SHA256 hashes of the same seed to keep bundles compact and avoid leaking file paths.
422If two server functions end up with the same ID (including when using a custom generator), the system de-duplicates by appending an incrementing suffix like `_1`, `_2`, etc.
423β
424Customization:
425β
426You can customize function ID generation for the production build by providing a `generateFunctionId` function when configuring the TanStack Start build tool plugin.
427β
428Prefer deterministic inputs (filename + functionName) so IDs remain stable between builds.
429β
430Please note that this customization is **experimental** and subject to change.
431β
432Example:
433β
434<!-- ::start:tabs variant="bundler" -->
435β
436# Vite
437β
438```ts title="vite.config.ts"
439import { defineConfig } from 'vite'
440import { tanstackStart } from '@tanstack/react-start/plugin/vite'
441β
442export default defineConfig({
443 plugins: [
444 tanstackStart({
445 serverFns: {
446 generateFunctionId: ({ filename, functionName }) => {
447 return crypto
448 .createHash('sha1')
449 .update(`${filename}--${functionName}`)
450 .digest('hex')
451 },
452 },
453 }),
454 ],
455})
456```
457β
458# Rsbuild
459β
460```ts title="rsbuild.config.ts"
461import { defineConfig } from '@rsbuild/core'
462import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild'
463β
464export default defineConfig({
465 plugins: [
466 tanstackStart({
467 serverFns: {
468 generateFunctionId: ({ filename, functionName }) => {
469 return crypto
470 .createHash('sha1')
471 .update(`${filename}--${functionName}`)
472 .digest('hex')
473 },
474 },
475 }),
476 ],
477})
478```
479β
480<!-- ::end:tabs -->
481β
482---
483β
484> **Note**: Server functions use a compilation process that extracts server code from client bundles while maintaining seamless calling patterns. On the client, calls become `fetch` requests to the server.