Server-Sent Events (SSE)

Server-Sent Events (SSE) in JavaScript
In the realm of web development, delivering real-time updates to users has become a crucial aspect of creating dynamic and engaging experiences.

Traditional methods like polling or WebSocket connections have been the go-to solutions, but there exists another powerful tool in the arsenal: AJAX Server-Sent Events (SSE). This article will delve into the world of SSE, exploring its fundamentals, setting up server-side SSE, and consuming SSE on the client side, accompanied by illustrative code examples.

Introduction to SSE

Server-Sent Events (SSE) is a standard that enables servers to push real-time updates to web clients over HTTP. Unlike traditional AJAX requests where the client initiates communication, SSE allows the server to initiate data transmission. This one-way communication stream is ideal for scenarios where real-time updates, such as news feeds, stock tickers, or social media notifications, need to be delivered to the client instantly.

SSE operates over a single, long-lived HTTP connection, making it lightweight and efficient. It leverages the EventSource interface on the client side to receive updates, providing a simple and elegant solution for implementing real-time communication without the complexity of WebSockets.

Setting up Server-Side SSE

Implementing SSE on the server side typically involves configuring an endpoint that sends a stream of data to the client. Let’s illustrate this with a basic Node.js example using Express:

				
					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');

  // Send a message every 2 seconds
  const intervalId = setInterval(() => {
    const data = `data: ${new Date().toLocaleTimeString()}\n\n`;
    res.write(data);
  }, 2000);

  // Clean up on client disconnect
  req.on('close', () => {
    clearInterval(intervalId);
    res.end();
  });
});

app.listen(3000, () => {
  console.log('SSE server listening on port 3000');
});

				
			

In this example, we define a route /events that sets the appropriate headers for SSE and sends a message containing the current time every 2 seconds. We also handle client disconnects to clean up resources.

Consuming SSE on the Client Side

On the client side, consuming SSE is straightforward using the EventSource interface. Let’s create a simple HTML page to receive and display the real-time updates:

				
					<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>SSE Client</title>
</head>
<body>
  <h1>Real-Time Updates</h1>
  <ul id="updates"></ul>

  <script>
    const eventSource = new EventSource('/events');
    const updatesList = document.getElementById('updates');

    eventSource.onmessage = function(event) {
      const newItem = document.createElement('li');
      newItem.textContent = event.data;
      updatesList.appendChild(newItem);
    };

    eventSource.onerror = function(error) {
      console.error('SSE error:', error);
      eventSource.close();
    };
  </script>
<script>var rocket_lcp_data = {"ajax_url":"https:\/\/codersship.com\/wp-admin\/admin-ajax.php","nonce":"8406859369","url":"https:\/\/codersship.com\/javascript\/ajax\/server-sent-events-sse","is_mobile":false,"elements":"img, video, picture, p, main, div, li, svg","width_threshold":1600,"height_threshold":700,"debug":null}</script><script data-name="wpr-lcp-beacon" src='https://codersship.com/wp-content/plugins/wp-rocket/assets/js/lcp-beacon.min.js' async></script></body>
</html>

				
			

This HTML page establishes a connection to the /events endpoint using EventSource. It listens for incoming messages and appends them to an unordered list (<ul>).

Conclusion

AJAX Server-Sent Events (SSE) offer a lightweight and efficient solution for implementing real-time communication in web applications. By allowing servers to push updates to clients over a single HTTP connection, SSE simplifies the process of delivering real-time data without the complexity of WebSockets. With the fundamentals of SSE, setting up server-side SSE, and consuming SSE on the client side covered in this article, developers can leverage this powerful technology to create dynamic and engaging user experiences in their web applications.

Scroll to Top