Skip to main content

Real-Time Web Updates with HTML SSE: Simplifying Server-Sent Events

HTML SSE (Server-Sent Events) API is a web API that enables a server to push data to a web page over a single HTTP or HTTPS connection.

The server sends data to the client in a text-based format called Event Stream, and the client receives these events using JavaScript.

Here are the basic steps involved in using the HTML SSE API:

  • Create a new EventSource object in JavaScript, passing in the URL of the server endpoint that will send the events.

As an example:

const eventSource = new EventSource("http://example.com/events");
  • Add event listeners to handle different types of events that the server may send, using the onmessage, onopen, and onerror properties of the EventSource object.

As an example:

eventSource.onmessage = function (event) {
console.log("Received event:", event.data);
};

eventSource.onopen = function (event) {
console.log("Connected to server");
};

eventSource.onerror = function (event) {
console.error("Error occurred:", event);
};
  • On the server side, set up an endpoint that sends events using the Event Stream format. An event is sent as a plain-text string with a specific format: a line starting with data: containing the data of the event, followed by an empty line. Here's an example of sending an event in Node.js:

As an example:

const http = require("http");

http.createServer(function (req, res) {
res.writeHead(200, {"Content-Type": "text/event-stream"});
res.write("data: hello\n\n");
}).listen(8000);

This will create an HTTP server that listens on port 8000 and sends a "hello" event to any connected clients.

  • When the client no longer needs to receive events, call the close() method on the EventSource object to terminate the connection with the server.

As an example:

eventSource.close();

Receive Server-Sent Event Notifications

To receive server-sent event notifications using the HTML SSE API, you need to create an EventSource object in JavaScript and specify the URL of the server endpoint that will send the events.

As an example:

const eventSource = new EventSource("/events");

eventSource.onopen = function (event) {
console.log("Connected to server");
};

eventSource.onerror = function (event) {
console.error("Error occurred:", event);
};

eventSource.onmessage = function (event) {
console.log("Received event:", event.data);
};

In this example:

  • The EventSource object is created with the URL "/events".
  • This could be a relative or absolute URL, depending on the location of the server endpoint that sends the events.
  • The onopen and onerror properties of the EventSource object are used to handle connection-related events.
  • The onopen function is called when the connection is established, and the onerror function is called if an error occurs during the connection.
  • The onmessage property is used to handle incoming events.
  • When an event is received, the onmessage function is called with an Event object that contains the data of the event in its data property.

Once you have created an EventSource object and set up event listeners, the server can start sending events to the client.

Each event is sent as a plain-text string with a specific format: a line starting with data: containing the data of the event, followed by an empty line.

An example of sending an event in Node.js:

const http = require("http");

http.createServer(function (req, res) {
res.writeHead(200, {"Content-Type": "text/event-stream"});

setInterval(function () {
res.write("data: " + new Date().toISOString() + "\n\n");
}, 1000);
}).listen(8000);

This will create an HTTP server that sends an event every second containing the current date and time.

Server-Side Code Example

Here's an example of server-side code in Node.js that sends server-sent events to clients:

const http = require("http");

http.createServer(function (req, res) {
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
});

setInterval(function () {
const event = {
id: Date.now(),
data: `Event sent at ${new Date().toISOString()}`,
};

res.write(`id: ${event.id}\n`);
res.write(`data: ${event.data}\n\n`);
}, 1000);
}).listen(3000);

In this example:

  • We creates an HTTP server that listens on port 3000 and sends server-sent events to clients every second.
  • The server sends events with a unique ID and a message containing the current date and time.
  • The Content-Type header is set to 'text/event-stream', and additional headers are set to ensure that the connection is kept alive and the response is not cached.

You can run this server-side code in a Node.js environment and connect to it from a client-side application using the EventSource API to receive and process the server-sent events.