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

overview.md

164 lines6.3 KB

1---
2title: Transports
3id: transports-overview
4order: 1
5description: "Pick how your chat gets chunks from the server to useChat: SSE, HTTP stream, JSON, WebSockets, React Native, server functions, or your own transport."
6keywords:
7 - tanstack ai
8 - transports
9 - connection adapters
10 - streaming transport
11 - sse
12 - http stream
13 - websocket
14 - server functions
15 - cancellation
16 - error handling
17redirect_from:
18 - /chat/connection-adapters
19---
20​
21A transport carries chunks from the server to `useChat`. Pick one from where the code runs: a web server, an edge runtime, a phone, or one process.
22​
23A transport is the one part of the chat that touches the network. You pick it with the `connection` option of `useChat`. Messages, tool calls, and UI updates work the same on every transport.
24​
25## Pick a transport
26​
27Start at the top. Use the first row that matches your app.
28​
29| Your app | Use | Page |
30| --- | --- | --- |
31| A normal HTTP server | `fetchServerSentEvents` | [Server-Sent Events](./sse) |
32| A runtime or proxy that blocks SSE | `fetchHttpStream` | [HTTP Stream](./http-stream) |
33| A host or proxy that buffers or breaks streams | `fetchJson` | [JSON](./json) |
34| React Native or Expo | `xhrHttpStream` | [React Native](./react-native) |
35| A TanStack Start server function, with no HTTP route | `fetcher` | [Server Functions](./server-functions#quick-setup) |
36​
37Not sure? Use SSE. It works in the most places, and it is the easiest to debug.
38​
39Less common cases:
40​
41| Your app | Use | Page |
42| --- | --- | --- |
43| A function that returns an `AsyncIterable<StreamChunk>` synchronously (in-process `chat()`, an RSC stream, tests) | `stream` | [Server Functions](./server-functions#in-process-streams) |
44| An RPC framework, such as Cap'n Web, gRPC-Web, or tRPC | `rpcStream` | [Server Functions](./server-functions#rpc-clients-with-rpcstream) |
45| One long-lived, resumable WebSocket for many runs | `webSocket` | [WebSockets](./websockets) |
46| BroadcastChannel, postMessage, a shared worker, or a different persistent channel | Your own `subscribe` / `send` adapter | [Custom Transports](./custom#persistent-transports) |
47| A different protocol, such as HTTP/3 | Your own `connect` adapter | [Custom Transports](./custom#request-scoped-adapters) |
48​
49To send headers, extra body data, or an auth token on any transport, see [Request Options](./request-options). To wrap `fetch` for auth refresh or retries, see [Wrap fetch](./request-options#wrap-fetch).
50​
51## Plug it in
52​
53Pass the transport to `useChat` as `connection`:
54​
55```tsx
56import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
57​
58export function Chat() {
59 const { messages, sendMessage } = useChat({
60 connection: fetchServerSentEvents("/api/chat"),
61 threadId: "support-chat",
62 });
63​
64 return (
65 <div>
66 {messages.map((message) => (
67 <p key={message.id}>
68 {message.parts.map((part) =>
69 part.type === "text" ? part.content : "",
70 )}
71 </p>
72 ))}
73 <button onClick={() => void sendMessage("Hello")}>Send</button>
74 </div>
75 );
77```
78​
79To change transports, change only the `connection` line and the matching server helper. Each transport page shows both halves. For the full server and client path, see [Streaming](../chat/streaming).
80​
81## How it works
82​
83- **The server** runs `chat()` and writes its chunks in one format: SSE, NDJSON, JSON, or WebSocket frames.
84- **The transport** reads that format and turns it back into `StreamChunk` events.
85- **The chat client** processes those events the same way on every transport.
86​
87All transports produce the same `StreamChunk` events ([AG-UI Protocol](../migration/ag-ui-compliance)). Only the wire format changes.
88​
89Pick a row, send a message, and the reply streams into `messages`.
90​
91## Advanced
92​
93### Cancel a run
94​
95Every transport gets an `AbortSignal`. The `stop()` function from `useChat` triggers the signal and aborts the active run:
96​
97```tsx
98import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
99​
100export function StopButton() {
101 const { stop, isLoading } = useChat({
102 connection: fetchServerSentEvents("/api/chat"),
103 threadId: "support-chat",
104 });
105​
106 return (
107 <button disabled={!isLoading} onClick={stop}>
108 Stop
109 </button>
110 );
112```
113​
114Who handles the signal:
115​
116- **Built-in transports** pass the signal to `fetch`.
117- **Custom transports** must honor the signal themselves.
118- **`SubscribeConnectionAdapter`**: the signal in `subscribe()` ends the full subscription (for example, on unmount). The signal in `send()` ends only the active send.
119​
120The fetch transports cancel the response body in these cases:
121​
122- Parsing fails.
123- You exit the chunk iterator early.
124​
125A response that gets to its normal end keeps all of its chunks.
126​
127Custom cancellation hooks do not delay errors or early iterator returns. The transports release the reader lock, also when cancellation fails or stays pending.
128​
129### Errors
130​
131A transport throws on a transport error:
132​
133- An HTTP status that is not 2xx.
134- A parse failure.
135- A dropped socket.
136​
137The `ChatClient` catches the error. If no `RUN_ERROR` chunk came yet, the client emits one. Then it shows the error through `onError` and the `error` state:
138​
139```tsx
140import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
141​
142export function ChatError() {
143 const { error } = useChat({
144 connection: fetchServerSentEvents("/api/chat"),
145 threadId: "support-chat",
146 onError: (err) => console.error("Chat failed:", err),
147 });
148​
149 return error ? <p>{error.message}</p> : null;
151```
152​
153If the connection drops in the middle of a line, the stream transports throw `StreamTruncatedError`.
154​
155In a custom transport, do not catch and hide an `AbortError`. Let it propagate, so that the client knows that the abort worked.
156​
157### Rules for a custom transport
158​
159- **Use `stream()` when you can.** If you control both sides and do not need HTTP, a server function takes less code than a custom adapter.
160- **Use `subscribe` / `send` only for a persistent channel.** Then you handle reconnection, run correlation, and the connection lifecycle yourself.
161- **Always honor `abortSignal`.** The client uses it to clean up on unmount and on `stop()`.
162- **Emit `RUN_FINISHED` from the server.** Without it, the client does not know that the turn ended. See [Stream Events](../chat/stream-events).
163​
164For the full type signatures, see [API Reference: `@tanstack/ai-client`](../api/ai-client).