SSE Connection Lifecycle
You'll learn: How to manage the different states of a Server-Sent Events connection, handle errors gracefully, and implement automatic reconnection when things go wrong.
The Life of an SSE Connection
An SSE connection isn't just "on" or "off"—it has multiple states throughout its lifetime. Think of it like a phone call: connecting, talking, getting disconnected, trying to redial. Understanding these states lets you build robust real-time features.
Connection States
The EventSource object has a readyState property with three possible values:
EventSource.CONNECTING(0): Currently trying to establish connectionEventSource.OPEN(1): Connected and receiving eventsEventSource.CLOSED(2): Connection is closed and won't reconnect
You can check the current state to update your UI or decide whether to attempt manual intervention.
Error Handling
The error event fires when connection problems occur. This includes network failures, server errors, or the server closing the connection:
const eventSource = new EventSource('/events');
eventSource.addEventListener('error', (event) => {
if (eventSource.readyState === EventSource.CONNECTING) {
console.log('Reconnecting...');
} else if (eventSource.readyState === EventSource.CLOSED) {
console.log('Connection failed permanently');
}
});
Automatic Reconnection
Good news: browsers automatically try to reconnect after connection loss! The browser respects the retry field sent by the server (in milliseconds). If not specified, it uses a default interval (usually 3 seconds).
To close permanently and prevent reconnection, call eventSource.close().
Key Takeaway: SSE connections have three states (connecting, open, closed), fire error events when problems occur, and automatically reconnect unless you explicitly close them—making real-time features resilient by default.