How streamText and useChat Prevent Memory Leaks in Next.js App Router
Memory leaks in Next.js App Router chat streaming usually come from un-aborted upstream streams, leaked event listeners/timers/closures across React unmounts, or unbounded client message/attachment state rather than the streaming transport itself.
- Propagate
req.signaltostreamText(abortSignal): Forwarding the incoming request’sAbortSignallets the server cancel upstream model generation and clean up stream resources when a client disconnects or callsstop(). - Stabilize
useChattransport, options, and callbacks: Creating new transport instances, inline callbacks, or unstable references on every render can cause unnecessary re-subscriptions or stale closures holding references to large component scopes. - Clean up client timers, audio/media URLs, and listeners on unmount: Any
AbortController, object URLs (URL.createObjectURL), WebSockets/audio contexts, or intervals tied to a chat session must be torn down when the component unmounts or switches conversations. - Bound active transcript size or archive older turns: Keeping massive multi-megabyte transcripts or base64/media payloads in React state indefinitely bloats browser memory over long sessions.
Steps to Wire streamText and useChat Without Memory Leaks
- Pass
abortSignal: req.signalin the App Router route handler: Convert UI messages withconvertToModelMessages(messages), passabortSignal: req.signaltostreamText, and return the UI message stream response cleanly. - Release server resources in
onAbort/onFinish: Clean up temporary buffers, database locks, or background tasks when streaming ends or aborts. - Memoize the transport/configuration in the Client Component: Keep the chat endpoint transport stable (
useMemo) and pass a freshchatId(key={chatId}) when switching threads so state resets cleanly instead of accumulating stale state. - Abort in-flight requests and revoke temporary resources on cleanup: Call
stop()or abort custom signals during unmount/navigation cleanup and release any allocated client media/buffer references.
TypeScript Example: Leak-Safe App Router Route and useChat Client
// app/api/chat/route.ts
import { convertToModelMessages, streamText, UIMessage } from "ai";
import { openai } from "@ai-sdk/openai";
export async function POST(req: Request) {
const { messages }: { messages: UIMessage[] } = await req.json();
const result = streamText({
model: openai("gpt-4o-mini"),
messages: await convertToModelMessages(messages),
abortSignal: req.signal,
onAbort: ({ steps }) => {
// Release any per-request resources when client aborts or disconnects
void steps;
},
});
return result.toUIMessageStreamResponse({
onFinish: () => {
// Optional telemetry/cleanup hook after stream completes
},
});
}
// app/components/ChatPanel.tsx
"use client";
import { useEffect, useMemo, useState } from "react";
import { useChat } from "@ai-sdk/react";
import { DefaultChatTransport } from "ai";
export function ChatPanel({ sessionId }: { sessionId: string }) {
const [input, setInput] = useState("");
const transport = useMemo(
() =>
new DefaultChatTransport({
api: "/api/chat",
}),
[]
);
const { messages, sendMessage, stop, status, error } = useChat({
id: sessionId,
transport,
onError: (err) => {
console.error("Chat stream error:", err);
},
});
useEffect(() => {
return () => {
// Stop any active stream when unmounting or switching sessions
stop();
};
}, [sessionId, stop]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
const trimmed = input.trim();
if (!trimmed) return;
setInput("");
await sendMessage({ text: trimmed });
};
return (
<div>
<div>
{messages.map((m) => (
<div key={m.id}>
<strong>{m.role}:</strong>{" "}
{m.parts
.filter((p) => p.type === "text")
.map((p, idx) => (
<span key={idx}>{p.text}</span>
))}
</div>
))}
</div>
{error && <p>Error: {error.message}</p>}
<form onSubmit={handleSubmit}>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
disabled={status === "streaming" || status === "submitted"}
placeholder="Type a message..."
/>
{(status === "streaming" || status === "submitted") && (
<button type="button" onClick={() => stop()}>
Stop
</button>
)}
<button type="submit" disabled={status === "streaming" || status === "submitted"}>
Send
</button>
</form>
</div>
);
}
Helpful Tips for Production Next.js Streaming
- Verify platform cancellation support: On serverless platforms, client disconnects only propagate to
req.signalif request cancellation is enabled for the route/runtime; otherwise the server stream can keep running until completion or timeout. - Avoid storing huge binary/base64 strings in React state: Upload files or audio to object storage/URLs and keep lightweight references in messages rather than retaining large raw buffers in browser memory.
- Use
key={sessionId}on chat containers: Mounting a fresh chat component per conversation ensures previous message arrays, hooks, and child component state are garbage-collected cleanly when switching chats.
You must log in or register to comment.
