The HTML Server-Sent Events (SSE) API is a client-side JavaScript API that enables a web page to receive real-time updates from a server over a single, long-lived HTTP connection. It provides a straightforward way to push server updates to the client without the need for continuous polling. Here’s an overview of how to use the SSE API:
- Establishing an SSE Connection:
- To establish an SSE connection, create a new EventSource object by passing the URL of the server-side script that will handle the SSE communication.
const eventSource = new EventSource('/sse-server');
- Handling SSE Events:
- The server-side script should send data to the client using the SSE protocol. Each data event from the server will trigger an event on the EventSource object in the client.
- In the client-side JavaScript, you can listen for events using the
onmessage
event handler.
eventSource.onmessage = function(event) {
const data = event.data;
// Handle the received data
};
- Handling SSE Errors:
- You can handle errors that occur during the SSE connection by listening for the
onerror
event.
eventSource.onerror = function(event) {
console.error('SSE error:', event);
};
- Closing the SSE Connection:
- To close the SSE connection, call the
close()
method on the EventSource object.
eventSource.close();
- Sending Server-Side Updates:
- On the server-side, you need to set up a script that sends updates to the client using the SSE protocol.
- In most server-side languages, you can set the appropriate headers and send data using the “text/event-stream” content type. Each update should be sent as a separate event with a “data” field.
- Here’s an example in Node.js using Express:
app.get('/sse-server', (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
// Send SSE events periodically
setInterval(() => {
const data = 'This is a server-side update';
res.write(`data: ${data}\n\n`);
}, 2000);
});
The HTML SSE API provides a simple and efficient way to implement real-time server updates in web applications. It enables the server to push data to the client over a single HTTP connection, eliminating the need for frequent polling and reducing network overhead. SSE is particularly useful for scenarios where real-time updates are required, such as chat applications, live feeds, or real-time monitoring systems.