Keeping chat history across reloads with Vercel AI SDK
Save a Jekyll release summary conversation by chat ID, restore it after reload, and decide when to keep an interrupted response.
Save a Jekyll 4.4.0 release-note conversation by chat ID, then reload the same URL to restore the original input and answer. I also stopped a follow-up response and checked what came back on the next reload.
I used Node.js 22.23.3, Next.js 16.4.6,
ai7.0.185, and@ai-sdk/react4.0.190. The Chrome test ran locally withMockLanguageModelV4responses and a temporary JSON file for the conversation store. AI SDK testing guide
Give the conversation a durable identity
In the streaming release-note summary, a new request cleared the previous result and sent just the latest input. That matched a form where every submission started a fresh summary. A follow-up like “summarize it again in one line” needs the first release note and the assistant’s previous answer.
I gave the conversation a stable chat ID and used that ID to name its saved history. A fresh Chat reads the same record and receives those messages as its initial state. Individual messages also need stable IDs. The client can keep the ID it already created for a user message. The server can supply the assistant’s ID through generateMessageId, so the streamed and saved copies of that message share an identity. Keeping these IDs also gives the UI a stable target if a future version lets users edit or regenerate a particular message. Chat and message IDs
Load the saved UI messages before generating
I store UIMessage[], which holds each message’s role, ID, and parts. These fields let the client render its history after a load. The assistant’s first part in the test was a step-start marker. As in the streaming example, I joined the text parts to compare the actual summary. Saving the complete message gives the next screen the same structure.
The client submits the chat ID and the latest user message. The server loads the existing history, appends that message, and checks the combined array with safeValidateUIMessages. It then uses convertToModelMessages for the model call. It also passes the combined UI messages to toUIMessageStream as originalMessages. That gives the stream adapter the original conversation and the new turn, so the completion callback can return the whole history plus the new assistant message. Validate and store UI messages
When the page opens, the server component reads the saved messages for the ID in the URL. The client uses that same ID and passes the saved list to useChat as its initial messages.
1
2
3
// app/history/[id]/page.jsx — after checking the chat ID
const messages = await loadChat(id);
return <HistoryChat key={id} id={id} initialMessages={messages} />;
1
2
3
4
5
6
// app/history/[id]/history-chat.jsx — inside HistoryChat
const { messages, sendMessage, status, stop } = useChat({
id,
messages: initialMessages,
transport,
});
Save the turn when the answer completes
I chose to save a user request and its completed answer as one turn. The client still displays text fragments while the response is streaming. On the server, the standalone toUIMessageStream helper calls onEnd. My fixture checks for a completed outcome and a finish reason of stop before writing the history file. I used both checks because the callback can also run after an abort. Save messages when a stream ends
1
2
3
4
5
6
7
8
9
10
11
12
13
// app/api/chat/route.js — after starting the model call
return createUIMessageStreamResponse({
stream: toUIMessageStream({
stream: result.stream,
originalMessages,
generateMessageId: randomUUID,
async onEnd({ messages, outcome, finishReason }) {
if (outcome.status === 'completed' && finishReason === 'stop') {
await saveChat(id, messages);
}
},
}),
});
| Event | What the test store returns |
|---|---|
| First summary finishes | The release note and completed assistant response |
| Follow-up is stopped after text arrives | The conversation through the last completed turn |
| A fresh chat loads the same ID | The saved user and assistant messages as its starting history |
This save policy fits the summary exercise. An app that should keep every question can store the user message at submission and attach the answer’s state separately. That design gives a retry screen an explicit question to work from and a way to show that its answer was interrupted.
Reload the same chat URL
I completed the Jekyll 4.4.0 summary in Chrome and reloaded the same URL. The page showed 불러온 메시지 2개 (two loaded messages) and displayed the release note and its answer. Both message IDs matched the saved records. The server read the file on reload, and the log showed one model call for the original summary.
For the follow-up request, the mock model received the user, assistant, and user messages in that order. I clicked 응답 중지 (Stop response) after the first fragment appeared. On that browser run, the server callback recorded isCancelled: true and outcome.status: 'unknown'. The completion check skipped the save. The next reload displayed the original two messages again.
Figure 1. After stopping the follow-up and reloading the URL, the browser displays the first completed turn.
Resume an active stream when the product needs it
This example restores the last saved view of a conversation. Reconnecting to an in-progress SSE stream calls for an active stream ID, a store for replayable events, and a route for the client to reconnect. With that setup, a client-side stop() may simply close the current connection. If users also need to cancel the generation, the backend should provide an explicit way to stop the active work. Resume streams in AI SDK UI
- On a shared service, check the server-authenticated user’s access to the chat before reading or writing its messages.
- If requests can overlap for one chat, choose how the store handles two attempts to update the same history. A revision check or transaction can protect a newer write.
- Test a reload after a completed answer and after an interrupted answer. Check the initial message state and the saved records for each case.