S10.14
Real-Time AI Features: How to Implement Streaming Responses
The short answer
TL;DR
- →Streaming shows AI output token by token, making responses feel 3-5x faster even at the same total speed.
- →Most AI providers support streaming via server-sent events (SSE). No WebSocket needed for most use cases.
- →The front-end work is as important as the back-end. Render tokens progressively without layout shifts.
- →Add a cancel/stop mechanism. Users who see a wrong response heading the wrong direction want to stop it.
- →Streaming complicates error handling. Plan for mid-stream failures before you ship.
Why does streaming matter for AI features?
Because waiting 8 seconds for a response to appear all at once feels slow. The same response streaming in over 8 seconds feels fast.
This is not a trick. It's how human perception works. Progressive disclosure of information feels responsive. A long blank wait does not. For AI features where response times are inherently longer than a standard API call, streaming is not optional. It's the difference between a feature users trust and one they abandon.
For the wider picture, see the AI integration hub.
How does streaming work technically?
Here's the flow at a high level:
- Your front end sends a request to your backend (not directly to the AI provider).
- Your backend opens a streaming request to the AI provider's API.
- The provider sends tokens back as they're generated, using server-sent events.
- Your backend forwards each token to the client via SSE.
- The client renders each token as it arrives.
- When the stream completes, your backend closes the connection and sends a done signal.
You keep the AI API call on the backend for security. Your API keys never touch the client.
How do you implement the backend?
Here's the pattern in Node.js/TypeScript:
// Set response headers for SSE
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
// Stream from Claude
const stream = await anthropic.messages.stream({
model: 'claude-sonnet-4-5',
max_tokens: 1024,
messages: [{ role: 'user', content: userMessage }],
});
for await (const chunk of stream) {
if (chunk.type === 'content_block_delta') {
res.write(`data: ${JSON.stringify({ token: chunk.delta.text })}\n\n`);
}
}
res.write('data: [DONE]\n\n');
res.end();The same pattern applies to OpenAI and other providers, with minor API differences.
How do you implement the front end?
Use the EventSource API or a fetch with ReadableStream. Here's the fetch approach, which gives more control:
const response = await fetch('/api/ai/stream', {
method: 'POST',
body: JSON.stringify({ message: userInput }),
headers: { 'Content-Type': 'application/json' },
});
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
// Parse SSE format and append token to displayed text
appendTokenToUI(chunk);
}The key front-end consideration: render tokens without causing layout shifts. Use a pre-sized container or a monospace output area that expands predictably. Shifting layouts as text appears is disorienting and makes the feature feel broken.
What else do you need to handle?
A cancel button. Let users stop a response that's going in the wrong direction. On the client, call reader.cancel(). On the server, check for client disconnection and abort the upstream API call to avoid burning tokens.
Mid-stream errors. If the provider drops the connection mid-stream, the partial response is visible. Don't blank it. Show an error state with the partial content still readable and offer a retry.
Typing indicators. Show a visual indicator (cursor, pulse animation) while the stream is active. Remove it on completion or error. This makes the progressive text feel intentional rather than like a UI glitch.
For production-hardened streaming implementation built into your existing stack, Devwiz handles the full front-to-back build. Get in touch to scope your feature.
Frequently Asked Questions
- Do you need WebSockets for streaming AI responses?
- Not usually. Server-sent events (SSE) are one-directional and sufficient for most AI streaming use cases. WebSockets add bidirectional communication you typically don't need for a streaming response. Use SSE first. Add WebSockets only if you need real-time user input during generation.
- How do you handle a streaming response that errors mid-way through?
- The partial response will already be visible to the user. Show a clear error state, keep the partial response visible (don't blank it), and offer a retry option. Log the error with the partial response included so you can debug the failure point.
- Can you stream structured data (JSON) from an AI response?
- Yes, but it requires careful parsing. Either stream plain text and parse at the end, or use providers that support structured output with streaming. Don't try to JSON.parse partial tokens. Accumulate the full streamed text, then parse once the stream closes.
Related Services