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

http-stream.md

126 lines3.7 KB

1---
2title: HTTP Stream
3id: transports-http-stream
4order: 3
5description: "Stream chat chunks as newline-delimited JSON with fetchHttpStream and toHttpResponse when SSE is blocked, and resume a stream after the connection drops."
6keywords:
7 - tanstack ai
8 - http stream
9 - ndjson
10 - newline-delimited json
11 - fetchHttpStream
12 - toHttpResponse
13 - resumeHttpResponse
14---
15​
16`httpStream()` reads newline-delimited JSON: one `StreamChunk` per line. Use it when SSE is blocked.
17​
18## Quick setup
19​
20### 1. Return NDJSON from the server
21​
22Wrap the `chat()` stream with `toHttpResponse()`:
23​
24```typescript
25// api/chat.ts
26import { chat, chatParamsFromRequest, toHttpResponse } from "@tanstack/ai";
27import { openaiText } from "@tanstack/ai-openai";
28​
29export async function POST(request: Request) {
30 const { messages, threadId, runId } = await chatParamsFromRequest(request);
31 const stream = chat({
32 adapter: openaiText("gpt-6.1-sol"),
33 messages,
34 threadId,
35 runId,
36 });
37 return toHttpResponse(stream);
39```
40​
41### 2. Connect from the client
42​
43Pass `fetchHttpStream()` to `useChat`:
44​
45```tsx
46import { useChat, fetchHttpStream } from "@tanstack/ai-react";
47​
48export function Chat() {
49 const { messages, sendMessage } = useChat({
50 connection: fetchHttpStream("/api/chat"),
51 threadId: "support-chat",
52 });
53​
54 return (
55 <div>
56 {messages.map((message) => (
57 <p key={message.id}>
58 {message.parts.map((part) =>
59 part.type === "text" ? part.content : "",
60 )}
61 </p>
62 ))}
63 <button onClick={() => void sendMessage("Hello")}>Send</button>
64 </div>
65 );
67```
68​
69Click Send. Each chunk arrives as one JSON line, and the reply streams into `messages`.
70​
71`fetchHttpStream` takes the same options as `fetchServerSentEvents`: `headers`, `body`, `credentials`, `fetchClient`, and dynamic functions. See [Request Options](./request-options).
72​
73On React Native, use `xhrHttpStream` with the same server. See [React Native](./react-native).
74​
75## How it works
76​
771. `sendMessage` posts the messages to `/api/chat`.
782. `toHttpResponse()` writes each chunk as `JSON.stringify(chunk) + "\n"`.
793. `fetchHttpStream()` splits the body on newlines and parses each line into a chunk.
80​
81To write the response yourself, write each chunk in that same line format to the response body.
82​
83## Advanced
84​
85### Resume a dropped stream
86​
87Pass a durability adapter to `toHttpResponse`. Then each line becomes an `{ id, chunk }` envelope, and the client can continue a reply:
88​
89- **Reconnect.** A dropped connection reconnects with `Last-Event-ID`. The transport removes the replayed chunks that it already has.
90- **`joinRun(runId)`.** It attaches to a run that already exists.
91​
92Add a `GET` handler for `joinRun`, with `resumeHttpResponse`:
93​
94```typescript
95// api/chat.ts
96import {
97 chat,
98 chatParamsFromRequest,
99 memoryStream,
100 resumeHttpResponse,
101 toHttpResponse,
102} from "@tanstack/ai";
103import { openaiText } from "@tanstack/ai-openai";
104​
105export async function POST(request: Request) {
106 const { messages, threadId, runId } = await chatParamsFromRequest(request);
107 const stream = chat({
108 adapter: openaiText("gpt-6.1-sol"),
109 messages,
110 threadId,
111 runId,
112 });
113 return toHttpResponse(stream, {
114 durability: { adapter: memoryStream(request) },
115 });
117​
118// joinRun hits GET ?offset=-1&runId=... (replay only, no messages sent).
119export async function GET(request: Request) {
120 return resumeHttpResponse({ adapter: memoryStream(request) });
122```
123​
124The client from step 2 needs no change. `xhrHttpStream` resumes the same way.
125​
126The guarantees are the same as [resumable SSE](./sse#resume-a-dropped-stream), over NDJSON. To pick a durability adapter for production, see [Resumable Streams](../resumable-streams/overview).