How to determine that an SSE connection was closed?

If the connection is closed (in such a way that the browser can realize it), it will auto-connect. And it tends to do this quickly (default is 3 seconds in Chrome, 5 seconds in Firefox). readyState will be CONNECTING (0) while it is doing this. It is only ever CLOSED (2) if there was some problem connecting in the first place (e.g. due to a CORS issue). Once CLOSED, it does not retry.

I prefer to add a keep-alive mechanism on top, as the browser cannot always detect dead sockets (not to mention a remote server process that is locked up, etc.). See ch.5 of Data Push Apps with HTML5 SSE for detailed code, but basically it involves having the server send a message every 15 seconds, then a JavaScript timer that runs for 20 seconds, but is reset each time a message is received. If the timer ever does expire, we close the connection and reconnect.


EventSource API Update

EventSource API now has three event handlers:

  • onerror
  • onmessage
  • onopen

These should be enough to handle everything you need on the client side.

Something like this:

const ssEvent = new EventSource( eventUrl );

ssEvent.onopen = function (evt) {
  // handle newly opened connection
}

ssEvent.onerror = function (evt) {
  // handle dropped or failed connection
}

ssEvent.onmessage = function (evt) {
  // handle new event from server
}

Ref: mozilla.org : EventSource : Event handlers

Browser support for EventSource API: onopen - caniuse.com