Open History to see the last commit
1---
2title: Server Functions
3id: transports-server-functions
4order: 6
5description: "Call your server code directly from useChat with fetcher, stream(), or rpcStream(): TanStack Start server functions, RSC streams, RPC clients, and tests."
6keywords:
7 - tanstack ai
8 - server functions
9 - tanstack start
10 - fetcher
11 - stream
12 - rpcStream
13 - rpc
14 - async iterable
15---
16
17Pass a server function to `useChat` when the client can call that function directly. Pick the helper from the return value:
18
19| Your function | Use |
20| --- | --- |
21| Returns a `Promise`, such as a [TanStack Start](https://tanstack.com/start) server function | [`fetcher`](#quick-setup) |
22| Returns an `AsyncIterable<StreamChunk>` synchronously (in-process `chat()`, an RSC stream, tests) | [`stream()`](#in-process-streams) |
23| Is an RPC method that returns an async iterable | [`rpcStream()`](#rpc-clients-with-rpcstream) |
24
25All three become the same request-scoped transport. So `stop()`, abort, errors, and tool calls work the same.
26
27## Quick setup
28
29This setup uses a TanStack Start server function.
30
31### 1. Write the server function
32
33End the server function with `toServerSentEventsResponse(...)`. It resolves to a `Response`:
34
35```typescript ignore
36// server/chat.server.ts
37import { createServerFn } from "@tanstack/react-start";
38import { chat, toServerSentEventsResponse } from "@tanstack/ai";
39import { openaiText } from "@tanstack/ai-openai";
40import type { UIMessage } from "@tanstack/ai";
41
42export const chatFn = createServerFn({ method: "POST" })
43 .inputValidator((data: { messages: Array<UIMessage>; threadId: string }) => data)
44 .handler(({ data }) =>
45 toServerSentEventsResponse(
46 chat({
47 adapter: openaiText("gpt-6.1-sol"),
48 messages: data.messages,
49 threadId: data.threadId,
50 }),
51 ),
52 );
53```
54
55### 2. Pass it to `useChat` as `fetcher`
56
57Use the top-level `fetcher` option, not `connection`:
58
59```tsx
60import { useChat } from "@tanstack/ai-react";
61import { chatFn } from "./server/chat.server";
62
63export function Chat() {
64 const { messages, sendMessage } = useChat({
65 fetcher: ({ messages, threadId }, { signal }) =>
66 chatFn({ data: { messages, threadId }, signal }),
67 threadId: "support-chat",
68 });
69
70 return (
71 <div>
72 {messages.map((message) => (
73 <p key={message.id}>
74 {message.parts.map((part) =>
75 part.type === "text" ? part.content : "",
76 )}
77 </p>
78 ))}
79 <button onClick={() => void sendMessage("Hello")}>Send</button>
80 </div>
81 );
82}
83```
84
85Click Send. The reply streams into `messages`, and your app has no chat route of its own.
86
87## How it works
88
891. `sendMessage` calls your fetcher with the messages and an `AbortSignal`.
902. The server function runs `chat()` and returns an SSE `Response`.
913. The chat client parses the SSE body, the same as with `fetchServerSentEvents`.
92
93The choice of helper depends on whether your function is sync or async. Both `stream()` and `fetcher` can give back an `AsyncIterable<StreamChunk>`. A server function returns a `Promise`, so it does not type-check in `stream()`.
94
95## In-process streams
96
97`stream()` takes a factory that returns an `AsyncIterable<StreamChunk>` synchronously. It connects that iterable straight to the client.
98
99On the server side, read the run input with `chatParamsFromRequestBody`, then stream `chat()`:
100
101```typescript
102// server/chat.server.ts
103import { chat, chatParamsFromRequestBody } from "@tanstack/ai";
104import { openaiText } from "@tanstack/ai-openai";
105
106export async function* chatServerFn(input: unknown) {
107 const { messages, threadId, runId, resume } =
108 await chatParamsFromRequestBody(input);
109
110 yield* chat({
111 adapter: openaiText("gpt-6.1-sol"),
112 messages,
113 threadId,
114 runId,
115 resume,
116 });
117}
118```
119
120Then pass the factory to `stream()`. The 4th argument is the run input:
121
122```typescript
123import { useChat, stream } from "@tanstack/ai-react";
124import { chatServerFn } from "./server/chat.server";
125
126export function useInProcessChat() {
127 return useChat({
128 connection: stream((_messages, _data, _signal, input) =>
129 chatServerFn(input),
130 ),
131 threadId: "support-chat",
132 });
133}
134```
135
136The factory gets these arguments:
137
138- `messages`: the conversation messages.
139- `data`: the per-request data that you passed to `sendMessage`.
140- `signal`: fires on `stop()`.
141- `input`: the AG-UI run input, the same body the HTTP adapters send. It holds `threadId`, `runId`, `resume`, the client tools, and `forwardedProps`.
142
143Return any async iterable that yields `StreamChunk` objects: a generator, the output of `chat()`, or a transformed stream.
144
145`stream()` is request-scoped. For each `sendMessage`, it calls the factory once, runs the iterable to its end, and closes the connection. For one long-lived channel that carries many sends, see [Custom Transports](./custom#persistent-transports).
146
147## RPC clients with `rpcStream`
148
149`rpcStream()` works the same as `stream()`. The name reads better when you call an RPC client. Use it with Cap'n Web, gRPC-Web, tRPC subscriptions, or any RPC framework that returns an async iterable:
150
151```typescript
152import { useChat, rpcStream } from "@tanstack/ai-react";
153import { api } from "./rpc-client";
154
155// `api.chat.stream` is your RPC method. It must return an AsyncIterable<StreamChunk>.
156export function useRpcChat() {
157 return useChat({
158 connection: rpcStream((_messages, _data, _signal, input) =>
159 api.chat.stream(input),
160 ),
161 threadId: "support-chat",
162 });
163}
164```
165
166On the server, read `input` with `chatParamsFromRequestBody`, the same as the `stream()` server function above.
167
168## Advanced
169
170### Async functions with `fetcher`
171
172Give `useChat` exactly one of `fetcher` or `connection`. The option works like `fetcher` on the [generation hooks](../media/generation-hooks).
173
174The fetcher gets two arguments:
175
176- **Input**: `{ messages, data, threadId, runId }`. A child run also gets `parentRunId`. A resumed run also gets `resume`.
177- **Options**: `{ signal, headers }`. The signal fires on `stop()`, or when a new send replaces the active one. `headers` holds extra request headers for this run, such as BYOK keys.
178
179Return one of these:
180
181- **A `Response`**: the chat client parses its SSE body for you.
182- **An `AsyncIterable<StreamChunk>`**: the client reads it directly. Use this when your server function returns the stream itself, not a `Response`.
183
184The fetcher can return the value directly or in a `Promise`.
185
186### Persistence handlers
187
188`stream()` and `rpcStream()` take an optional second argument with persistence handlers. With them, server-driven persistence (`persistence: true`) works with no HTTP endpoint. Each one is usually a one-line call into your server:
189
190- `hydrate`: restores a chat thread.
191- `hydrateGeneration`: restores the last run of a generation.
192- `joinRun`: replays a run that is still in flight.
193
194The generation hooks (`useGenerateImage` and the others) also accept `hydrateGeneration` and `joinRun` options next to their `fetcher`. So `persistence: true` hydrates and rejoins through server functions too.
195
196For the full wiring, see [Generation Persistence: Server functions / direct](../persistence/generation-persistence#server-functions--direct).