HTTP Stream Handling JS

how to get http streams in browser-side js

To get HTTP streams in browser-side JavaScript, you're typically working with the Fetch API, which supports streaming responses via ReadableStream. This allows you to read the response body in chunks as they arrive, rather than waiting for the full payload.

Here's a practical example:


✅ Fetching and handling HTTP stream (e.g., text stream or server-sent logs):

js
fetch('https://example.com/stream-endpoint') .then(response => { const reader = response.body.getReader(); const decoder = new TextDecoder(); return new ReadableStream({ start(controller) { function push() { reader.read().then(({ done, value }) => { if (done) { controller.close(); return; } // Decode and process the chunk const chunk = decoder.decode(value, { stream: true }); console.log('Received chunk:', chunk); controller.enqueue(value); push(); }); } push(); } }); }) .catch(error => console.error('Stream error:', error));

📦 Use Cases:

  • Streaming logs or events (e.g. from a backend like FastAPI, Express, etc.)

  • Real-time chat messages

  • Large text/video/audio files

  • Server-Sent Events (SSE)


🛠️ Notes:

  • response.body is a ReadableStream (if the server supports it and doesn't buffer the whole response).

  • If you're dealing with binary data, you can use Uint8Array directly.

  • The server must support chunked transfer encoding (Transfer-Encoding: chunked) and flush output correctly.


🚫 Not for:

  • WebSockets (use WebSocket API instead)

  • HTTP/1.0 (no streaming support)

  • Cross-origin endpoints without proper CORS headers


Would you like an example using Node.js as the backend to emit streams? Or are you working with an API that returns a specific kind of stream (like audio, video, JSON, etc.)?