Open History to see the last commit
1---
2title: WebSockets
3id: transports-websockets
4order: 4
5description: "Run many chat turns over one resumable WebSocket with the webSocket() adapter and toWebSocketResponse or toWebSocketStream on the server."
6keywords:
7 - tanstack ai
8 - websocket
9 - webSocket
10 - toWebSocketResponse
11 - toWebSocketStream
12 - persistent transport
13 - resumable websocket
14---
15
16`webSocket()` opens one socket for the conversation. A durable run reconnects on that socket.
17
18## Quick setup
19
20### 1. Accept the socket on the server
21
22On Cloudflare Workers or Durable Objects, use `toWebSocketResponse`:
23
24```typescript
25// worker.ts
26import { chat, memoryStream, toWebSocketResponse } from "@tanstack/ai";
27import { openaiText } from "@tanstack/ai-openai";
28
29export default {
30 fetch(request: Request): Response {
31 return toWebSocketResponse(request, {
32 durability: (ctx) => memoryStream(ctx.request),
33 onRun: ({ messages, threadId, runId }) =>
34 chat({
35 adapter: openaiText("gpt-6.1-sol"),
36 messages,
37 threadId,
38 runId,
39 }),
40 });
41 },
42};
43```
44
45On other hosts, such as Node, accept the socket yourself. Then pass it to `toWebSocketStream`. See [Resumable Streams: WebSockets](../resumable-streams/websockets#hosting-on-node).
46
47### 2. Connect from the client
48
49```tsx
50import { useChat, webSocket } from "@tanstack/ai-react";
51
52const connection = webSocket("/api/chat-ws");
53
54export function Chat() {
55 const { messages, sendMessage } = useChat({ connection, threadId: "support-chat" });
56
57 return (
58 <div>
59 {messages.map((message) => (
60 <p key={message.id}>
61 {message.parts.map((part) =>
62 part.type === "text" ? part.content : "",
63 )}
64 </p>
65 ))}
66 <button onClick={() => void sendMessage("Hello")}>Send</button>
67 </div>
68 );
69}
70```
71
72Send two messages. Both replies stream over the same socket.
73
74## How it works
75
761. `webSocket()` opens the socket on the first `sendMessage`.
772. Each user message goes over the socket as one frame.
783. The server runs one `chat()` turn for each frame, through `onRun`, and streams the chunks back.
794. The socket stays open for the next message.
80
81For the wire protocol, the `onRun` context, client options, and the reconnect details, see [Resumable Streams: WebSockets](../resumable-streams/websockets).
82
83## Advanced
84
85### Use your own wire format
86
87To use your own wire format or a server that you do not control, write a custom transport. See [Custom Transports](./custom#persistent-transports).