Skip to main content
Back to Community & Earn Hub
Q&A Questionai-agents +150 pt Bounty

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?

@ishaan_malhotra4 days ago 1514 views

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:

  1. Next.js / Vercel aborts the HTTP response stream.
  2. streamText stops consuming, onFinish never 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?

1 Answers

Community Answers

@priya_sharma Accepted Answer4 days ago

The reason onFinish never fires on tab close is that the Vercel AI SDK stream is pull-based: when the browser closes the HTTP connection, the response ReadableStream cancels, stopping the internal async iterator before onFinish is reached.

In Next.js 15+, the clean official fix is combining result.consumeStream() inside Next.js's after() API (which keeps the serverless/Node lifecycle alive after the response finishes or aborts) and NOT forwarding req.signal as abortSignal to streamText:


Production Route Handler (Next.js 15 App Router)

ts
import { after } from "next/server";
import { streamText } from "ai";
import { anthropic } from "@ai-sdk/anthropic";

export async function POST(req: Request) {
  const { messages, chatId } = await req.json();

  // Do NOT pass `abortSignal: req.signal` if you want the agent turn to finish server-side!
  const result = streamText({
    model: anthropic("claude-3-5-sonnet-latest"),
    messages,
    maxSteps: 8,
    onStepFinish: async ({ toolResults, usage }) => {
      // Optional: persist each completed step incrementally for crash safety
      await saveStepProgress(chatId, toolResults, usage);
    },
    onFinish: async ({ response, usage }) => {
      await saveChatTurnToPostgres(chatId, response.messages, usage);
    },
  });

  // Ensure the stream finishes draining on the server even if the client disconnects!
  after(async () => {
    await result.consumeStream();
  });

  return result.toDataStreamResponse();
}

Why after() + result.consumeStream() Works:

  1. result.consumeStream() creates a server-side tee/consumer that drains the full streamText execution to completion regardless of whether the browser socket closed early.
  2. after() (Next.js 15) guarantees Vercel / Node waits for consumeStream() and onFinish() to resolve before freezing or tearing down the function instance.
  3. onStepFinish incremental saves ensure that even if a 300-second serverless timeout hits mid-trajectory, every completed MCP tool call and token count is already safely persisted in Postgres.

Have a solution or working configuration?

Sign in or create a free account to answer this question (+10 pts, +25 pts if accepted) and tag helpful AIStoreHub repositories.