folkwaysDocs
Developer guides

How to resume an AI response stream after a page reload

Decouple AI generation from the browser connection and rebuild a response from ordered chunks after a reload or network interruption.

To resume an AI response after a page reload, run generation independently of the browser request, publish ordered output chunks to a response-specific stream and reconstruct the UI from retained events or a durable snapshot. Reconnecting the browser must not start the model generation again.

Separate generation from delivery

A direct HTTP response ties delivery to the request lifecycle. A server-side job can instead continue generating while the browser is offline. Give each response an identifier, publish chunks to its own Stream topic and publish a terminal event on successful completion or failure. Keep job ownership and status in your backend.

Authorize subscription to that response on the server. Never let the browser choose unrestricted topic permissions. Do not expose model-provider credentials or signing keys to the client.

Rebuild a response from retained chunks

The example uses a Stream topic ai/response-42 with chunk and done events. Configure the rule and token endpoint using the quick start, and have your authorized worker publish { text } chunks and a done event. The client intentionally uses an in-memory SDK store so a fresh page can replay from oldest and reconstruct its output.

Browser example · render into <pre id="answer">``</pre> and an element with id="status"

import { Folkways } from '@folkwaysio/realtime';

const client = await Folkways.connect({
  url: 'https://rte.example.com',
  authUrl: '/api/realtime-token',
});

const answer = document.querySelector('#answer')!;
const status = document.querySelector('#status')!;
const chunks = new Map<string, string>();
type Events = { chunk: { text: string }; done: Record<string, never> };

const sub = client.topic<Events>('ai/response-42').subscribe((msg) => {
  if (msg.name === 'chunk') {
    chunks.set(msg.id, msg.data.text);
    answer.textContent = [...chunks.values()].join('');
  }
  if (msg.name === 'done') status.textContent = 'Complete';
}, { from: 'oldest', onGap: 'fail' });
sub.on('gap', () => {
  status.textContent = 'History expired; reload the saved response.';
});
await sub.ready;

Choose a recovery strategy

Replaying from oldest works only while the complete response remains retained. For long responses or long absences, save the assembled response and a corresponding checkpoint in your database. Load that snapshot before resuming incremental events.

If you opt in to persistent SDK cursors, do not append only the missed suffix to an empty UI after reload. Restore the saved prefix or rebuild from a complete history.

Make generation independent of reconnects

Use one durable job ID per generation request and an idempotent start endpoint. A reload should subscribe to the existing job rather than launch another one. Persist the final answer and terminal status independently of messaging retention. Group small model tokens into chunks when appropriate to reduce publication overhead.

Validate failure cases

Disconnect during generation, reload before completion and open a second authorized browser. Check that the job continues once, the assembled output matches the saved result, and terminal status survives. Test authorization failures and expired history. Folkways transports the response; it does not run the model or guarantee that your generation job survives a backend failure.

Create a free workspace and follow the quick start to try this pattern.

On this page