Demo link: https://firstdomain.world
This gist demonstrates how to implement resumable AI SDK chat streaming using Vercel Workflow, allowing chat sessions to survive network interruptions and function timeouts.
- Resumable streaming: Chat continues even after network interruptions
- Persistent state: Chat history saved in localStorage
- Workflow durability: Long-running operations survive function timeouts
- Error recovery: Automatic reconnection with stored workflow run IDs
chat.tsx- Main chat component with WorkflowChatTransportapi-chat-route.ts- Initial chat API route (/api/chat/route.ts)api-chat-resume-route.ts- Resume API route (/api/chat/[id]/stream/route.ts)chat-workflow.ts- Workflow implementation with durable stepschat-schema.ts- TypeScript types for messageschat-input.tsx- Chat input component
- WorkflowChatTransport: Handles resumable streaming with workflow run ID storage
- Workflow Functions: Durable orchestration that survives timeouts
- Step Functions: Individual operations with full Node.js access
- Persistence Layer: localStorage for demo (use database in production)
- Initial Request: Client sends message to
/api/chat - Workflow Creation: Server starts workflow and returns run ID in
x-workflow-run-idheader - ID Storage: Client stores workflow run ID in localStorage
- Interruption Handling: On network errors, client reconnects using stored run ID
- Resume Stream: Client calls
/api/chat/{workflowRunId}/streamwith startIndex - State Recovery: Workflow resumes from last checkpoint
transport: new WorkflowChatTransport({
prepareReconnectToStreamRequest: ({ id, api, ...rest }) => {
const workflowRunId = localStorage.getItem('active-workflow-run-id');
return {
...rest,
api: `/api/chat/${encodeURIComponent(workflowRunId)}/stream`,
};
},
})export async function chat(messages: UIMessage[]) {
'use workflow';
const writable = getWorkflowWritableStream<UIMessageChunk>();
// Durable steps that survive function timeouts
for (let i = 0; i < MAX_STEPS; i++) {
const result = await streamTextStep(i, currMessages, writable);
// State automatically persisted between steps
}
}- Set up Vercel Workflow SDK in your Next.js project
- Copy these files to appropriate locations:
chat.tsxβapp/chat.tsxapi-chat-route.tsβapp/api/chat/route.tsapi-chat-resume-route.tsβapp/api/chat/[id]/stream/route.tschat-workflow.tsβworkflows/chat.ts
- Install dependencies:
@vercel/workflow-ai,@ai-sdk/react,ai - Configure your AI provider in the workflow
- Resilient UX: Users don't lose progress during network issues
- Scalable: Handles long-running AI operations without function timeouts
- Developer-friendly: Standard React hooks with workflow durability
- Production-ready: Built on Vercel's durable execution primitives
Perfect for AI applications requiring reliable, long-running conversations!