Skip to content
AI Skills Central

Type to search Agent Skills, workflows, tutorials, tools and the glossary.

Tutorial

Stream LLM responses to a web page with server-sent events

A Node server relays tokens as server-sent events, the page renders them as they arrive, and a Stop button cancels.

By Intermediate45 min hands-on
Bookmark

Bookmarks are kept in your free account, so you can find this page again on any device.

Sign in to bookmark
Quiz at the end
On this page

A model that takes eight seconds to write an answer feels broken if the page stays blank for eight seconds, and fast if the first words appear after a tenth of a second. This tutorial builds the plumbing that makes the difference: a small Node.js server that relays a model’s output to the browser as server-sent events (SSE), a page that renders each piece as it arrives, and a Stop button whose cancellation travels all the way back to the model so it stops generating. You will understand the SSE wire format, why the page uses fetch rather than EventSource, and where streams get stuck in production.

The build uses no npm packages and no API key until the last step. A stub model stands in first, so you can see the mechanics in isolation; then the same server streams from a local model through Ollama, and finally, optionally, from the Claude API. It was written and run against Node.js 22.23.4, Ollama 0.40.17 with llama3.2:3b, and @anthropic-ai/sdk 1.12.0, all checked on 21 November 2026. The time the reader waits for the first words has a name, time to first token; streaming is how you show it off.

Three hops, three formats

A streamed answer crosses three boundaries, and each has its own framing. Keeping them apart is most of the work.

Hop Format Who parses it
Model to your server Ollama: newline-delimited JSON. Claude API: server-sent events Your server, or the provider’s SDK
Your server to the browser Server-sent events: event: and data: lines, a blank line after each event The page’s JavaScript
Script to the screen Plain text appended to an element The browser

Your server translates the first format into the second, so the page never needs to know which model is behind it. That is why the stub, Ollama and Claude can be swapped with one environment variable.

1. Set up the project

Make a folder and check your Node version. Node 22 has fetch, web streams and AbortController built in, so nothing needs installing yet.

mkdir stream-demo && cd stream-demo
node --version
v22.23.4

2. Write a server that streams from a stub model

Save this as server.mjs:

import { createServer } from "node:http";
import { readFile } from "node:fs/promises";

const PORT = 3000;
const BACKEND = process.env.BACKEND ?? "stub";

// A fake model: yields a canned answer word by word, so you can build the
// whole pipeline with no API key and no GPU.
async function* stubModel(prompt, signal) {
  const answer =
    `You asked: "${prompt}". Streaming sends each piece of the answer ` +
    "as soon as the model produces it, so the reader starts reading after " +
    "the first token instead of waiting for the last one.";
  for (const word of answer.split(" ")) {
    if (signal.aborted) return;
    await new Promise((r) => setTimeout(r, 80));
    yield word + " ";
  }
}

const backends = { stub: stubModel };
const model = backends[BACKEND];
if (!model) throw new Error(`Unknown BACKEND "${BACKEND}"`);

// One server-sent event: a name, a JSON payload, then a blank line.
function sse(res, event, data) {
  res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
}

async function handleChat(req, res) {
  let body = "";
  for await (const chunk of req) body += chunk;
  const { prompt } = JSON.parse(body);

  res.writeHead(200, {
    "Content-Type": "text/event-stream",
    "Cache-Control": "no-cache",
    "X-Accel-Buffering": "no", // ask nginx not to buffer this response
  });

  // When the browser disconnects (Stop button, closed tab), cancel upstream.
  const upstream = new AbortController();
  res.on("close", () => {
    if (!res.writableFinished) {
      upstream.abort();
      console.log("client went away: generation cancelled");
    }
  });

  let chunks = 0;
  try {
    for await (const text of model(prompt, upstream.signal)) {
      chunks++;
      sse(res, "token", { text });
    }
    if (!upstream.signal.aborted) sse(res, "done", { chunks });
  } catch (err) {
    if (!upstream.signal.aborted) sse(res, "error", { message: err.message });
  } finally {
    console.log(`sent ${chunks} chunks`);
    res.end();
  }
}

createServer(async (req, res) => {
  if (req.method === "POST" && req.url === "/api/chat") return handleChat(req, res);
  if (req.method === "GET" && req.url === "/") {
    res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
    return res.end(await readFile(new URL("./index.html", import.meta.url)));
  }
  res.writeHead(404).end();
}).listen(PORT, () => console.log(`http://localhost:${PORT} (backend: ${BACKEND})`));

Three decisions here carry the rest of the tutorial:

  • The model is an async generator. stubModel yields one piece of text at a time with an 80 ms pause, which is roughly how a real model’s output arrives. Every backend you add later has the same shape, (prompt, signal) => pieces of text, so handleChat never changes.
  • Each piece goes out as one SSE event. The format is plain text: an event: line naming the event, a data: line with the payload, and a blank line to end it. Encoding the payload as JSON keeps newlines and quotes in the model’s text from breaking the framing. The done and error events tell the page how the stream ended, because a closed connection alone does not say whether the answer was complete.
  • Cancellation starts at res.on("close"). When the browser goes away before the response finishes, the handler aborts an AbortController whose signal the model receives. The stub checks signal.aborted between words; a real backend passes the signal to its HTTP request.

The Cache-Control: no-cache and X-Accel-Buffering: no headers matter once there is a proxy between you and the browser; the pitfalls cover them.

3. Watch the stream with curl

Start the server in one terminal:

node server.mjs

In a second terminal, send a prompt. -N turns off curl’s output buffering so you see events as they arrive:

curl -sN -X POST http://localhost:3000/api/chat \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Why stream?"}'
event: token
data: {"text":"You "}

event: token
data: {"text":"asked: "}

event: token
data: {"text":"\"Why "}

...

event: token
data: {"text":"one. "}

event: done
data: {"chunks":34}

The words appear one by one over about three seconds, not all at once at the end. Now hang up early: --max-time 1 makes curl disconnect after one second, the way a closed browser tab would.

curl -sN --max-time 1 -X POST http://localhost:3000/api/chat \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Stop me"}'

The server’s terminal shows both requests:

http://localhost:3000 (backend: stub)
sent 34 chunks
client went away: generation cancelled
sent 13 chunks

The second request stopped after 13 of its 34 chunks. Proving cancellation with curl before you build the page means that when the Stop button misbehaves later, you know which side to look at.

4. Render the stream in a page

Save this as index.html next to server.mjs. The server already serves it at /.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Streaming demo</title>
  <style>
    body { font: 16px/1.5 system-ui, sans-serif; max-width: 40rem; margin: 2rem auto; }
    #output { white-space: pre-wrap; min-height: 6rem; border: 1px solid #ccc; padding: 1rem; }
  </style>
</head>
<body>
  <form id="ask">
    <label for="prompt">Prompt</label>
    <input id="prompt" value="Explain streaming in two sentences." size="40">
    <button id="send">Send</button>
    <button id="stop" type="button" disabled>Stop</button>
  </form>
  <div id="output" aria-live="polite"></div>
  <p id="status"></p>

  <script type="module">
    const form = document.querySelector("#ask");
    const output = document.querySelector("#output");
    const status = document.querySelector("#status");
    const send = document.querySelector("#send");
    const stop = document.querySelector("#stop");
    let controller = null;

    // Parse a block of SSE text ("event: x\ndata: {...}") into { event, data }.
    function parseEvent(block) {
      let event = "message";
      let data = "";
      for (const line of block.split("\n")) {
        if (line.startsWith("event:")) event = line.slice(6).trim();
        else if (line.startsWith("data:")) data += line.slice(5).trim();
      }
      return { event, data: data ? JSON.parse(data) : null };
    }

    async function stream(prompt) {
      controller = new AbortController();
      const res = await fetch("/api/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ prompt }),
        signal: controller.signal,
      });
      const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
      let buffer = "";
      while (true) {
        const { value, done } = await reader.read();
        if (done) break;
        buffer += value;
        const blocks = buffer.split("\n\n");
        buffer = blocks.pop(); // the last block may be incomplete
        for (const block of blocks) {
          const { event, data } = parseEvent(block);
          if (event === "token") output.append(data.text); // text, never HTML
          if (event === "done") status.textContent = `Done: ${data.chunks} chunks.`;
          if (event === "error") status.textContent = `Error: ${data.message}`;
        }
      }
    }

    form.addEventListener("submit", async (e) => {
      e.preventDefault();
      output.textContent = "";
      status.textContent = "Streaming...";
      send.disabled = true;
      stop.disabled = false;
      try {
        await stream(document.querySelector("#prompt").value);
      } catch (err) {
        status.textContent = err.name === "AbortError" ? "Stopped." : `Error: ${err.message}`;
      } finally {
        send.disabled = false;
        stop.disabled = true;
      }
    });

    stop.addEventListener("click", () => controller?.abort());
  </script>
</body>
</html>

The server reads the file on every request, so there is no need to restart it. Open http://localhost:3000 and press Send. The answer appears word by word. In our run, measured with a headless Chromium, the first words were on screen about 90 ms after the click, and the whole stub answer took about three seconds. Press Send again and then Stop partway through: the text stops, the status reads “Stopped.” and the server logs client went away: generation cancelled.

What the page is doing, and why:

  • fetch instead of EventSource. The browser’s built-in EventSource only opens GET requests, and its constructor takes a URL and one option, withCredentials. There is no way to send the prompt as a POST body or add an Authorization header, and it reconnects on its own when the connection drops, which for a chat answer means asking the model again. Reading the fetch response body yourself costs about fifteen lines of parsing and gives you POST, headers and an AbortController.
  • Buffer until a blank line. Network chunks do not line up with events. One read() can hold half an event or three of them. The loop adds each chunk to buffer, splits on the blank line that ends an event, and keeps the last, possibly incomplete, piece for the next read. Skip this and you get intermittent JSON.parse errors that never show up on localhost.
  • Append text, never HTML. output.append(data.text) adds a text node, so whatever the model writes, including markup it was tricked into producing, is shown as characters. If you want Markdown, re-render the whole accumulated text through a sanitising renderer on each update rather than inserting fragments as HTML.
  • aria-live="polite" lets screen readers announce new text without interrupting what they are reading.
  • One controller per request. The Stop button calls controller.abort(). The pending fetch or read() rejects with an AbortError, which the page reports as “Stopped.” rather than as an error, and the browser closes the connection, which fires res.on("close") on the server.

5. Stream from a local model with Ollama

Replace the stub with a real model. With Ollama installed and running (see Run local models with Ollama), pull a small model:

ollama pull llama3.2:3b

In server.mjs, add this function just above the const backends line:

// A real local model: Ollama streams newline-delimited JSON objects.
const OLLAMA_MODEL = process.env.OLLAMA_MODEL ?? "llama3.2:3b";

async function* ollamaModel(prompt, signal) {
  const res = await fetch("http://localhost:11434/api/chat", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      model: OLLAMA_MODEL,
      stream: true,
      messages: [{ role: "user", content: prompt }],
    }),
    signal, // aborting this closes the connection, and Ollama stops generating
  });
  if (!res.ok) throw new Error(`Ollama returned ${res.status}: ${await res.text()}`);

  const decoder = new TextDecoder();
  let buffer = "";
  for await (const bytes of res.body) {
    buffer += decoder.decode(bytes, { stream: true });
    const lines = buffer.split("\n");
    buffer = lines.pop(); // keep the incomplete last line for the next read
    for (const line of lines) {
      if (!line.trim()) continue;
      const event = JSON.parse(line);
      if (event.message?.content) yield event.message.content;
    }
  }
}

Then register it, replacing the const backends line:

const backends = { stub: stubModel, ollama: ollamaModel };

Restart the server with the Ollama backend:

BACKEND=ollama node server.mjs

The curl command from step 3 now returns the model’s own words (yours will differ):

event: token
data: {"text":"Hello"}

event: token
data: {"text":","}

event: token
data: {"text":" I"}

...

event: done
data: {"chunks":8}

Ollama’s streaming format is not SSE. Its docs describe the response as application/x-ndjson: one JSON object per line, each with a message.content fragment and done: true on the last. ollamaModel uses the same buffer-and-split technique as the page, splitting on single newlines instead of blank lines, which is the general rule for any streamed format: never assume a network chunk is a whole message.

The measurement that shows why streaming matters, from three runs of the page’s prompt on a four-core CPU:

first bytes after 3.47s, finished after 5.86s
first bytes after 0.10s, finished after 2.88s
first bytes after 0.09s, finished after 2.51s

The first run includes loading the model into memory. After that, text started arriving after about a tenth of a second, while the full answer took two and a half to three seconds. Without streaming the reader would stare at a blank box for the whole time.

Now press Stop partway through an answer in the page. Our server logged sent 44 chunks for the stopped answer against 81 for a complete one, and Ollama’s own log showed the request ending after 1.6 seconds with stop: cancel task. Passing signal to fetch is what does this: aborting closes the connection to Ollama, and Ollama stops generating. Without it, the browser would stop showing text while the model kept running to the end, using CPU or, on a hosted API, output tokens you pay for.

6. Optional: stream from the Claude API

The Claude API streams server-sent events too, with named events such as message_start, content_block_delta, ping and message_stop. The official SDK parses them, so the backend only picks out text deltas. Install the SDK, pinned:

npm init -y
npm install @anthropic-ai/sdk@1.12.0

Add this function above the const backends line:

// A hosted model: the Claude API streams server-sent events, and the SDK parses them.
async function* claudeModel(prompt, signal) {
  const { default: Anthropic } = await import("@anthropic-ai/sdk");
  const client = new Anthropic(); // reads ANTHROPIC_API_KEY from the environment
  const stream = client.messages.stream(
    {
      model: "claude-haiku-5-5",
      max_tokens: 1024,
      messages: [{ role: "user", content: prompt }],
    },
    { signal }, // aborting closes the connection to the API
  );
  for await (const event of stream) {
    if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
      yield event.delta.text;
    }
  }
}

Register it:

const backends = { stub: stubModel, ollama: ollamaModel, claude: claudeModel };

Run it with your key in the environment, never in the file:

export ANTHROPIC_API_KEY=your-key-here
BACKEND=claude node server.mjs

claude-haiku-5-5 is the fastest and cheapest model on Anthropic’s models page on the day of writing, which suits a demo. The { signal } request option does for the API what it did for Ollama: Stop closes the connection, so the model stops producing output tokens you would be billed for. If the key is missing, the page shows the SDK’s error, because the server turns it into an error event:

event: error
data: {"message":"Could not resolve authentication method. Expected one of apiKey, authToken, credentials, config, or profile to be set. Or for the \"Authorization\" header to be explicitly omitted"}

That is the general rule for errors in a stream: by the time anything fails, the 200 status and headers have already gone, so the only way to tell the page is an event in the stream itself.

Taking it to production

The local build hides three problems that appear as soon as the server sits behind real infrastructure:

  • Buffering proxies and compression. A reverse proxy or compression layer that waits to fill a buffer turns your stream back into one late response. nginx honours the X-Accel-Buffering: no response header the server sends (unless configured to ignore it); for other proxies and CDNs, check their docs for how to turn off response buffering on this route.
  • The six-connection limit. MDN notes that over HTTP/1.1 a browser allows only six open SSE connections per domain, shared across tabs. Serve the app over HTTP/2, and close streams you no longer need.
  • Partial answers. A stream can stop at any point. Store what was sent along with how it ended (done, error or cancelled), so a retry or a log does not treat half an answer as a whole one.

Pitfalls

Parsing each network chunk as one event. On localhost, chunks often happen to line up with events, so the code works until it meets a real network. Buffer and split on the blank line that ends an SSE event (or the newline that ends an NDJSON line), and keep the remainder.

Using EventSource for a chat endpoint. It can only make GET requests without a body or custom headers, and it reconnects on its own, which re-runs the prompt. Use fetch with a streamed body for anything that sends a prompt.

Stopping the display but not the model. Aborting in the browser without passing the signal on to the model request leaves the model generating to the end. Check the server log, or the provider’s usage, after pressing Stop.

Inserting model output as HTML. Appending fragments with innerHTML lets markup in the model’s output run in your page. Append text nodes, or sanitise the whole accumulated text on each render.

Reporting errors with a status code mid-stream. Once the first event is sent, the status is already 200. Send an error event and have the page show it, as handleChat does.

Testing without -N. Without it, curl may buffer output and print the events in a burst at the end, which looks like the server is not streaming.

Next steps

Covers

Tools

Check your understanding

Stream LLM responses to a web page quiz

The SSE wire format, cancellation with AbortController, fetch versus EventSource, buffering partial chunks, safe rendering, and streams in production.

8 questions · pass mark 70%

Question 1 of 80 answered
  1. In the server, what marks the end of one server-sent event on the wire?
  • Run local models with Ollama

    Install Ollama, run an open-weight model on your own machine, call it from scripts over the local API and choose a model size your hardware can handle, offline.

    TutorialBeginner30 min

  • Time to first token

    How long a model takes to return the first token of a response after a request, the main driver of how fast a streamed reply feels.

    Glossary

  • Build your first agent in TypeScript

    Tools that search and read notes, a step limit, a clear stop condition and logged steps.

    TutorialIntermediate1 h

  • Latency

    The time from sending a request to a model to getting the response, often split into time to first token and total generation time.

    Glossary

  • Controlling LLM costs without hurting quality

    Where LLM spend actually goes (context, retries, agent loops, output) and the levers that cut it without hurting quality: caching, routing, batching, budgets.

    Article

Back to top