← Tous les articles

Streaming AI responses in JavaScript: server relay, fetch and Server-Sent Events, minus the pitfalls

Show a model's answer word by word in your site or SaaS: relay the stream server-side without exposing your key, read it with fetch, handle stopping and errors, and avoid the buffering that breaks everything in production.

Streaming AI responses in JavaScript: server relay, fetch and Server-Sent Events, minus the pitfalls

Key points

  • Streaming doesn’t make the model faster, but the first words appear in a fraction of the total time, and that’s what changes how users perceive it.
  • The browser should never call the AI provider directly: your server relays the stream and keeps the API key.
  • In production, the number one problem is buffering by a proxy, CDN or compression layer, which makes the whole answer land at once.

When we add an AI assistant to an application or website, the first version often returns the full answer in one go. It works, but users stare at a spinner, assume something crashed and click again. Streaming fixes that, with a few pitfalls you only hit in production. Here’s the complete implementation we use, from server to browser.

Why stream, and the architecture to stick to

A model produces its answer piece by piece. With streaming, your server forwards each piece as it arrives: total time is unchanged, but users start reading at once and can stop an answer that’s going the wrong way.

There are three links: browser, your server, provider API. The middle one isn’t optional: calling the provider from the browser would hand your API key to every visitor. Your server also controls question length, system instructions and quotas.

Between your server and the browser, Server-Sent Events (SSE) are the natural fit: a text stream over HTTP where each event is a data: line followed by a blank line. WebSockets are overkill, since data only flows one way.

Server side: relaying the stream without exposing the key

Here’s a Node.js example against an API using the most common chat format; the approach is the same in PHP or Python:

// server.js (Node 18+ et Express) : relays the provider's stream; the key stays here
import express from 'express';
const app = express();
app.use(express.json());

app.post('/api/assistant', async (req, res) => {
  const question = String(req.body.question ?? '').slice(0, 4000);
  const controller = new AbortController();
  // Visitor closes the tab or clicks Stop: cancel the provider call too
  res.on('close', () => { if (!res.writableEnded) controller.abort(); });

  try {
    const upstream = await fetch('https://api.openai.com/v1/chat/completions', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${process.env.LLM_API_KEY}`,
      },
      body: JSON.stringify({
        model: process.env.LLM_MODEL,
        stream: true,
        messages: [{ role: 'user', content: question }],
      }),
      signal: controller.signal,
    });
    if (!upstream.ok) return res.status(502).json({ error: 'Service unavailable' });

    res.set({
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      'X-Accel-Buffering': 'no',   // tells Nginx not to buffer
    });
    res.flushHeaders();

    let buffer = '';
    for await (const chunk of upstream.body.pipeThrough(new TextDecoderStream())) {
      buffer += chunk;
      const lines = buffer.split('n');
      buffer = lines.pop();                 // the last line may be incomplete
      for (const line of lines) {
        if (!line.startsWith('data: ') || line === 'data: [DONE]') continue;
        const text = JSON.parse(line.slice(6)).choices[0]?.delta?.content;
        if (text) res.write(`data: ${JSON.stringify({ text })}nn`);
      }
    }
    res.write('event: donendata: {}nn');
  } catch (e) {
    if (e.name !== 'AbortError') console.error('assistant', e);
  } finally {
    res.end();
  }
});

app.listen(3000);

Three details matter. The buffer: a network chunk isn’t a complete line, and without it JSON parsing fails at random, often only in production. The format: we send a minimal format ({text}), never the raw stream, so switching providers doesn’t touch the client. Cancellation: tab closed, call aborted, and you stop paying for output nobody reads.

In PHP (inside WordPress, say), disable output buffering (ob_end_flush() while ob_get_level() is positive) and call flush() after each chunk. Each connection ties up a PHP-FPM worker for the whole generation, so plan capacity accordingly.

Browser side: reading the stream with fetch

EventSource only sends GET requests with no body, so the question would end up in URLs, logs and history. We use fetch() with POST and read the body as a stream:

async function ask(question, target, signal) {
  const rep = await fetch('/api/assistant', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ question }),
    signal,
  });
  if (!rep.ok || !rep.body) throw new Error(`HTTP ${rep.status}`);

  // getReader() rather than for await: Safari can't iterate a ReadableStream
  const reader = rep.body.pipeThrough(new TextDecoderStream()).getReader();
  let buffer = '';
  while (true) {
    const { value, done } = await reader.read();
    if (done) break;
    buffer += value;
    const events = buffer.split('nn');   // an SSE event ends with a blank line
    buffer = events.pop();
    for (const ev of events) {
      if (ev.startsWith('event: done')) return;
      const data = ev.split('n').find((l) => l.startsWith('data: '));
      if (data) target.textContent += JSON.parse(data.slice(6)).text;
    }
  }
}

Note textContent rather than innerHTML: a malicious user can coax the model into returning a script tag, so output must never be injected as HTML.

To render Markdown, show plain text while streaming, then convert everything at the end and pass the HTML through a sanitiser such as DOMPurify. Re-rendering on every chunk is costly and makes the layout jump while a code block is still open.

Stop button, errors and accessibility

You need a stop button, and a clear signal when an answer is cut off midway (limit hit, connection lost), or users will assume it’s complete.

const form = document.querySelector('#assistant');
const answer = document.querySelector('#answer');      // aria-live="polite" aria-busy
const stopButton = document.querySelector('#stop');
let controller = null;

form.addEventListener('submit', async (e) => {
  e.preventDefault();
  controller = new AbortController();
  answer.textContent = '';
  answer.setAttribute('aria-busy', 'true');   // screen readers wait for the end
  stopButton.hidden = false;
  try {
    await ask(form.question.value, answer, controller.signal);
  } catch (err) {
    if (err.name !== 'AbortError') {
      answer.textContent += ' — The answer was cut off. Please try again in a moment.';
    }
  } finally {
    answer.setAttribute('aria-busy', 'false');
    stopButton.hidden = true;
  }
});

stopButton.addEventListener('click', () => controller?.abort());

An aria-live region updated per chunk would make screen readers announce fragments in bursts; aria-busy tells them to wait. And only auto-scroll if the user was already at the bottom.

Disable submitting during generation too, or two streams will write into the same element.

What breaks in production

The most common symptom: once deployed, the answer arrives in one block. The cause is almost always something buffering in between (Nginx, a CDN, a load balancer, compression). For Nginx, the X-Accel-Buffering: no header is often enough; if not:

location /api/assistant {
    proxy_pass http://127.0.0.1:3000;
    proxy_http_version 1.1;
    proxy_buffering off;        # pass each chunk on as soon as it arrives
    proxy_read_timeout 300s;    # a long answer can take more than 60 s
    gzip off;                   # compression batches small chunks together
}
  • CDNs and proxies: some buffer or compress text/event-stream by default. Test under real conditions.
  • Timeouts: many proxies drop idle connections after a few tens of seconds.
  • Cost and abuse: require authentication or per-user and per-IP rate limiting. On our projects we also cap question and answer size.
  • Logging: time to first chunk, total duration, interruptions.

To narrow it down, compare curl -N against the app server (port 3000) and against the public URL: if chunks only arrive progressively in the first case, your infrastructure is buffering.

FAQ

Should I use EventSource or fetch?

EventSource is handy for a stream triggered by a simple GET request, and it reconnects automatically. For an AI assistant where the question goes out as a POST, fetch with a stream reader is the better fit. Automatic reconnection makes little sense here anyway: resending the same question would generate a brand new answer.

Does streaming cost more with the AI provider?

No. Billing depends on how much text is sent and generated, not on how it’s delivered. Streaming can even save money when users stop an answer early, provided your server actually aborts the provider call.

Want to add an AI assistant to your website or SaaS application? We build secure, streaming AI integrations with costs and access kept under control.

Partager LinkedIn Facebook X WhatsApp
</>

webtestudio

Agence web : sites WordPress sur mesure, thèmes premium et logiciels SaaS.

Parler de votre projet →