Skip to content

SSE Streaming Guide

BacMR uses Server-Sent Events (SSE) for the /chat endpoint to provide a responsive, "typing" experience.

Protocol Detail

  • Endpoint: POST /chat with stream: true.
  • Content-Type: text/event-stream.

Event Types

  1. event: token: Data is a single string chunk (token).
  2. event: sources: Data is a JSON array of source objects.
  3. event: error: Data is an error message string.
  4. event: done: Data is [DONE].

Security Considerations

  • CORS: Ensure the frontend origin is in CORS_ALLOWED_ORIGINS.
  • JWT: The Bearer token must be passed in the Authorization header. Note: Standard EventSource in browsers doesn't support headers; use a library like fetch-event-source or pass the token via a cookie/query param (though BacMR currently expects the Header).

Frontend Consumption Pattern (Pseudo-code)

import { fetchEventSource } from '@microsoft/fetch-event-source';

await fetchEventSource('https://api.bacmr.mr/chat', {
  method: 'POST',
  headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
  body: JSON.stringify({ messages: [...], stream: true }),
  onmessage(ev) {
    if (ev.event === 'token') updateUI(ev.data);
    if (ev.event === 'sources') showSources(JSON.parse(ev.data));
  }
});

Back to Index