HTML Server-Sent Events (SSE) API

HTML Server-Sent Events (SSE) API is a powerful and efficient way to establish a unidirectional connection between a web server and a client. It allows the server to send real-time updates to the client without the need for the client to constantly poll the server for new information. In this article, we will explore the SSE API and provide examples to demonstrate its usage.

SSE API is based on the EventSource interface, which provides a simple and intuitive way to receive server-sent events. To establish a connection with the server, the client creates a new instance of the EventSource object and specifies the URL of the server endpoint that will be sending the events. Let’s take a look at an example:

“`html

const eventSource = new EventSource(‘/events’);

eventSource.onmessage = function(event) {
const eventData = JSON.parse(event.data);
// Handle the received event data
};

eventSource.onerror = function() {
// Handle any errors that occur during the connection
};

“`

In the above example, we create a new EventSource object and pass the URL ‘/events’ as the parameter. This URL represents the server endpoint that will be sending the server-sent events. We then define two event handlers: `onmessage` and `onerror`. The `onmessage` event handler is triggered whenever a new event is received from the server. In this example, we parse the event data as JSON and handle it accordingly. The `onerror` event handler is triggered if any errors occur during the connection.

On the server side, you need to implement an endpoint that sends the server-sent events to the client. Let’s consider an example using Node.js and Express:

“`javascript
const express = require(‘express’);
const app = express();

app.get(‘/events’, (req, res) => {
res.setHeader(‘Content-Type’, ‘text/event-stream’);
res.setHeader(‘Cache-Control’, ‘no-cache’);
res.setHeader(‘Connection’, ‘keep-alive’);
res.flushHeaders();

// Send server-sent events periodically
setInterval(() => {
const eventData = { message: ‘Hello, client!’ };
res.write(`data: ${JSON.stringify(eventData)}nn`);
}, 1000);
});

app.listen(3000, () => {
console.log(‘Server listening on port 3000’);
});
“`

In this example, we define a GET endpoint ‘/events’ that sets the necessary headers for SSE. We use `res.setHeader()` to set the appropriate headers, including ‘Content-Type’, ‘Cache-Control’, and ‘Connection’. We then call `res.flushHeaders()` to ensure that the headers are sent immediately.

To send server-sent events, we use `setInterval()` to periodically send events to the client. In this example, we send a simple JSON object with a ‘message’ property every second. The event data is sent using the `res.write()` method, with the ‘data’ field specified as ‘data:’. The event data is then stringified using `JSON.stringify()` and sent to the client.

The client will receive the server-sent events and trigger the `onmessage` event handler defined earlier. The event data can be accessed using `event.data`. In our example, we parse the event data as JSON and handle it accordingly.

HTML SSE API provides a reliable and efficient way to establish a real-time connection between a server and a client. It eliminates the need for constant polling and allows for instant updates. SSE is supported by most modern web browsers, making it a versatile choice for real-time applications.

In conclusion, HTML SSE API is a powerful tool for establishing real-time connections between servers and clients. By utilizing the EventSource interface, developers can easily send and receive server-sent events. With the examples provided in this article, you can start leveraging SSE in your own web applications to deliver real-time updates to your users.

Scroll to Top