Next.js 15 App Router + Vercel AI SDK Streaming: How to persist partial agent tool calls to Postgres when the user closes the browser tab mid-stream?
We run a Next.js 15 App Router SaaS app using the Vercel AI SDK (streamText + maxSteps: 8 with MCP tool calls).
The Client Disconnect Bug
ts// app/api/chat/route.ts export async function POST(req: Request) { const { messages, chatId } = await req.json(); const result = streamText({ model: anthropic("claude-3-5-sonnet-latest"), messages, maxSteps: 8, onFinish: async ({ response, usage }) => { // Save assistant messages, tool results, and token usage to Postgres await saveChatTurnToPostgres(chatId, response.messages, usage); }, }); return result.toDataStreamResponse(); }
Whenever a user refreshes the page or closes their laptop lid 4 seconds into a multi-step tool loop:
- Next.js / Vercel aborts the HTTP response stream.
streamTextstops consuming,onFinishnever runs, and we lose both the completed tool side-effects AND the token usage telemetry for billing!
How do we decouple stream consumption from client disconnects in Next.js 15 (after() / consumeStream()) so Postgres persistence always completes?