Skip to main content

open

§9.2.3

EventSource onopen

The open event fires on the EventSource object when the connection to the server is established and the HTTP response headers have been received with Content-Type: text/event-stream. It does not correspond to a server-sent event field – it is fired by the browser when the connection is ready. EventSource.readyState changes from CONNECTING (0) to OPEN (1).

Details

The open event is fired by the browser EventSource API when the HTTP response is received successfully with the correct Content-Type. It is not a field in the event stream – the server does not send anything special to trigger it.

The open event is the right place to update UI to show 'connected' status. It fires once per connection, including after automatic reconnects.

ReadyState transitions: CONNECTING (0) → OPEN (1): open event fires OPEN (1) → CONNECTING (0): connection lost, browser queues reconnect CONNECTING (0) → CLOSED (2): permanent error (204 response, or source.close() called)

The open event is also a good place to reset any error state from a previous disconnect.

Examples

Listening for open
const source = new EventSource('/stream');

source.onopen = (e) => {
  console.log('Connected. readyState:', source.readyState); // 1
  updateStatus('connected');
};

// Or with addEventListener:
source.addEventListener('open', () => {
  console.log('SSE connection open');
});
ReadyState constants
// EventSource readyState values (spec §9.2.2)
console.log(EventSource.CONNECTING); // 0
console.log(EventSource.OPEN);       // 1
console.log(EventSource.CLOSED);     // 2

// Check connection state
if (source.readyState === EventSource.OPEN) {
  console.log('Connection is active');
}

Gotchas

!

The open event fires per connection – it fires again after each successful reconnect

!

A successful HTTP 200 response with wrong Content-Type will fire the error event, not open

!

The open event fires after headers are received, not after the first event data arrives

See Also