Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

server-functions.md

484 lines15.7 KB

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 })
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) })
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 })
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:
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!"
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 },
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 },
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.