patternjavascriptModerate
EventSource: Reconnection, Last-Event-ID, and Named Events
Viewed 0 times
eventsourcelast-event-idsse reconnectnamed eventsserver-sent eventsevent stream
Problem
SSE connections that drop don't resume from where they left off — the client reconnects and starts receiving events from the beginning, or misses events that occurred during disconnection.
Solution
Use the SSE
id field and Last-Event-ID header for resume-on-reconnect. Use named events for multiplexing different message types on one connection.// Server: send id with each event
function sendEvent(res, id, event, data) {
res.write(`id: ${id}\n`);
res.write(`event: ${event}\n`);
res.write(`data: ${JSON.stringify(data)}\n\n`);
}
// Server: handle reconnection
app.get('/events', (req, res) => {
const lastId = req.headers['last-event-id'];
res.setHeader('Content-Type', 'text/event-stream');
// Replay missed events since lastId
if (lastId) replayFrom(lastId, res);
// Then stream new events
});
// Client: listen to named events
const es = new EventSource('/events');
es.addEventListener('order-update', (e) => handleOrder(JSON.parse(e.data)));
es.addEventListener('notification', (e) => handleNotif(JSON.parse(e.data)));
// es.lastEventId gives the last received idWhy
The browser sends
Last-Event-ID automatically on reconnect if the server set id on previous events. This enables the server to resume the stream from the correct point, preventing data loss.Gotchas
- Set
retry: 3000(ms) in the event stream to suggest reconnect interval to the browser. - If you close the EventSource manually (
es.close()), it does not reconnect — this is intentional. - EventSource does not support HTTP/2 server push — it's purely based on the response body stream.
- Named events use
event:field; unnamed events usedata:only and fire themessageevent.
Revisions (0)
No revisions yet.