--- title: WebSockets id: transports-websockets order: 4 description: "Run many chat turns over one resumable WebSocket with the webSocket() adapter and toWebSocketResponse or toWebSocketStream on the server." keywords: - tanstack ai - websocket - webSocket - toWebSocketResponse - toWebSocketStream - persistent transport - resumable websocket --- `webSocket()` opens one socket for the conversation. A durable run reconnects on that socket. ## Quick setup ### 1. Accept the socket on the server On Cloudflare Workers or Durable Objects, use `toWebSocketResponse`: ```typescript // worker.ts import { chat, memoryStream, toWebSocketResponse } from "@tanstack/ai"; import { openaiText } from "@tanstack/ai-openai"; export default { fetch(request: Request): Response { return toWebSocketResponse(request, { durability: (ctx) => memoryStream(ctx.request), onRun: ({ messages, threadId, runId }) => chat({ adapter: openaiText("gpt-6.1-sol"), messages, threadId, runId, }), }); }, }; ``` On other hosts, such as Node, accept the socket yourself. Then pass it to `toWebSocketStream`. See [Resumable Streams: WebSockets](../resumable-streams/websockets#hosting-on-node). ### 2. Connect from the client ```tsx import { useChat, webSocket } from "@tanstack/ai-react"; const connection = webSocket("/api/chat-ws"); export function Chat() { const { messages, sendMessage } = useChat({ connection, threadId: "support-chat" }); return (
{message.parts.map((part) => part.type === "text" ? part.content : "", )}
))}