MSMuhammad Shahid

Engineering notes

Streaming LLM Responses in React with Server-Sent Events

By Muhammad Shahid · · 22 min read

Quick answer

To stream an LLM answer into React, have a Node.js endpoint respond with Content-Type: text/event-stream and write each text delta as a Server-Sent Event: event: delta, a JSON data: line and a blank line. In React, read the response with fetch and a stream reader, parse the events, append each delta to the message, and wire a Stop button to an AbortController that also aborts the model call on the server.

Key facts
StackExpress 5, React 19, Vite, TypeScript, @anthropic-ai/sdk
ProtocolServer-Sent Events (text/event-stream) over a POST response
Clientfetch + custom SSE parser + React hook, rendered once per frame
StopAbortController in React, stream.abort() in Express
CheckedType-checked; server, parser and React app run end to end, nginx 1.30 tested

This tutorial shows how to stream LLM responses in React with Server-Sent Events and Node.js: an Express endpoint that turns Claude's token stream into SSE, a parser that reads it from fetch, a React hook that renders it smoothly, and a Stop button that really stops the model. Every file is complete. The code was type-checked, and the server, the parser and the React app ran end to end in Chrome with a stand-in for the model's stream, so no API key was used; the proxy measurements below come from nginx 1.30 in Docker.

What are Server-Sent Events?

Server-Sent Events (SSE) is a web standard for a server to push a stream of text messages to the browser over one ordinary HTTP response. The response has the content type text/event-stream, stays open, and the server writes small blocks of text, each ending with a blank line. Browsers have a built-in client for it, EventSource, and any client that can read a streaming HTTP body can parse it too.

SSE is one-way: server to client. That is exactly the shape of an LLM answer. The user sends one request, then the model writes text for several seconds. Anthropic's own API streams its responses as Server-Sent Events, which is why the pattern fits so naturally.

Why stream LLM responses at all?

A long answer can take many seconds to generate. Without streaming, the user stares at a spinner for the whole time and then gets a wall of text. With streaming, the first words appear within a fraction of a second, people start reading while the model is still writing, and they can stop an answer that is going the wrong way. The total time is the same; the wait the user feels is much shorter, and that changes whether a chat feels responsive.

Streaming also lets you show progress and handle errors mid-answer, and a Stop button saves money: when the user stops, you can stop the model and stop paying for output tokens nobody reads.

Which should you choose: SSE, WebSockets or a plain fetch stream?

Server-Sent EventsWebSocketsRaw fetch stream (NDJSON)
DirectionServer to clientBoth waysServer to client
TransportPlain HTTP responseUpgraded TCP connectionPlain HTTP response
Message framingBuilt in: event, data, idBuilt in: framesYours to define, such as one JSON per line
Browser clientEventSource (GET only) or fetchWebSocketfetch
Works through proxies and CDNsUsually, with buffering and compression handledNeeds upgrade supportUsually, same caveats as SSE
Best forLLM answers, notifications, progressChat between users, games, collaborationSimple one-off streams

For an LLM chat, SSE is the usual choice: the request goes up once and the answer streams down. WebSockets add a second protocol and stateful connections you have to scale, for a two-way channel you do not need. A raw NDJSON stream works too (the RAG tutorial on this site uses one), but SSE gives you event names, IDs and a standard format that tools, proxies and other developers already understand.

One detail decides the client side: EventSource can only send a GET request with no body and no custom headers. A chat needs to send the conversation, so this tutorial posts it with fetch and parses the SSE body itself.

How does the SSE wire format work?

Anatomy of a Server-Sent Events message: an id line, an event line, a data line with JSON, a blank line that ends the message, and a comment line used as a heartbeat
Every SSE message is a few field lines followed by a blank line.

Each message is a set of field: value lines. data carries the payload, event names the message type (the default is message), and id sets the last event ID, which EventSource sends back in a Last-Event-ID header when it reconnects. A blank line ends the message, and a line that starts with a colon is a comment that parsers ignore. This is what the server in this tutorial actually sends:

id: 1
event: delta
data: {"text":"Server-Sent "}

id: 2
event: delta
data: {"text":"Events "}

: ping

id: 18
event: done
data: {"stopReason":"end_turn","usage":{"input":12,"output":17}}

Putting JSON on a single data: line keeps parsing simple: JSON.stringify never writes a raw line break, so one line per message is always enough, and the text inside can contain anything, including line breaks and emoji.

How the pieces fit together

Architecture: a React app posts to Express through a proxy; Express streams Claude text deltas back as Server-Sent Events; Stop aborts the fetch and the model call
One request goes up, one long response comes back. The proxy must not hold events back.

The React app posts the conversation to /api/chat. Express validates it, opens an SSE response and starts a streaming request to Claude. Each text delta from the model becomes one SSE message. In development Vite forwards /api to Express; in production nginx or another proxy does. The proxy's only job is to pass bytes on as they arrive, and the most common streaming bug is a proxy that does not.

What do you need before you start?

ToolVersion used hereWhy
Node.js20 or laterRuns Express and Vite
Express5The streaming endpoint
React + ViteReact 19, Vite 8The chat UI and the development proxy
@anthropic-ai/sdk1.xStreams the model answer
zod4Validates the request body
TypeScript7Types for the server and the client

You need an Anthropic API key to run it against the real model, and familiarity with React hooks and async iteration.

Step 1: Set up the project

mkdir sse-chat && cd sse-chat && npm init -y
npm install express@5 @anthropic-ai/sdk zod react react-dom
npm install -D typescript tsx vite @vitejs/plugin-react @types/express @types/node @types/react @types/react-dom

The finished project has a small server folder and a Vite client:

sse-chat/
  server/
    sse.ts                # SSE headers, heartbeat and event writer
    llm.ts                # Anthropic client
    app.ts                # POST /api/chat: validate, stream, abort
    index.ts              # starts Express on port 3001
  client/
    index.html
    vite.config.ts        # proxies /api to Express in development
    src/
      lib/parseSSE.ts     # text/event-stream parser for fetch bodies
      hooks/useChatStream.ts
      App.tsx
      main.tsx

Step 2: Write the SSE helper for Express

import type { Response } from "express";

// Turns an Express response into a Server-Sent Events stream.
export function openSSE(res: Response) {
  res.status(200);
  res.setHeader("Content-Type", "text/event-stream; charset=utf-8");
  res.setHeader("Cache-Control", "no-cache, no-transform");
  res.setHeader("Connection", "keep-alive");
  res.setHeader("X-Accel-Buffering", "no"); // ask nginx not to buffer this response
  res.flushHeaders();

  let id = 0;
  const open = () => !res.writableEnded && !res.destroyed;
  // A comment line every 15 seconds stops proxies from closing an idle connection.
  const heartbeat = setInterval(() => {
    if (open()) res.write(": ping\n\n");
  }, 15000);

  return {
    send(event: string, data: unknown) {
      if (!open()) return;
      id += 1;
      // JSON.stringify never emits a raw line break, so one data: line is enough.
      res.write("id: " + id + "\nevent: " + event + "\ndata: " + JSON.stringify(data) + "\n\n");
    },
    close() {
      clearInterval(heartbeat);
      if (open()) res.end();
    },
  };
}

This helper turns any Express response into an event stream. Content-Type: text/event-stream is what makes it SSE. Cache-Control: no-cache, no-transform stops caches from storing it and, just as important, tells compression middleware and proxies not to transform the body; the measurements later in this article show why that matters. X-Accel-Buffering: no asks nginx not to buffer this response, and flushHeaders() sends the headers at once so the browser knows the stream has started.

A comment line every 15 seconds keeps idle connections alive through load balancers that close quiet connections; during a long tool call or a slow first token there may be no text for a while. Each message gets an increasing id, and send does nothing once the response has closed, so a late delta can never throw.

Step 3: Stream the model's answer from an Express route

import Anthropic from "@anthropic-ai/sdk";

export const client = new Anthropic(); // reads ANTHROPIC_API_KEY
export const MODEL = "claude-opus-5-5";
import express from "express";
import Anthropic from "@anthropic-ai/sdk";
import { z } from "zod";
import { client, MODEL } from "./llm";
import { openSSE } from "./sse";

const Message = z.object({
  role: z.enum(["user", "assistant"]),
  content: z.string().min(1).max(8000),
});
const Body = z.object({
  messages: z
    .array(Message)
    .min(1)
    .max(40)
    .refine((m) => m[m.length - 1].role === "user", "The last message must come from the user."),
});

export const app = express();
app.use(express.json({ limit: "200kb" }));

app.post("/api/chat", async (req, res) => {
  const parsed = Body.safeParse(req.body);
  if (!parsed.success) {
    // Validation errors are plain JSON: the stream has not started yet.
    res.status(400).json({ error: parsed.error.issues[0]?.message ?? "Invalid request" });
    return;
  }

  const sse = openSSE(res);
  const stream = client.beta.messages.stream({
    model: MODEL,
    max_tokens: 16000,
    output_config: { effort: "low" },
    betas: ["server-side-fallback-2026-07-01"],
    fallbacks: "default",
    system: "You are a concise, friendly assistant. Use Markdown for lists and code.",
    messages: parsed.data.messages,
  });

  // The connection closed before the answer finished (Stop button, closed tab, network drop):
  // stop generating, and paying for, tokens.
  res.on("close", () => {
    if (!res.writableFinished) stream.abort();
  });

  try {
    for await (const event of stream) {
      if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
        sse.send("delta", { text: event.delta.text });
      }
    }
    const final = await stream.finalMessage();
    sse.send("done", {
      stopReason: final.stop_reason,
      usage: { input: final.usage.input_tokens, output: final.usage.output_tokens },
    });
  } catch (err) {
    if (!(err instanceof Anthropic.APIUserAbortError)) {
      console.error(err);
      sse.send("error", { message: "The answer could not be generated. Please try again." });
    }
  } finally {
    sse.close();
  }
});

The route validates the body before anything streams: up to 40 messages, each up to 8,000 characters, and the last one from the user. Validation errors return ordinary JSON with status 400, because once SSE headers are sent you can no longer change the status code.

Then it opens the stream and calls client.beta.messages.stream. Every text_delta becomes a delta event, and when the model finishes, a done event carries the stop reason and token usage. The model is claude-opus-5-5 at effort: "low", which suits fast chat replies, and server-side fallbacks are on (fallbacks: "default" with its beta flag), so a request the model declines can be retried on a fallback model inside the same call. If the model still refuses, the done event says so and the client shows a message. Errors after the stream has started go out as an error event, since the HTTP status is already 200.

The close listener is the part most tutorials skip. When the browser disconnects before the answer finished, res.writableFinished is false and the route calls stream.abort(), which ends the request to the model.

import { app } from "./app";

const port = Number(process.env.PORT ?? 3001);
app.listen(port, () => console.log("API listening on http://localhost:" + port));

Step 4: Parse the stream in the browser

export interface SSEMessage {
  event: string;
  data: string;
  id?: string;
}

// Reads a text/event-stream body and yields one message per block that ends in a blank line.
// Handles comments, multi-line data and messages split across network chunks.
export async function* parseSSE(body: ReadableStream<Uint8Array>): AsyncGenerator<SSEMessage> {
  const reader = body.getReader();
  const decoder = new TextDecoder(); // stream: true keeps multi-byte characters split across chunks intact
  let buffer = "";
  let event = "message";
  let data: string[] = [];
  let id: string | undefined;

  try {
    while (true) {
      const { value, done } = await reader.read();
      if (done) break;
      buffer += decoder.decode(value, { stream: true });
      const lines = buffer.split(/\r?\n/);
      buffer = lines.pop() ?? ""; // the last piece may be an incomplete line

      for (const line of lines) {
        if (line === "") {
          if (data.length) yield { event, data: data.join("\n"), id };
          event = "message";
          data = [];
          continue;
        }
        if (line.startsWith(":")) continue; // a comment, such as the heartbeat
        const colon = line.indexOf(":");
        const field = colon === -1 ? line : line.slice(0, colon);
        let value = colon === -1 ? "" : line.slice(colon + 1);
        if (value.startsWith(" ")) value = value.slice(1);
        if (field === "event") event = value;
        else if (field === "data") data.push(value);
        else if (field === "id") id = value;
      }
    }
  } finally {
    reader.releaseLock();
  }
}

Network chunks do not respect message boundaries: one chunk can hold half a line, or three messages. The parser keeps the unfinished end of the text in a buffer, splits complete lines, collects event, data and id fields, and yields a message at each blank line. TextDecoder with stream: true matters too: an emoji or an accented letter is several bytes, and without it a character split across two chunks turns into garbage. In testing, the parser got the same messages when the input was fed one byte at a time, with an emoji cut in half, comments and multi-line data. It handles the line endings servers actually send (LF and CRLF); a lone CR, which the standard also allows, is not handled.

Step 5: Build the useChatStream React hook

import { useCallback, useRef, useState } from "react";
import { parseSSE } from "../lib/parseSSE";

export type ChatMessage = { role: "user" | "assistant"; content: string };
type Status = "idle" | "streaming" | "error";

export function useChatStream(endpoint = "/api/chat") {
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [status, setStatus] = useState<Status>("idle");
  const [error, setError] = useState("");
  const controller = useRef<AbortController | null>(null);

  const send = useCallback(
    async (text: string) => {
      const history: ChatMessage[] = [...messages, { role: "user", content: text }];
      setMessages([...history, { role: "assistant", content: "" }]);
      setStatus("streaming");
      setError("");
      const ac = new AbortController();
      controller.current = ac;

      // Deltas can arrive faster than the screen repaints: collect them, render once per frame.
      let pending = "";
      let frame = 0;
      const flush = () => {
        frame = 0;
        const chunk = pending;
        pending = "";
        setMessages((prev) => {
          const next = prev.slice();
          const last = next[next.length - 1];
          next[next.length - 1] = { ...last, content: last.content + chunk };
          return next;
        });
      };

      try {
        const res = await fetch(endpoint, {
          method: "POST",
          headers: { "Content-Type": "application/json", Accept: "text/event-stream" },
          body: JSON.stringify({ messages: history }),
          signal: ac.signal,
        });
        if (!res.ok || !res.body) {
          const body = await res.json().catch(() => null);
          throw new Error(body?.error ?? "Request failed (" + res.status + ")");
        }
        for await (const msg of parseSSE(res.body)) {
          const payload = JSON.parse(msg.data);
          if (msg.event === "delta") {
            pending += payload.text;
            if (!frame) frame = requestAnimationFrame(flush);
          } else if (msg.event === "error") {
            throw new Error(payload.message);
          } else if (msg.event === "done" && payload.stopReason === "refusal") {
            throw new Error("The model declined to answer this request.");
          }
        }
        setStatus("idle");
      } catch (err) {
        if (ac.signal.aborted) {
          setStatus("idle"); // the user pressed Stop: keep what was written so far
        } else {
          setStatus("error");
          setError(err instanceof Error ? err.message : "Something went wrong");
        }
      } finally {
        if (frame) cancelAnimationFrame(frame);
        if (pending) flush();
        controller.current = null;
      }
    },
    [endpoint, messages],
  );

  const stop = useCallback(() => controller.current?.abort(), []);

  return { messages, status, error, send, stop };
}

The hook owns the conversation, the status and the error. send adds the user's message and an empty assistant message, posts the history, and appends each delta to that last message. Two details make it feel smooth:

  • One render per frame. A fast model can send dozens of deltas between screen refreshes. The hook collects them in a string and updates React state once per requestAnimationFrame, so the page re-renders at most once per frame however fast the text arrives.
  • Stop is not an error. Aborting a fetch makes it reject. The hook checks signal.aborted, keeps the text written so far and returns to idle instead of showing an error.

Step 6: Build the chat component

import { useState, type FormEvent } from "react";
import { useChatStream } from "./hooks/useChatStream";

export default function App() {
  const { messages, status, error, send, stop } = useChatStream();
  const [input, setInput] = useState("");
  const streaming = status === "streaming";

  function submit(e: FormEvent) {
    e.preventDefault();
    const text = input.trim();
    if (!text || streaming) return;
    setInput("");
    void send(text);
  }

  return (
    <main className="chat">
      <ol className="messages" aria-live="polite">
        {messages.map((m, i) => (
          <li key={i} className={m.role}>
            {m.content || (streaming && i === messages.length - 1 ? "..." : "")}
          </li>
        ))}
      </ol>
      {error && <p role="alert">{error}</p>}
      <form onSubmit={submit}>
        <label htmlFor="message">Message</label>
        <textarea id="message" value={input} onChange={(e) => setInput(e.target.value)} rows={2} />
        {streaming ? (
          <button type="button" onClick={stop}>
            Stop
          </button>
        ) : (
          <button disabled={!input.trim()}>Send</button>
        )}
      </form>
    </main>
  );
}

The component only renders state. The message list has aria-live="polite" so screen readers announce new text without interrupting, the textarea has a real label, and the Send button turns into Stop while an answer streams. The Vite config forwards /api to Express in development, so the browser sees one origin and no CORS setup is needed:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

// In development, Vite forwards /api to the Express server so the browser sees one origin.
export default defineConfig({
  plugins: [react()],
  server: { proxy: { "/api": "http://localhost:3001" } },
});

Step 7: Make Stop really stop

What Stop does: AbortController cancels the fetch, the browser closes the connection, Express sees the close event and calls stream.abort, and Claude stops generating
Stop has to reach the model, or you keep paying for an answer nobody reads.

Pressing Stop calls AbortController.abort(). The browser cancels the fetch and closes the connection. Express emits close on the response, sees the answer is not finished and calls stream.abort(), so Claude stops generating. Without that last step, the page would stop showing text while the server kept reading, and paying for, the rest of the answer. In the end-to-end test, pressing Stop after 0.7 seconds kept the partial text on the page, showed no error, and the server aborted the model stream; a stream that finished normally was not aborted.

How do you run and test it?

# terminal 1: the API
ANTHROPIC_API_KEY=your-key npx tsx server/index.ts

# terminal 2: the React app on http://localhost:5173
cd client && npx vite

# watch the raw stream
curl -N -X POST http://localhost:3001/api/chat -H "Content-Type: application/json" -d '{"messages":[{"role":"user","content":"Explain SSE in one paragraph"}]}'

curl -N turns off curl's own buffering, so you see each event the moment it is written. Then open the app, ask something long, and check four things: text appears within a second and keeps growing; Stop leaves the partial answer and no error; the server log shows the model call aborted after Stop; and sending an invalid body (for example a last message from the assistant) returns a 400 with a readable message.

For this article the same checks ran automatically. A stand-in stream replaced the model and wrote 17 words over 2.6 seconds. The first event reached the client after about 180 milliseconds, the parser passed its byte-by-byte tests, and a Chrome test through the Vite proxy confirmed that the text grew on screen, that Stop kept the partial answer, and that the server aborted the stream.

Deploying behind nginx and other proxies

Streams that work locally often arrive all at once in production. The cause is something between the server and the browser that waits for more data before passing it on: a buffering proxy, a CDN, or compression. This nginx block is a safe default for an SSE route:

location /api/ {
  proxy_pass http://127.0.0.1:3001;
  proxy_http_version 1.1;
  proxy_set_header Connection "";
  proxy_buffering off;      # pass each event on as soon as it arrives
  proxy_cache off;
  proxy_read_timeout 1h;    # long answers must not hit the 60-second default
}

Measured with nginx 1.30 in front of the stand-in stream (17 deltas over about 2.6 seconds); the two Express compression() rows used a shorter stand-in of 6 deltas over about 1.8 seconds:

SetupFirst event arrived afterResult
Express directlyabout 0.18 sStreams
nginx with the config aboveabout 0.18 sStreams
nginx default buffering, X-Accel-Buffering ignoredabout 0.17 sStreams in this test
nginx with gzip_types text/event-streamabout 2.6 sEverything arrives at the end
Express compression(), no no-transformabout 1.8 sEverything arrives at the end
Express compression() with no-transformabout 0.33 sStreams

Two lessons came out of this. First, in this test proxy buffering alone did not hold events back, but compression did, every time it applied: the compressor waits for enough bytes to compress well, and an LLM delta is only a few bytes. Second, the no-transform in the SSE helper's Cache-Control header is what made the popular compression middleware (1.8) skip the stream; remove it and every event arrived together at the end. Keep compression off for text/event-stream, keep no-transform, and still turn proxy buffering off, because other proxies and versions behave differently. Also raise read timeouts above the longest answer you expect; nginx closes an upstream connection after 60 seconds of silence by default, which the 15-second heartbeat also prevents.

Serverless platforms add their own limits on how long a response may stay open and whether it may stream at all, so check your host's documentation before you rely on long answers there.

Performance: rendering thousands of deltas smoothly

  • Batch renders. The hook's once-per-frame update keeps re-renders bounded no matter how fast tokens arrive.
  • Keep the streaming message cheap. If you render Markdown, re-parsing the whole growing answer on every frame gets slow for long replies. Render finished messages fully and the streaming one as plain text or with a lightweight renderer, or memoize earlier messages so only the last one updates.
  • Do not log every delta in production, on either side.
  • Measure time to first token on the server and in the browser; it is the number users feel, and it is where model choice, prompt size and network show up.

Security considerations

  • Keep the key on the server. The browser talks to your endpoint, never to the model API directly.
  • Authenticate and rate-limit the endpoint before it calls the model, per user and per IP. Every request costs money, and an open streaming endpoint is easy to abuse.
  • Validate input sizes, as the zod schema does, so no one can send a huge history.
  • Render model output as text. The component inserts the answer as text, which React escapes. If you render Markdown to HTML, sanitize it, because model output can contain links and markup taken from user input.
  • Limit concurrent streams per user, since each open stream holds a server connection and a model request.

Scaling SSE servers

Each streaming answer holds one open HTTP connection for its whole length. Node.js handles many idle connections cheaply, so the usual limits are the model API's rate limits and your proxy's connection settings, not CPU. Spread load across several instances behind a load balancer; because each answer lives on one connection, you do not need sticky sessions. Over HTTP/1.1, browsers allow only about six connections per site, so many open streams in several tabs can block other requests; HTTP/2 between the browser and your proxy removes that limit. Resuming a dropped answer with Last-Event-ID is possible, but it means storing generated text server-side, for example in Redis, and replaying it, because a model call cannot resume halfway.

Common mistakes and how to fix them

MistakeSymptomFix
Compression on the streamThe whole answer appears at once at the endExclude text/event-stream from gzip and send Cache-Control: no-transform
Using EventSource for the chat requestNo way to send the conversation or an auth headerPOST with fetch and parse the SSE body
Splitting the body on blank lines per chunkLost or broken messages under loadBuffer partial lines across chunks, as parseSSE does
Decoding chunks without stream: trueBroken characters in non-English text and emojiUse one TextDecoder with { stream: true }
setState on every deltaLaggy typing and high CPU on long answersBatch deltas and render once per animation frame
Stop only hides the textThe model keeps generating and billingAbort the model stream when the response closes early
Errors sent as HTTP status after streaming startedThe client never sees the errorSend an error event inside the stream

Limitations and trade-offs

SSE is one-way, so anything the user sends mid-answer needs a new request. It carries UTF-8 text only; binary data has to be encoded. EventSource cannot POST or set headers, which pushes you to fetch-based parsing like the one here, and you then own reconnection. Long-lived responses are awkward on some serverless platforms and some corporate proxies. And streaming does not make the model faster: it moves the first words earlier, while the total time stays the same.

What to build next

You now have a complete streaming chat: an SSE endpoint, a parser that survives real network chunks, a hook that renders smoothly, and a Stop button that reaches the model. Good next steps are Markdown rendering with sanitizing, a conversation store so chats survive a reload, per-user rate limits, and time-to-first-token metrics. To ground the answers in your own documents, combine this endpoint with the retrieval step from the RAG pipeline with Next.js and pgvector.

Frequently asked questions

What are Server-Sent Events?

A web standard for a server to push text messages to the browser over one long HTTP response with the content type text/event-stream. Each message is a few field lines such as event and data, followed by a blank line.

Should I use SSE or WebSockets for an LLM chat?

SSE in most cases. The answer only flows from server to client, SSE works over plain HTTP, and it avoids running a second protocol with stateful connections.

Can EventSource send a POST request?

No. EventSource only makes GET requests and cannot send a body or custom headers. For a chat, post the conversation with fetch and parse the text/event-stream body yourself.

Why does my stream arrive all at once?

Something between the server and the browser waits for more data, usually compression or a buffering proxy. Exclude text/event-stream from gzip, send Cache-Control: no-transform and turn proxy buffering off.

How do I stop an LLM stream from React?

Pass an AbortController signal to fetch and call abort on Stop. On the server, listen for the response close event and abort the model stream if the answer had not finished.

Does stopping the stream save money?

Yes, if the server aborts the model request when the client disconnects. If it only stops sending to the browser, the model keeps generating output tokens you pay for.

How do I avoid re-rendering React on every token?

Collect incoming text in a variable and update state once per requestAnimationFrame, so the component renders at most once per frame.

Why use JSON in the data field?

JSON.stringify never writes raw line breaks, so each message fits on one data line, and the text inside can contain anything, including line breaks and emoji.

How do I send errors once streaming has started?

The HTTP status is already 200, so send an error event inside the stream and let the client show it.

Do I need a heartbeat in SSE?

It helps. A comment line every 15 seconds or so stops proxies and load balancers from closing a connection that is quiet while the model works.

Can an SSE stream resume after a dropped connection?

EventSource reconnects and sends Last-Event-ID, but a model call cannot resume halfway. You would need to store the generated text and replay it from that ID.

Does this work with OpenAI or other models?

Yes. Only the server route changes: read that SDK's stream and send each text chunk as a delta event. The SSE helper, parser and React hook stay the same.

Sources

Free apps from the author of this guide