Open History to see the last commit
1---
2title: Request Options
3id: transports-request-options
4order: 7
5description: "Send auth headers, dynamic URLs, extra body data, and per-message data with TanStack AI transports, and wrap fetch with fetchClient."
6keywords:
7 - tanstack ai
8 - request options
9 - headers
10 - authentication
11 - forwardedProps
12 - body
13 - chatParamsFromRequest
14 - fetchClient
15---
16
17Transport options send an auth token, a user id, a model choice, or per-message data with the messages.
18
19The examples use `fetchServerSentEvents`. `fetchHttpStream` and `fetchJson` take the same options. The XHR transports take `headers` and `body` too, and use `withCredentials` for cookies.
20
21## Quick setup
22
23### 1. Send a header and extra data from the client
24
25Put headers in `headers`. Put extra JSON in `body`:
26
27```tsx
28import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
29import { getToken } from "./auth";
30
31export function Chat() {
32 const { messages, sendMessage } = useChat({
33 connection: fetchServerSentEvents("/api/chat", () => ({
34 headers: { Authorization: `Bearer ${getToken()}` },
35 body: { provider: "openai", model: "gpt-6.1-sol" },
36 })),
37 threadId: "support-chat",
38 });
39
40 return (
41 <div>
42 {messages.map((message) => (
43 <p key={message.id}>
44 {message.parts.map((part) =>
45 part.type === "text" ? part.content : "",
46 )}
47 </p>
48 ))}
49 <button onClick={() => void sendMessage("Hello")}>Send</button>
50 </div>
51 );
52}
53```
54
55The options are a function, so the transport calls it on every send. The header always has the latest token.
56
57### 2. Read them on the server
58
59Read the header from the request. Read the `body` data from `forwardedProps`:
60
61```typescript
62// api/chat.ts
63import {
64 chat,
65 chatParamsFromRequest,
66 toServerSentEventsResponse,
67} from "@tanstack/ai";
68import { openaiText } from "@tanstack/ai-openai";
69
70export async function POST(request: Request) {
71 const authorization = request.headers.get("Authorization");
72 if (!authorization) {
73 return new Response("Unauthorized", { status: 401 });
74 }
75
76 const { messages, threadId, runId, forwardedProps } =
77 await chatParamsFromRequest(request);
78 console.log("Client asked for", forwardedProps.model);
79
80 const stream = chat({
81 adapter: openaiText("gpt-6.1-sol"),
82 messages,
83 threadId,
84 runId,
85 });
86 return toServerSentEventsResponse(stream);
87}
88```
89
90Click Send. Your server gets the header, the body data, and the messages in one request.
91
92## How it works
93
94- **`headers`** go on the POST request.
95- **`body`** goes into the AG-UI `forwardedProps` field of the request body. The model does not see it.
96- **Cookies** go with the request when `credentials` is `"same-origin"` (the default) or `"include"`.
97
98## Advanced
99
100### Static headers
101
102If the token never changes, pass a plain object:
103
104```typescript
105import { fetchServerSentEvents } from "@tanstack/ai-react";
106import { token } from "./auth";
107
108export const connection = fetchServerSentEvents("/api/chat", {
109 headers: { Authorization: `Bearer ${token}` },
110});
111```
112
113Pass this `connection` to `useChat`.
114
115### Change the URL per request
116
117If the URL depends on per-request state (for example, the current user), pass a function for the URL too:
118
119```typescript
120import { fetchServerSentEvents } from "@tanstack/ai-react";
121import { currentUserId, getToken } from "./auth";
122
123export const connection = fetchServerSentEvents(
124 () => `/api/chat?user=${currentUserId}`,
125 () => ({
126 headers: { Authorization: `Bearer ${getToken()}` },
127 }),
128);
129```
130
131### Send data with one message
132
133Pass extra JSON for one send in the second argument of `sendMessage`:
134
135```tsx
136import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
137
138export function SummarizeButton() {
139 const { sendMessage } = useChat({
140 connection: fetchServerSentEvents("/api/chat"),
141 threadId: "support-chat",
142 forwardedProps: { provider: "openai" },
143 });
144
145 return (
146 <button
147 onClick={() =>
148 void sendMessage("Summarize the attached files", {
149 body: { attachmentIds: ["att_1", "att_2"] },
150 })
151 }
152 >
153 Summarize
154 </button>
155 );
156}
157```
158
159The client does a shallow merge of this `body` into the `forwardedProps` option. If a key is in both, the `sendMessage` value wins. The merge applies to this request only.
160
161Read the merged object on the server. If the model must not see those keys, do not copy them into `messages`:
162
163```typescript
164// api/chat.ts
165import {
166 chat,
167 chatParamsFromRequest,
168 toServerSentEventsResponse,
169} from "@tanstack/ai";
170import { openaiText } from "@tanstack/ai-openai";
171
172export async function POST(request: Request) {
173 const { messages, forwardedProps, threadId } = await chatParamsFromRequest(request);
174 const { attachmentIds } = forwardedProps;
175 if (Array.isArray(attachmentIds) && attachmentIds.length > 0) {
176 // Look up the uploads. Do not add them to `messages`.
177 }
178 const stream = chat({
179 adapter: openaiText("gpt-6.1-sol"),
180 messages,
181 threadId,
182 });
183 return toServerSentEventsResponse(stream);
184}
185```
186
187### Merge order
188
189`body` on the transport and `forwardedProps` fill the same wire field. Later sources win on the same key:
190
1911. The `body` option of the transport: static defaults.
1922. The `forwardedProps` option of `useChat`.
1933. The `body` of one `sendMessage` call.
194
195Two more rules:
196
197- **`ChatClient`**: `sendMessage(content, body, sendOptions)` takes the extra JSON as its second argument. The client does a shallow merge of it with `sendOptions.body`. If a key is in both, `sendOptions.body` wins.
198- **`reload()`**: it starts a new request with the transport `body` and the `forwardedProps` option. It does not send the per-call `body` of the previous send again.
199
200### Wrap fetch
201
202To keep SSE or HTTP streaming but wrap `fetch` (auth refresh, retries, logs, or an edge proxy), pass a `fetchClient`:
203
204```typescript
205import { fetchServerSentEvents } from "@tanstack/ai-react";
206import { refreshToken } from "./auth";
207
208async function authedFetch(input: RequestInfo | URL, init?: RequestInit) {
209 let response = await fetch(input, init);
210 if (response.status === 401) {
211 await refreshToken();
212 response = await fetch(input, init);
213 }
214 return response;
215}
216
217export const connection = fetchServerSentEvents("/api/chat", {
218 fetchClient: authedFetch,
219});
220```
221
222The `fetchClient` must have the standard `fetch` signature. `fetchHttpStream` accepts the same option. For a production example, see the [Cloudflare Adapter](../community-adapters/cloudflare).