Back to Snippets

Stream AI Response with Fetch JS

A reply that appears as the server sends it, the way chat apps show a model's answer. Press Send and the text streams in with a cursor at its end, including a code block that fills in word by word. Send turns into Stop while the reply is running. The Server menu switches the fake server between a normal stream, a 500 error and a connection that drops partway through, so you can see how each one is handled.

The client reads res.body through a TextDecoderStream with getReader. Chunks do not line up with events, so the code keeps a buffer, splits it on the blank line between server-sent events (lines may end in LF, CRLF or CR), keeps the unfinished tail for the next chunk and reads the data lines of each event. [DONE] ends the stream, and events with no text field are skipped. An AbortController stops the request, and rendering is batched with requestAnimationFrame so a fast stream is not redrawn for every chunk.

fakeFetch builds a real Response around a ReadableStream that cuts the bytes at random points, so the parser meets the same split events a network would give it. Replace it with fetch to your own server route, keep the API key on the server, and change the JSON field the handler reads to match your API. The reply is built from text nodes with textContent and append(), so text from the model is never parsed as HTML.

0
#javascript
#css
#ai
#streaming
#fetch
#readablestream
#server-sent events
#chatbot