Event Stream Response
Introduction
A few of our API endpoints use server-sent events (SSE) to provide real-time feedback for long-running operations. This document explains how to consume these event streams in your frontend code.
Basic Implementation Pattern
1. Making the API Request
const response = await axios.post(
"/api/your-endpoint",
requestPayload,
{
headers: {
"Content-Type": "application/json",
"Accept": "text/event-stream",
"Authorization": `Bearer ${localStorage.getItem("access_token")}`
},
responseType: "stream",
adapter: "fetch"
}
);
// Get the stream from response
const stream = response.data;
const reader = stream.pipeThrough(new TextDecoderStream()).getReader();2. Reading and Processing the Stream
3. Buffer Processing Function
Here's a standard pattern for the buffer processing function:
4. Event Handling Using State Updates
Key Concepts
Event Stream Format: Our APIs send events in the Server-Sent Events format with
event:anddata:fields separated by newlines.Buffer Management: We accumulate incoming data in a buffer and process complete events, keeping any partial events for the next processing cycle.
Event Types: Different event types indicate different stages of processing. Handle each according to your UI needs.
Error Handling: Error events should be handled appropriately to update UI and inform users.
Common Pitfalls
Buffer Processing: Always maintain partial events in the buffer to avoid data loss.
JSON Parsing: Always use try/catch when parsing JSON data from events.
Memory Management: For very long streams, consider limiting buffer size or clearing processed events.
Connection Issues: Handle network interruptions and provide retry capabilities.
Example Implementation
Here's a simplified implementation example:
This pattern will work for all event stream responses from our APIs.
Last updated