Loading...
const source = new EventSource('/events', {
headers: { Authorization: `Bearer ${token}` },
});const source = new EventSource('/events', { withCredentials: true });
source.addEventListener('message', (e) => render(JSON.parse(e.data)));
window.addEventListener('pagehide', () => source.close());EventSource ignores custom headers, so auth goes through cookies, and the stream is closed when the page goes away.
EventSource for requests that need custom headers or a request body, which it does not support.close() when the component or page no longer needs it.Yes. If the connection drops, it reconnects after a delay and sends the 'Last-Event-ID' header so the server can resume.
No. It only makes GET requests. For a POST stream, read the fetch() response body with a stream reader.
Use addEventListener('name', ...) for events the server sends with an 'event: name' line; onmessage gets only unnamed events.