Last updated: 4 December 2026
To stream an LLM's answer into a page without a framework, have your server send one JSON object per line (NDJSON) and read response.body in the browser. Decode it with TextDecoder in streaming mode, split on newlines, and keep the last, possibly incomplete, line for the next chunk. That's about 20 lines of code. The harder part is everything around it: what the user sees while waiting, when the stream stalls, when it breaks halfway, when they press Stop, and when they've asked too many times. This post covers the server, the parser and all eight UI states, with code I tested against each case.
Why NDJSON, not SSE or plain text
- Server-Sent Events (
EventSource) only make GET requests and can't send a JSON body. A chat needs POST, so you end up usingfetchanyway. - Plain text works until something fails. Once the server has sent a
200and the first words, it can't change the status code. Plain text has no way to say "this broke halfway". - NDJSON gives every line a type. The browser reads events, not just text, and you can still watch the raw stream with
curl -N.
The whole contract is three event types:
| Event | Example line | Meaning |
|---|---|---|
delta | {"type":"delta","text":"Hello"} | More text to append |
done | {"type":"done"} | The answer finished normally |
error | {"type":"error","message":"The answer stopped early."} | It failed after streaming started |
The server: a Vercel Function
This runs on Vercel's default Node.js runtime. It uses only the web-standard Request, Response and ReadableStream, so it also works on the Edge runtime and other platforms. The example uses Anthropic's SDK; any provider that streams works the same way.
// api/chat.js
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic(); // reads ANTHROPIC_API_KEY from the environment
const encoder = new TextEncoder();
const line = (event) => encoder.encode(JSON.stringify(event) + '\n');
export async function POST(request) {
const { message } = await request.json().catch(() => ({}));
if (typeof message !== 'string' || !message.trim() || message.length > 2000) {
return new Response('Bad request', { status: 400 });
}
// Check your rate limit here, BEFORE streaming starts:
// return new Response('Too many requests', { status: 429, headers: { 'Retry-After': '30' } });
const upstream = new AbortController();
const body = new ReadableStream({
async start(controller) {
try {
const events = await client.messages.create(
{
model: 'claude-sonnet-5-5',
max_tokens: 1024,
messages: [{ role: 'user', content: message }],
stream: true,
},
{ signal: upstream.signal },
);
for await (const event of events) {
if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') {
controller.enqueue(line({ type: 'delta', text: event.delta.text }));
}
}
controller.enqueue(line({ type: 'done' }));
controller.close();
} catch (err) {
if (upstream.signal.aborted) return; // the reader went away; nothing to send
console.error(err);
controller.enqueue(line({ type: 'error', message: 'The answer stopped early.' }));
controller.close();
}
},
cancel() {
upstream.abort(); // tab closed or Stop pressed: stop paying for tokens
},
});
return new Response(body, {
headers: {
'Content-Type': 'application/x-ndjson; charset=utf-8',
'Cache-Control': 'no-store',
},
});
}Three decisions in there matter more than the rest:
- Check limits before the first byte. A
429or400is only possible before streaming starts. After that, failures must beerrorevents. cancel()aborts the upstream request. When the user presses Stop or closes the tab, the model stops generating, and you stop paying for tokens nobody will read.- The user sees a plain message, the logs get the details. Never stream raw provider errors to the browser.
Reading the stream without breaking text
// ndjson.js
export async function* readNDJSON(body) {
const reader = body.getReader();
const decoder = new TextDecoder();
let buffer = '';
try {
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true }); // keeps split multi-byte chars (₹, हिंदी) intact
const lines = buffer.split('\n');
buffer = lines.pop(); // the last piece may be an incomplete line
for (const line of lines) {
if (line.trim()) yield JSON.parse(line);
}
}
buffer += decoder.decode();
if (buffer.trim()) yield JSON.parse(buffer);
} finally {
reader.releaseLock();
}
}This avoids two bugs that only appear on real networks:
- A JSON line split across two chunks. The network decides chunk sizes, not your server. Parsing each chunk as if it held whole lines throws a
SyntaxErrorat random. Keeping the last piece inbufferfixes it. - A character split across two chunks.
₹is three bytes in UTF-8, and Devanagari letters are three bytes each. In my test I cut the stream in the middle of a₹. Decoding each chunk separately produced�replacement characters.decode(value, { stream: true })holds back the incomplete bytes until the next chunk, and the text came through intact.
The eight states nobody designs
Most streaming demos design two states: empty and streaming. Real users see all of these:
| State | When | What the user sees |
|---|---|---|
idle | Before the first question | Empty answer area, input ready |
waiting | Request sent, no text yet | "Thinking…" and a Stop button |
streaming | Text arriving | The answer growing, with a caret at the end |
stalled | No new text for 8 seconds | "Still working… this is taking longer than usual." |
done | done event received | Full answer; Stop button hidden |
error | Failed before any text | "Something went wrong. Please try again." |
error (partial) | Failed after some text | The partial answer kept, with "The answer stopped early. What you see above is incomplete." |
cancelled | User pressed Stop | Partial answer kept, marked "Stopped. The answer above is incomplete." |
rate-limited | Server returned 429 | "Too many questions right now. Try again in 20 seconds." (from Retry-After) |
The partial-answer states matter most in anything financial or factual. An answer that stops mid-sentence and looks complete is worse than an error message.
The controller
// answer.js
import { readNDJSON } from './ndjson.js';
const STALL_MS = 8000;
export function createStreamingAnswer({ output, status, stopButton, endpoint = '/api/chat' }) {
let controller = null;
function setState(state, message = '') {
output.dataset.state = state;
output.setAttribute('aria-busy', String(['waiting', 'streaming', 'stalled'].includes(state)));
status.textContent = message;
}
async function ask(message) {
controller?.abort();
controller = new AbortController();
const { signal } = controller;
output.textContent = '';
setState('waiting', 'Thinking…');
stopButton.hidden = false;
let pending = '';
let frame = 0;
let stallTimer = 0;
const flush = () => { output.append(pending); pending = ''; frame = 0; };
const resetStall = () => {
clearTimeout(stallTimer);
stallTimer = setTimeout(
() => setState('stalled', 'Still working… this is taking longer than usual.'),
STALL_MS,
);
};
try {
resetStall();
const res = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message }),
signal,
});
if (res.status === 429) {
const wait = Number(res.headers.get('Retry-After')) || 30;
setState('rate-limited', `Too many questions right now. Try again in ${wait} seconds.`);
return;
}
if (!res.ok || !res.body) throw new Error(`HTTP ${res.status}`);
for await (const event of readNDJSON(res.body)) {
resetStall();
if (event.type === 'delta') {
if (output.dataset.state !== 'streaming') setState('streaming', '');
pending += event.text;
frame ||= requestAnimationFrame(flush); // batch DOM writes to one per frame
} else if (event.type === 'error') {
throw new Error(event.message);
} else if (event.type === 'done') {
break;
}
}
if (frame) { cancelAnimationFrame(frame); flush(); }
setState('done', 'Answer complete.');
} catch (err) {
if (frame) { cancelAnimationFrame(frame); flush(); }
if (signal.aborted) {
setState('cancelled', 'Stopped. The answer above is incomplete.');
} else if (output.textContent) {
setState('error', 'The answer stopped early. What you see above is incomplete.');
} else {
setState('error', 'Something went wrong. Please try again.');
}
} finally {
clearTimeout(stallTimer);
stopButton.hidden = true;
}
}
stopButton.addEventListener('click', () => controller?.abort());
return { ask };
}Two details worth copying:
- Batch DOM writes. Tokens can arrive faster than the screen refreshes. Collecting them in
pendingand writing once per animation frame keeps long answers smooth on mid-range Android phones. append(), neverinnerHTML. Model output is untrusted text. Appending it as text means nothing in the answer can run as HTML. Rendering Markdown safely is the subject of my next post in this series.
The markup and styles
<form id="ask">
<label for="q">Ask about my work</label>
<input id="q" name="q" required maxlength="2000">
<button>Ask</button>
<button type="button" id="stop" hidden>Stop</button>
</form>
<p id="status" role="status"></p>
<div id="answer" data-state="idle" aria-busy="false"></div>
<script type="module">
import { createStreamingAnswer } from './answer.js';
const ui = createStreamingAnswer({
output: document.querySelector('#answer'),
status: document.querySelector('#status'),
stopButton: document.querySelector('#stop'),
});
document.querySelector('#ask').addEventListener('submit', (e) => {
e.preventDefault();
ui.ask(new FormData(e.target).get('q'));
});
</script>#answer { white-space: pre-wrap; }
#answer[data-state="streaming"]::after {
content: '▍';
animation: blink 1s steps(1) infinite;
}
@keyframes blink { 50% { opacity: 0; } }
#answer[data-state="error"],
#answer[data-state="cancelled"] {
border-left: 3px solid #d97706;
padding-left: 0.75rem;
}
@media (prefers-reduced-motion: reduce) {
#answer::after { animation: none; }
}Accessibility
- Don't make the answer a live region. A screen reader would try to read every few words as they arrive. Instead,
aria-busy="true"marks the answer as updating while it streams. - Announce changes through one
role="status"element. It says "Thinking…", "Answer complete." or the error, once each. The user can then read the finished answer at their own pace. - Keep focus in the input so the next question is one keystroke away. Make sure Stop is reachable by keyboard.
How I tested it
Network chunking is random, so I didn't trust a few manual runs. I fed the parser and controller simulated streams in Node and checked each case:
| Case | Result |
|---|---|
JSON lines and a ₹ split across chunks | Text intact: ₹1,23,456 हिंदी |
error event after two deltas | Partial text kept, marked incomplete |
| Network drops mid-stream | Partial text kept, marked incomplete |
429 with Retry-After: 20 | "Try again in 20 seconds" |
500 before streaming | "Something went wrong" |
| User presses Stop | State cancelled, partial text kept |
| Tab closed (stream cancelled) | Upstream model request aborted |
To watch the raw stream from your terminal:
curl -N -X POST https://mayurkashyap.com/api/chat \
-H 'Content-Type: application/json' \
-d '{"message":"What do you build?"}'-N turns off curl's buffering, so you see each line as it arrives.
What state did I miss? Tell me in the comments.

