Creating an SSE Connection
What you'll learn: How to use the EventSource API to open and listen to a stream of server-sent events from your JavaScript code.
The Core Idea
Creating an SSE connection is surprisingly simple: you instantiate an EventSource object with a URL, and the browser automatically establishes a persistent HTTP connection to that endpoint. The server can then push messages to your client whenever it wants, without you having to repeatedly ask for updates.
Think of it like subscribing to a news ticker—you tune into a channel once, and updates flow to you automatically as they happen.
How to Create the Connection
You create an SSE connection by constructing an EventSource object:
const eventSource = new EventSource('/api/notifications');
That single line opens a connection to the /api/notifications endpoint. The browser handles all the connection management, reconnection logic, and message parsing for you.
Listening to Events
Once connected, you listen for messages using event listeners:
const eventSource = new EventSource('/api/notifications');
// Listen for the default "message" event
eventSource.onmessage = (event) => {
console.log('New message:', event.data);
};
// Listen for connection opened
eventSource.onopen = () => {
console.log('Connection established');
};
// Handle errors
eventSource.onerror = (error) => {
console.error('Connection error:', error);
};
The server sends text data, which arrives in event.data. The browser automatically manages the connection state—if it drops, EventSource tries to reconnect automatically.
Closing the Connection
When you're done, close the connection to free resources:
eventSource.close();
Key Takeaway: The EventSource API creates a persistent server connection with just new EventSource(url), then receives real-time updates through simple event listeners like onmessage, handling reconnection automatically.