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

connection-adapters.md

723 lines31.1 KB

1---
2title: Connection Adapters
3id: connection-adapters
4order: 3
5description: "Connection adapters bridge your client and server in TanStack AI — SSE, HTTP streaming, server functions, RPC, and persistent transports like WebSockets via subscribe/send."
6keywords:
7 - tanstack ai
8 - connection adapters
9 - sse
10 - server-sent events
11 - http stream
12 - websocket
13 - rpc
14 - server functions
15 - fetcher
16 - streaming transport
17 - fetchServerSentEvents
18 - subscribe send
19---
20​
21A **connection adapter** is the piece that decides _how_ chunks get from your server to the `ChatClient` (and through it, to your framework's `useChat`). Everything else in TanStack AI — chunk processing, message reassembly, tool calls, UI updates — is transport-agnostic. The adapter is the only thing that touches the network.
22​
23This page covers every supported transport, when to pick which, and how to build a custom one.
24​
25## Pick a Transport
26​
27| You have… | Use |
28| --- | --- |
29| A normal HTTP server and want the default | [`fetchServerSentEvents`](#server-sent-events-sse) |
30| An environment that blocks SSE (some edge runtimes, strict proxies) | [`fetchHttpStream`](#http-streaming-ndjson) |
31| React Native or Expo | [`xhrHttpStream`](#react-native-and-expo) by default, [`xhrServerSentEvents`](#react-native-and-expo) for SSE, or [`fetchHttpStream`](#http-streaming-ndjson) only when streaming `fetch` is available |
32| Code that **synchronously** returns an `AsyncIterable<StreamChunk>` (in-process `chat()`, an RSC stream, tests) | [`stream`](#server-functions-and-direct-async-iterables) |
33| An **async** call — a TanStack Start server function or any `Promise`-returning function — resolving to a `Response` or an `AsyncIterable<StreamChunk>` | [`fetcher`](#server-functions-via-fetcher) |
34| An RPC framework like Cap'n Web, gRPC-Web, or tRPC | [`rpcStream`](#rpc-streams) |
35| A single long-lived, resumable WebSocket serving many runs | [`webSocket`](#websockets) |
36| BroadcastChannel, postMessage, a shared worker, or another persistent transport | [Custom `subscribe` / `send` adapter](#persistent-transports-websockets-and-friends) |
37| Standard SSE but with custom fetch wrapping (auth refresh, retries) | [`fetchServerSentEvents` with `fetchClient`](#custom-fetch-client) |
38| Something else entirely (HTTP/3, Server-Sent Events over a different protocol, etc.) | [Custom `connect` adapter](#custom-request-scoped-adapters) |
39​
40All adapters produce the same `StreamChunk` events ([AG-UI Protocol](../migration/ag-ui-compliance)) — the choice is purely about transport.
41​
42## Server-Sent Events (SSE)
43​
44The default. SSE is well-supported across browsers, transparent through most proxies, and easy to debug. Pair it with `toServerSentEventsResponse()` on the server.
45​
46```typescript
47import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
48​
49const { messages, sendMessage } = useChat({
50 connection: fetchServerSentEvents("/api/chat"),
51});
52```
53​
54**Dynamic URL and headers.** Pass functions when the value depends on per-request state (current user, fresh token):
55​
56```typescript
57import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
58import { currentUserId, getToken } from "./auth";
59​
60const { messages } = useChat({
61 connection: fetchServerSentEvents(
62 () => `/api/chat?user=${currentUserId}`,
63 () => ({
64 headers: { Authorization: `Bearer ${getToken()}` },
65 }),
66 ),
67});
68```
69​
70**Static body.** Anything in `options.body` is merged into the AG-UI `forwardedProps` payload sent to your server. Per-message `sendMessage` `body` wins over this:
71​
72```typescript
73import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
74​
75const { messages } = useChat({
76 connection: fetchServerSentEvents("/api/chat", {
77 body: { provider: "openai", model: "gpt-5.5" },
78 }),
79});
80```
81​
82> **Tip:** `body` and `forwardedProps` populate the same wire field. Use adapter `body` for static defaults. Use the `forwardedProps` constructor option, or `sendMessage(content, { body })`, for values that change. Runtime values always win.
83​
84**Per-call body.** Pass extra JSON for one send in `sendMessage`'s second argument. It is shallow-merged into `forwardedProps` with the chat-level `body` (`{ ...chatBody, ...sendOptions.body }`). Shared keys take the `sendMessage` value. That merge is for this request only.
85​
86```typescript
87import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
88​
89const { sendMessage } = useChat({
90 connection: fetchServerSentEvents("/api/chat"),
91 forwardedProps: { provider: "openai" },
92});
93​
94await sendMessage("Summarize the attached files", {
95 body: { attachmentIds: ["att_1", "att_2"] },
96});
97```
98​
99Your server reads the merged object from `chatParamsFromRequest`. If the model must not see those keys, do not copy them into `messages`.
100​
101```typescript
102import {
103 chat,
104 chatParamsFromRequest,
105 toServerSentEventsResponse,
106} from "@tanstack/ai";
107import { openaiText } from "@tanstack/ai-openai";
108​
109export async function POST(request: Request) {
110 const { messages, forwardedProps } = await chatParamsFromRequest(request);
111 const stream = chat({
112 adapter: openaiText("gpt-5.5"),
113 messages,
114 });
115 if (
116 forwardedProps &&
117 typeof forwardedProps === "object" &&
118 "attachmentIds" in forwardedProps
119 ) {
120 const { attachmentIds } = forwardedProps
121 if (Array.isArray(attachmentIds) && attachmentIds.length > 0) {
122 // Look up the uploads. Do not add them to `messages`.
123 }
124 }
125 return toServerSentEventsResponse(stream);
127```
128​
129On `ChatClient` directly, the positional second argument is the same extra JSON. It shallow-merges with `sendOptions.body`. `sendOptions.body` wins on key collisions.
130​
131`reload()` starts a new request. It uses chat-level `forwardedProps` / `body` only. It does not replay the previous send's per-call `body`.
132​
133### Resumable SSE
134​
135`fetchServerSentEvents` watches SSE `id:` values. If a connection drops after
136receiving an id, it reconnects with `Last-Event-ID` and de-duplicates the
137replayed prefix. `joinRun(runId)` performs a read-only GET with `offset=-1` and
138the run id, replaying an in-flight or finished run from the start.
139​
140The ids only appear when the server passes a durability adapter to
141`toServerSentEventsResponse`. They are opaque tokens owned by that adapter; the
142chat client does not create, parse, or persist them. Without ids, behavior is
143identical to a plain single fetch. See
144[Resumable Streams](../resumable-streams/overview).
145​
146Your route needs a `GET` handler alongside `POST` for `joinRun` (second tab or
147reload) to work. `POST` handles fresh runs and auto-reconnects (it re-sends the
148same body with `Last-Event-ID`); `GET` replays a known run from the start:
149​
150```typescript
151import {
152 chat,
153 chatParamsFromRequest,
154 memoryStream,
155 resumeServerSentEventsResponse,
156 toServerSentEventsResponse,
157} from "@tanstack/ai";
158import { openaiText } from "@tanstack/ai-openai";
159​
160export async function POST(request: Request) {
161 const { messages, threadId, runId } = await chatParamsFromRequest(request);
162 const stream = chat({ adapter: openaiText("gpt-5.5"), messages, threadId, runId });
163 return toServerSentEventsResponse(stream, {
164 durability: { adapter: memoryStream(request) },
165 });
167​
168// joinRun hits GET ?offset=-1&runId=... (replay only, no messages sent).
169export async function GET(request: Request) {
170 return resumeServerSentEventsResponse({ adapter: memoryStream(request) });
172```
173​
174The `GET` handler calls no provider: on a replay the durability adapter's
175`resumeFrom()` is non-null (from `?offset`), so the log is replayed instead.
176`resumeServerSentEventsResponse` returns a 400 when the request has no resume
177offset. Use `resumeHttpResponse` for the NDJSON adapters.
178​
179`fetchHttpStream` and `xhrHttpStream` resume the same way over NDJSON, where the
180offset rides in an `{ id, chunk }` envelope (see below) instead of an SSE `id:`
181line. Enable it by passing a durability adapter to `toHttpResponse`.
182`xhrServerSentEvents` resumes over SSE exactly like `fetchServerSentEvents`
183(paired with `toServerSentEventsResponse` and its `id:` lines).
184​
185## HTTP Streaming (NDJSON)
186​
187For environments that don't speak SSE — some edge runtimes, certain mobile WebViews, or anywhere a proxy strips `text/event-stream` — use raw newline-delimited JSON. The wire format is one JSON `StreamChunk` per line:
188​
189```typescript
190import { useChat, fetchHttpStream } from "@tanstack/ai-react";
191​
192const { messages } = useChat({
193 connection: fetchHttpStream("/api/chat"),
194});
195```
196​
197Server-side, write each chunk as `JSON.stringify(chunk) + "\n"` to the response body (or use `toHttpResponse(stream)`). Options (`url`, `headers`, `body`, `fetchClient`, dynamic functions) match `fetchServerSentEvents` exactly.
198​
199`fetchHttpStream` is also resumable: pass a durability adapter to `toHttpResponse` and each line becomes an `{ id, chunk }` envelope. A dropped connection reconnects with `Last-Event-ID`, de-duplicates the replayed prefix, and `joinRun(runId)` attaches to an existing run. Same guarantees as [Resumable SSE](#resumable-sse), over NDJSON.
200​
201## React Native and Expo
202​
203You have a native app that needs to call your own backend rather than a
204same-origin browser route. Use `useChat` from `@tanstack/ai-react` with an
205explicit chat transport and an absolute URL. By the end of this section, the
206client adapter and server response helper will be paired correctly for React
207Native or Expo.
208​
209```typescript
210const baseUrl =
211 process.env.EXPO_PUBLIC_TANSTACK_AI_BASE_URL ??
212 'http://127.0.0.1:8787'
213const httpUrl = `${baseUrl}/chat/http`
214const sseUrl = `${baseUrl}/chat/sse`
215```
216​
217Use the URL your runtime can reach:
218​
219- **iOS simulator**: often `localhost` or `127.0.0.1`.
220- **Android emulator**: commonly `10.0.2.2` to reach the host machine.
221- **A physical device**: a LAN or tunneled URL.
222​
223Prefer `xhrHttpStream()` for Expo and React Native. It pairs with
224`toHttpResponse()` and reads newline-delimited JSON through incremental XHR
225progress events:
226​
227```typescript
228import { useChat, xhrHttpStream } from "@tanstack/ai-react";
229​
230const baseUrl = process.env.EXPO_PUBLIC_TANSTACK_AI_BASE_URL ?? 'http://127.0.0.1:8787';
231const httpUrl = `${baseUrl}/chat/http`;
232​
233const chat = useChat({
234 connection: xhrHttpStream(httpUrl),
235});
236```
237​
238Mobile connections drop often, so this is where resumability pays off most.
239Both XHR adapters reconnect and `joinRun` when the server adds a durability
240adapter. See [Resumable Streams](../resumable-streams/overview).
241​
242Use `xhrServerSentEvents()` when your server returns `text/event-stream` via
243`toServerSentEventsResponse()`:
244​
245```typescript
246import { useChat, xhrServerSentEvents } from "@tanstack/ai-react";
247​
248const baseUrl = process.env.EXPO_PUBLIC_TANSTACK_AI_BASE_URL ?? 'http://127.0.0.1:8787';
249const sseUrl = `${baseUrl}/chat/sse`;
250​
251const chat = useChat({
252 connection: xhrServerSentEvents(sseUrl),
253});
254```
255​
256Only use `fetchHttpStream()` if your exact React Native runtime exposes
257streaming `fetch` responses, `Response.body.getReader()`, and `TextDecoder`.
258The server still returns newline-delimited JSON with `toHttpResponse()`:
259​
260```typescript
261import { useChat, fetchHttpStream } from "@tanstack/ai-react";
262​
263const baseUrl = process.env.EXPO_PUBLIC_TANSTACK_AI_BASE_URL ?? 'http://127.0.0.1:8787';
264const httpUrl = `${baseUrl}/chat/http`;
265​
266const chat = useChat({
267 connection: fetchHttpStream(httpUrl),
268});
269```
270​
271If one of those fetch-streaming APIs is missing, `fetchHttpStream()` throws
272`UnsupportedResponseStreamError`. A polyfill that buffers the response does not
273make fetch streaming compatible; the adapter needs incremental bytes. Switch to
274`xhrHttpStream()` or `xhrServerSentEvents()` instead.
275​
276Keep provider SDKs and server helpers on your backend. The React Native bundle
277should import hooks and connection adapters, not OpenAI/Anthropic/Gemini SDKs,
278React DOM UI, devtools UI, or other framework packages. For a complete mobile
279walkthrough, see [Quick Start: React Native](../getting-started/quick-start-react-native).
280​
281## Server Functions and Direct Async Iterables
282​
283When your client can call into your server without going over HTTP — RSC streams, in-process tests, a direct in-process `chat()` call — skip the transport entirely. `stream()` takes a factory that returns an `AsyncIterable<StreamChunk>` **synchronously** and wires it straight into the client. (A [TanStack Start](https://tanstack.com/start) server function returns a `Promise`, so it needs [`fetcher`](#server-functions-via-fetcher), not `stream()` — see the next section.)
284​
285```typescript
286import { useChat, stream } from "@tanstack/ai-react";
287import { chatServerFn } from "./server/chat.server";
288​
289// `chatServerFn` is an in-process server-side function that synchronously
290// returns an AsyncIterable<StreamChunk> — e.g. the result of
291// `chat({ adapter, model, messages })` on the server.
292const { messages } = useChat({
293 connection: stream((messages, data) => chatServerFn({ messages, ...data })),
294});
295```
296​
297The factory receives the conversation messages plus any per-request `data` you passed to `sendMessage`. Return any async iterable that yields `StreamChunk` objects — a generator, the output of `chat()` on the server, a transformed stream, anything.
298​
299> **Tip:** `stream()` is **request-scoped**. The factory is invoked once per `sendMessage`, the iterable runs to completion, and the connection closes. If you need a single long-lived channel that multiplexes many sends — for example a WebSocket — use [`subscribe` / `send`](#persistent-transports-websockets-and-friends) instead.
300​
301`stream()` also takes an optional second argument of persistence handlers, spread onto the adapter, so server-driven persistence (`persistence: true`) works without an HTTP endpoint. Each is typically a one-line call into your server:
302​
303- `hydrate`: restores a chat thread.
304- `hydrateGeneration`: restores a generation's last run.
305- `joinRun`: replays a run still in flight.
306​
307See [Generation Persistence](../persistence/generation-persistence#server-functions--direct) for the full server-function wiring.
308​
309## Server Functions via `fetcher`
310​
311When you call into your server with an **async** function — the universal case for a [TanStack Start](https://tanstack.com/start) server function, which always returns a `Promise` — use the top-level `fetcher` option instead of a connection adapter. `fetcher` is a sibling of `connection` (provide exactly one), and it accepts a plain async function. It mirrors the `fetcher` option on the [generation hooks](../media/generation-hooks). The most common shape is a handler that ends with `toServerSentEventsResponse(...)` and resolves to a `Response`:
312​
313```typescript ignore
314// server/chat.server.ts
315import { createServerFn } from "@tanstack/react-start";
316import { chat, toServerSentEventsResponse } from "@tanstack/ai";
317import { openaiText } from "@tanstack/ai-openai";
318import type { UIMessage } from "@tanstack/ai";
319​
320export const chatFn = createServerFn({ method: "POST" })
321 .inputValidator((data: { messages: Array<UIMessage> }) => data)
322 .handler(({ data }) =>
323 toServerSentEventsResponse(
324 chat({ adapter: openaiText("gpt-5.5"), messages: data.messages }),
325 ),
326 );
327```
328​
329```typescript
330import { useChat } from "@tanstack/ai-react";
331import { chatFn } from "./server/chat.server";
332​
333const { messages, sendMessage } = useChat({
334 fetcher: ({ messages }, { signal }) => chatFn({ data: { messages }, signal }),
335});
336```
337​
338The fetcher receives `{ messages, data, threadId, runId }` plus an `AbortSignal` (triggered by `stop()` or when a send is superseded). Return either:
339​
340- a `Response`: the chat client parses its SSE body for you.
341- an `AsyncIterable<StreamChunk>`: yielded directly. This covers a server function that returns the stream itself rather than wrapping it in a `Response`.
342​
343Sync and `Promise`-wrapped returns are both accepted.
344​
345> **Tip:** The generation hooks (`useGenerateImage` and siblings) take the same server-function shape a step further: alongside their `fetcher` they accept `hydrateGeneration` and `joinRun` options, so `persistence: true` hydrates and rejoins through server functions with no HTTP route at all. See [Generation Persistence — Server functions / direct](../persistence/generation-persistence#server-functions--direct).
346​
347> **Tip:** The choice between `fetcher` and [`stream()`](#server-functions-and-direct-async-iterables) is about **async vs sync**, not `Response`-vs-iterable — both can yield an `AsyncIterable<StreamChunk>`. `stream()`'s factory must return that iterable **synchronously**, so a server-function call (which returns a `Promise`) won't typecheck there — that's the gap `fetcher` fills ([issue #509](https://github.com/TanStack/ai/issues/509)). Use `stream()` when you can hand back an async iterable synchronously (in-process `chat()`, an RPC client, tests); use `fetcher` for anything you have to `await`. Both normalize to the same request-scoped adapter, so `stop()`/abort, error handling, and tool calls behave identically.
348​
349## RPC Streams
350​
351`rpcStream()` is identical in behavior to `stream()` but reads better at call sites that hand off to an RPC client. Use it when integrating with Cap'n Web, gRPC-Web, tRPC subscriptions, or any RPC framework that already returns an async iterable:
352​
353```typescript
354import { useChat, rpcStream } from "@tanstack/ai-react";
355import { api } from "./rpc-client";
356​
357// `api.chat.stream` is your RPC method; it must return an AsyncIterable<StreamChunk>.
358const { messages } = useChat({
359 connection: rpcStream((messages, data) =>
360 api.chat.stream({ messages, ...data }),
361 ),
362});
363```
364​
365Like `stream()`, `rpcStream()` takes an optional second argument of persistence handlers (`{ hydrate, hydrateGeneration, joinRun }`) so server-driven persistence works over RPC — each handler is usually a one-line RPC call.
366​
367## WebSockets
368​
369For a persistent, resumable WebSocket, use the built-in `webSocket()` adapter instead of hand-rolling a `SubscribeConnectionAdapter`. It opens one socket for the whole conversation, reconnects a dropped durable run automatically, and pairs with the server's `toWebSocketStream` / `toWebSocketResponse`:
370​
371```typescript
372import { useChat, webSocket } from "@tanstack/ai-react";
373​
374const connection = webSocket("/api/chat-ws");
375​
376const { messages, sendMessage } = useChat({ connection });
377```
378​
379On Cloudflare Workers or Durable Objects, pair that client with `toWebSocketResponse`. Elsewhere, accept the socket yourself and pass it to `toWebSocketStream` (see [WebSockets](../resumable-streams/websockets)):
380​
381```typescript
382import { chat, memoryStream, toWebSocketResponse } from "@tanstack/ai";
383import { openaiText } from "@tanstack/ai-openai";
384​
385export default {
386 fetch(request: Request): Response {
387 return toWebSocketResponse(request, {
388 durability: (ctx) => memoryStream(ctx.request),
389 onRun: ({ messages, threadId, runId }) =>
390 chat({
391 adapter: openaiText("gpt-5.5"),
392 messages,
393 threadId,
394 runId,
395 }),
396 });
397 },
398};
399```
400​
401See [WebSockets](../resumable-streams/websockets) for the wire protocol, reconnect details, and hosting on Node vs Cloudflare.
402​
403## Persistent Transports (WebSockets and Friends)
404​
405A persistent transport — WebSocket, BroadcastChannel, postMessage between iframes, a shared worker — is fundamentally different from request/response. You open the channel **once**, then send and receive over it for the lifetime of the client. `stream()`/`connect()` can't model this cleanly because they assume one async iterable per request.
406​
407The built-in `webSocket()` adapter above covers the common resumable WebSocket case. For anything else persistent, implement the `SubscribeConnectionAdapter` interface directly. The shape (full definition in [The Adapter Interface](#the-adapter-interface)):
408​
409```typescript
410import type { SubscribeConnectionAdapter } from "@tanstack/ai-react";
411​
412// subscribe(abortSignal?): AsyncIterable<StreamChunk> — long-lived
413// send(messages, data?, abortSignal?, runContext?): Promise<void> — one per user message
414```
415​
416- `subscribe()` is called **once** by the `ChatClient` and returns a long-lived async iterable of every chunk the channel produces.
417- `send()` is called **once per user message** to push a request frame onto the channel. It returns when the frame has been written — chunks arrive separately through `subscribe()`.
418​
419The runtime correlates them: chunks emitted on the subscription queue between `send()` and the next terminal event (`RUN_FINISHED` / `RUN_ERROR`) are attributed to that run.
420​
421### Custom WebSocket example
422​
423Building your own protocol instead of the built-in `webSocket()` adapter (a different wire format, no resume support needed, or a server you don't control)? Implement `SubscribeConnectionAdapter` by hand:
424​
425```typescript
426import { useChat, type SubscribeConnectionAdapter } from "@tanstack/ai-react";
427import type { StreamChunk } from "@tanstack/ai";
428​
429function websocketConnection(url: string): SubscribeConnectionAdapter {
430 const ws = new WebSocket(url);
431 const queue: Array<StreamChunk> = [];
432 let pending: ((chunk: StreamChunk | null) => void) | null = null;
433 let closed = false;
434​
435 const ready = new Promise<void>((resolve) => {
436 ws.addEventListener("open", () => resolve(), { once: true });
437 });
438​
439 function deliver(chunk: StreamChunk | null) {
440 const resolve = pending;
441 if (resolve) {
442 pending = null;
443 resolve(chunk);
444 } else if (chunk !== null) {
445 queue.push(chunk);
446 }
447 }
448​
449 ws.addEventListener("message", (event) => {
450 const chunk: StreamChunk = JSON.parse(event.data);
451 deliver(chunk);
452 });
453 ws.addEventListener("close", () => {
454 closed = true;
455 deliver(null);
456 });
457​
458 return {
459 async *subscribe(abortSignal) {
460 // Register the abort listener once (not per-iteration) so it can't
461 // accumulate on a long-lived socket.
462 const onAbort = () => deliver(null);
463 abortSignal?.addEventListener("abort", onAbort, { once: true });
464 try {
465 while (!abortSignal?.aborted) {
466 // Drain buffered chunks BEFORE honoring `closed`: a burst of messages
467 // followed by a close event (common within one macrotask) must still
468 // deliver the queued chunks (including a trailing RUN_FINISHED),
469 // otherwise the client would hang waiting for a terminal it dropped.
470 const buffered = queue.shift();
471 if (buffered !== undefined) {
472 yield buffered;
473 continue;
474 }
475 if (closed) return;
476 const chunk = await new Promise<StreamChunk | null>((resolve) => {
477 pending = resolve;
478 });
479 if (chunk === null) return;
480 yield chunk;
481 }
482 } finally {
483 abortSignal?.removeEventListener("abort", onAbort);
484 }
485 },
486​
487 async send(messages, data, _abortSignal, runContext) {
488 await ready;
489 ws.send(
490 JSON.stringify({
491 threadId: runContext?.threadId,
492 runId: runContext?.runId,
493 messages,
494 data,
495 }),
496 );
497 },
498 };
500​
501const { messages } = useChat({
502 connection: websocketConnection("wss://example.com/chat"),
503});
504```
505​
506> **Tip:** Your server is responsible for emitting `RUN_FINISHED` (or `RUN_ERROR`) at the end of each run. Without it, the client will not know the assistant turn has ended and will wait indefinitely. See [Stream Events](./stream-events) for the full event lifecycle.
507​
508### When to choose persistent over request-scoped
509​
510Pick `subscribe` / `send` when **any** of these are true:
511​
512- A single connection multiplexes many runs (chat thread keeps the socket open across messages).
513- The server pushes chunks outside of a request (presence updates, server-initiated tool calls, broadcast notifications).
514- You want to share one connection across multiple tabs (BroadcastChannel) or workers.
515​
516Otherwise, prefer `fetchServerSentEvents` or `stream()` — they're simpler and require no connection lifecycle management.
517​
518## Custom Fetch Client
519​
520If you're keeping SSE or HTTP streaming but need to wrap `fetch` — for auth refresh, retries, logging, or routing through an edge proxy — pass a `fetchClient`:
521​
522```typescript
523import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
524import { refreshToken } from "./auth";
525​
526async function authedFetch(input: RequestInfo | URL, init?: RequestInit) {
527 let response = await fetch(input, init);
528 if (response.status === 401) {
529 await refreshToken();
530 response = await fetch(input, init);
531 }
532 return response;
534​
535const { messages } = useChat({
536 connection: fetchServerSentEvents("/api/chat", {
537 fetchClient: authedFetch,
538 }),
539});
540```
541​
542The `fetchClient` must satisfy the standard `fetch` signature. `fetchHttpStream` accepts the same option.
543​
544## Custom Request-Scoped Adapters
545​
546When none of the built-ins fit but the transport is still request-scoped (one request per user message), implement `ConnectConnectionAdapter` directly. This is the lowest-level escape hatch short of going persistent:
547​
548```typescript
549import { useChat, type ConnectConnectionAdapter } from "@tanstack/ai-react";
550import type { StreamChunk } from "@tanstack/ai";
551​
552const myAdapter: ConnectConnectionAdapter = {
553 async *connect(messages, data, abortSignal, runContext) {
554 const response = await fetch("/api/chat", {
555 method: "POST",
556 headers: {
557 "Content-Type": "application/json",
558 ...runContext?.headers,
559 },
560 body: JSON.stringify({
561 threadId: runContext?.threadId,
562 runId: runContext?.runId,
563 messages,
564 ...data,
565 }),
566 ...(abortSignal ? { signal: abortSignal } : {}),
567 });
568​
569 if (!response.ok) throw new Error(`HTTP ${response.status}`);
570 if (!response.body) throw new Error("Response has no body");
571​
572 // Example: newline-delimited JSON. Replace this loop with whatever
573 // framing your wire format uses, yielding one `StreamChunk` per event.
574 const reader = response.body.getReader();
575 const decoder = new TextDecoder();
576 let buffer = "";
577 while (true) {
578 const { done, value } = await reader.read();
579 if (done) break;
580 buffer += decoder.decode(value, { stream: true });
581 const lines = buffer.split("\n");
582 buffer = lines.pop() ?? "";
583 for (const line of lines) {
584 if (line.trim()) {
585 const chunk: StreamChunk = JSON.parse(line);
586 yield chunk;
587 }
588 }
589 }
590 },
591};
592​
593const { messages } = useChat({ connection: myAdapter });
594```
595​
596`runContext` carries `threadId`, `runId`, `clientTools`, `forwardedProps`, and `headers`. Include the first four in your JSON payload so the server can build an AG-UI-compliant response.
597​
598Copy `runContext.headers` onto the **POST request headers**, not the body. Built-in fetch and XHR adapters do this. `stream()` and `rpcStream()` do not — they never see `runContext`. A custom `connect` that skips `headers` drops BYOK keys (`x-byok-*`). See [Bring Your Own Key](../advanced/byok).
599​
600The runtime covers the terminal event either way:
601​
602- Your `connect` stream completes without emitting `RUN_FINISHED`: one is synthesized for you.
603- Your `connect` stream throws: a `RUN_ERROR` is synthesized.
604​
605## The Adapter Interface
606​
607A `ConnectionAdapter` is a union — provide **either** `connect`, **or** both `subscribe` and `send`. Never both modes.
608​
609```typescript
610import type { UIMessage } from "@tanstack/ai-client";
611import type { ModelMessage, StreamChunk } from "@tanstack/ai";
612​
613export interface RunAgentInputContext {
614 threadId: string;
615 runId: string;
616 parentRunId?: string;
617 clientTools?: Array<{ name: string; description: string; parameters: unknown }>;
618 forwardedProps?: Record<string, unknown>;
619 headers?: Record<string, string>;
621​
622export interface ConnectConnectionAdapter {
623 connect(
624 messages: UIMessage[] | ModelMessage[],
625 data?: Record<string, any>,
626 abortSignal?: AbortSignal,
627 runContext?: RunAgentInputContext,
628 ): AsyncIterable<StreamChunk>;
630​
631export interface SubscribeConnectionAdapter {
632 subscribe(abortSignal?: AbortSignal): AsyncIterable<StreamChunk>;
633 send(
634 messages: UIMessage[] | ModelMessage[],
635 data?: Record<string, any>,
636 abortSignal?: AbortSignal,
637 runContext?: RunAgentInputContext,
638 ): Promise<void>;
640​
641export type ConnectionAdapter =
642 | ConnectConnectionAdapter
643 | SubscribeConnectionAdapter;
644```
645​
646Internally, `ChatClient` normalizes both shapes to a single `subscribe`/`send` pair via `normalizeConnectionAdapter()`:
647​
648- Provide `connect` and it gets wrapped in an async queue. The wrapped `send()` waits until the active subscriber processes all events or exits.
649- Provide `subscribe` + `send` natively and they are used as-is.
650​
651## Authentication
652​
653Static headers go in `options.headers`:
654​
655```typescript
656import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
657import { token } from "./auth";
658​
659const { messages } = useChat({
660 connection: fetchServerSentEvents("/api/chat", {
661 headers: { Authorization: `Bearer ${token}` },
662 }),
663});
664```
665​
666For tokens that change per request (refresh tokens, short-lived JWTs), pass a function — it's called on every send, so the header always reflects the latest token:
667​
668```typescript
669import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
670import { getToken } from "./auth";
671​
672const { messages } = useChat({
673 connection: fetchServerSentEvents("/api/chat", () => ({
674 headers: { Authorization: `Bearer ${getToken()}` },
675 })),
676});
677```
678​
679Cookies are sent automatically when `credentials` is `"same-origin"` (default) or `"include"`.
680​
681## Cancellation
682​
683Every adapter — built-in or custom — receives an `AbortSignal`. Built-ins propagate it to `fetch`; custom adapters must honor it themselves. `useChat`'s `stop()` aborts the current run by triggering the signal:
684​
685```typescript
686import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
687​
688const { stop } = useChat({ connection: fetchServerSentEvents("/api/chat") });
689stop(); // aborts the active stream
690```
691​
692For `SubscribeConnectionAdapter`, the signal in `subscribe()` ends the entire subscription (component unmount); the signal in `send()` ends just the in-flight send.
693​
694## Error Handling
695​
696Adapters should throw on transport errors (HTTP non-2xx, parse failures, dropped sockets). The `ChatClient` catches the throw, emits a `RUN_ERROR` chunk if none has been emitted yet, and surfaces it via `onError` / the `error` state:
697​
698```typescript
699import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
700​
701const { error } = useChat({
702 connection: fetchServerSentEvents("/api/chat"),
703 onError: (err) => console.error("Chat failed:", err),
704});
705```
706​
707Don't swallow `AbortError` — let it propagate so the client knows the abort succeeded.
708​
709## Best Practices
710​
711- **Default to SSE.** It's the most compatible and the easiest to debug. Switch only when something blocks it.
712- **Use `stream()` when you can.** If you control both sides and don't need HTTP semantics, server functions are faster to wire up than building a custom adapter.
713- **Reach for `subscribe`/`send` only when you need persistence.** WebSockets are powerful but require you to handle reconnection, run correlation, and lifecycle yourself.
714- **Always honor `abortSignal`.** It's how the client cleans up on unmount and on `stop()`.
715- **Emit `RUN_FINISHED` from the server.** Without it, the client never knows the turn ended.
716​
717## Next Steps
718​
719- [Stream Events](./stream-events) for the full event lifecycle and `StreamChunk` types
720- [Streaming](./streaming) for the server and client streaming path
721- [AG-UI Client Compliance](../migration/ag-ui-compliance) — the wire protocol your server emits
722- [Cloudflare Adapter](../community-adapters/cloudflare) — example of a custom `fetchClient` in production
723- [API Reference: `@tanstack/ai-client`](../api/ai-client) — full type signatures