Language: EN

comunicacion-sse-nodejs

How to do SSE (Server Sent Events) with Node.js

In Node.js, we can implement Server-Sent Events easily using the standard http module along with the EventEmitter module. Below, we’ll see a basic example of how to create an SSE server and how to send events to the client.

Server-Sent Events (SSE) is a technology that allows us to send real-time updates from the server to the client through one-way communication from the server to the client.

Unlike Websockets, which provide bidirectional communication, SSE is ideal for scenarios where we only need to send updates from the server to the client.

The advantages of Server-Sent Events are:

  • Simplicity: SSE is easy to implement on both the server and the client, without the need for external libraries.
  • Compatibility: They are compatible with most modern browsers without the need for additional libraries or polyfills.
  • Automatic Reconnection: In case of disconnection, the browser will automatically attempt to reconnect to the server, ensuring a more stable communication.

Example of Server-Sent Events in Node.js

Let’s see a basic example of how to create an SSE server and how to handle connection and message events.

Creating the SSE Server

First, we create an SSE server in Node.js to handle client communications.

import http from 'http';

// Function to send events to the client
function sendEvent(res, event, data) {
  res.write(`event: ${event}\n`);
  res.write(`data: ${JSON.stringify(data)}\n\n`);
}

// Create HTTP server
const server = http.createServer((req, res) => {
  // Header to indicate that SSE events are being sent
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
  });

  // Send an event every 5 seconds
  const interval = setInterval(() => {
    sendEvent(res, 'message', { message: 'Hello from the server' });
  }, 5000);

  // Handle client connection closure
  req.on('close', () => {
    clearInterval(interval);
    console.log('Client disconnected');
  });
});

const port = 3030;
server.listen(port, () => {
  console.log(`SSE server started at http://localhost:${port}`);
});

In this example:

  • An HTTP server is created listening on port 3000.
  • When a client connects, the server sets the Content-Type header as text/event-stream to indicate that SSE events will be sent.
  • Every 5 seconds, an event is sent to the client with a JSON message.
  • When a client disconnects, the event sending interval is cleared.

SSE Web Client (Frontend)

On the client side, we can use JavaScript to receive and handle events sent by the server.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>SSE Client</title>
</head>
<body>
  <div id="message"></div>

  <script>
    const messageDiv = document.getElementById('message');

    const evtSource = new EventSource('http://localhost:3030');

    evtSource.onmessage = function(event) {
      const data = JSON.parse(event.data);
      messageDiv.innerHTML = 'Server Message: ' + data.message;
    };

    evtSource.onerror = function(event) {
      console.error('SSE Error:', event);
      evtSource.close();
    };
  </script>
</body>
</html>

In this HTML client example, we create an EventSource pointing to our SSE server at http://localhost:3030. When the client receives an event (onmessage), we update the content of an HTML element with the current time sent from the server.

To try it out:

  1. Run the Node.js server that sends SSE events.
  2. In a browser, go to the address localhost:3030
  3. You should see that the server message is updated every 5 seconds on the page.

sse-example