Transport
Learn how to use custom transports with useChat.
The useChat transport system provides fine-grained control over how messages are sent to your API endpoints and how responses are processed. This is particularly useful for alternative communication protocols like WebSockets, custom authentication patterns, or specialized backend integrations.
Default Transport
By default, useChat uses HTTP POST requests to send messages to /api/chat:
This is equivalent to:
Custom Transport Configuration
Configure the default transport with custom options:
Dynamic Configuration
You can also provide functions that return configuration values. This is useful for authentication tokens that need to be refreshed, or for configuration that depends on runtime conditions:
Request Transformation
Transform requests before sending to your API:
WebSocket Transport
Use WebSocketChatTransport when you want chat turns to share a persistent
WebSocket connection instead of opening an HTTP request for every turn. This is
useful for chats with frequent client-side tool results or other multi-step
interactions.
The transport multiplexes requests by requestId, validates incoming
UIMessageChunk values, forwards aborts to the server, and reuses the open
socket for later turns. HTTP and HTTPS URLs are automatically converted to WS
and WSS URLs.
The code that creates a transport owns its lifecycle. React and Vue chat hooks
do not close caller-supplied transports when options change or components are
disposed, because the same transport can be shared by multiple chats. Call
transport.close() after its last consumer is gone. If a directly managed
Chat instance exclusively owns the transport, call chat.dispose(); for a
shared transport, stop individual chats and close the transport only after all
consumers are finished.
Your WebSocket server must implement the
WebSocketChatTransport protocol.
The exported WebSocketChatTransportRequest and
WebSocketChatTransportResponse types can be used to type server frames. Use
safeValidateWebSocketChatTransportRequest before handling an untrusted client
frame.
Browser WebSocket APIs cannot set arbitrary handshake headers. The headers
option is included inside each application-level request frame. Authenticate
the handshake with secure cookies, a short-lived query parameter, or a
subprotocol, and validate the connection origin and every frame on the server.
sendAutomaticallyWhen still starts a new chat turn after the preceding UI
message stream finishes. WebSocketChatTransport avoids opening another HTTP
connection for that turn, but it does not send tool results into an active
model generation.
If the socket closes during a response, the active stream errors. A later send
opens a new connection. The transport does not automatically replay requests,
because replaying a generation can duplicate model output or tool effects.
reconnectToStream requests a complete replay of the retained response from
sequence zero. Chat rebuilds the message with a fresh parser, so the replay must
include all earlier chunks and the original start chunk's messageId. That
stable message ID lets Chat replace the partial assistant message. Duplicate
sequence numbers are ignored within each response stream.
For complete options, protocol details, cancellation behavior, and a server
example, see the
WebSocketChatTransport reference.
Direct Agent Transport
For scenarios where you want to communicate directly with an Agent without going through HTTP, you can use DirectChatTransport. This transport invokes the agent's stream() method directly in-process.
This is useful for:
- Server-side rendering: Run the agent on the server without an API endpoint
- Testing: Test chat functionality without network requests
- Single-process applications: Desktop or CLI apps where client and agent run together
How It Works
Unlike DefaultChatTransport which sends HTTP requests:
DirectChatTransportvalidates incoming UI messages- Converts them to model messages using
convertToModelMessages - Calls the agent's
stream()method directly - Returns the result as a UI message stream via
toUIMessageStream()
Configuration Options
You can pass additional options to customize the stream output:
DirectChatTransport does not support stream reconnection since there is no
persistent server-side stream. The reconnectToStream() method always returns
null.
For complete API details, see the DirectChatTransport reference.
Workflow Transport
For chat apps built on the Workflow SDK, WorkflowChatTransport from @ai-sdk/workflow provides automatic stream reconnection. It handles the common scenario where a workflow function times out mid-stream — the transport detects the missing finish event and reconnects to resume from where it left off.
Key features:
- Automatic reconnection: Detects interrupted streams (no
finishevent) and reconnects via GET to{api}/{runId}/stream - Page refresh recovery:
initialStartIndexcontrols where the initial reconnection begins - Configurable retries:
maxConsecutiveErrorscontrols how many consecutive reconnection failures to tolerate - Lifecycle callbacks:
onChatSendMessageandonChatEndfor tracking chat state
Negative initialStartIndex values can fetch only the tail when the durable
server stream already stores UIMessageChunk objects. For raw WorkflowAgent
streams, use a non-negative cursor and follow the server-side conversion in the
WorkflowAgent guide.
For the full API reference, see WorkflowChatTransport. For server-side endpoint setup, see the WorkflowAgent guide.
Building Custom Transports
To understand how to build your own transport, refer to the source code of the default implementation:
- DefaultChatTransport - The complete default HTTP transport implementation
- HttpChatTransport - Base HTTP transport with request handling
- ChatTransport Interface - The transport interface you need to implement
These implementations show you exactly how to:
- Handle the
sendMessagesmethod - Process UI message streams
- Transform requests and responses
- Handle errors and connection management
The transport system gives you complete control over how your chat application communicates, enabling integration with any backend protocol or service.