How do I read the event stream in JavaScript?
The browser's EventSource can't send Authorization headers, so read the stream with fetch on your server (Node 18+ has fetch built in):
const res = await fetch(`${BASE}/v1/runs/${runId}/events?after=${after}`, { headers });
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
let buf = "";
for (;;) {
const { value, done } = await reader.read();
if (done) break;
buf += value;
let i;
while ((i = buf.indexOf("\n\n")) >= 0) {
const chunk = buf.slice(0, i); buf = buf.slice(i + 2);
const event = /^event: (.*)$/m.exec(chunk)?.[1];
const data = JSON.parse(/^data: (.*)$/m.exec(chunk)?.[1] ?? "null");
// handle status / step / done / timeout / error
}
}
The full reconnecting client is in the Streaming guide.
Related articles
Still need help?
Tried the steps above and still stuck? Email us. We usually reply within the first hour, and always within 24 hours. A full support team is with you.
Infrastructure questions, or permanent deletion of your data
infrastructure@clatterlabs.xyzFor deleting your whole account or the data of one service.