DEV Community

DhiWise
DhiWise

Posted on • Updated on

How to Implement Server-sent Events in Node.js?

Server-sent events are a new HTTP API for pushing events from the server to the client. Unlike WebSockets, server-sent events (SSE for short) are built on top of the HTTP protocol, so no need for ws:// URLs or additional npm modules. Server-side events also handle reconnecting automatically, so you don’t have to write code to reconnect if the connection is lost.

image credit : [https://www.woolha.com](https://www.woolha.com/)

After discussing with plenty of developers during the last few days, I have realize that a more of them don’t know what “Server-Sent Events” (or “SSE” or “EventSource”) is. My aim here is to give you all the information you may need about Server-Sent Events.

With Server-sent events you are able to send one-directional events to a web page.

Using Server-Send-Events eliminates the need to poll a server periodically for information using AJAX and is really easy to implement because of the simple specification and the fact that nearly all modern browsers already implement this specification.

Why should you even learn about SSE?

In the fast generation world, users are more and more real-time oriented, so we need Server-Sent Events if displaying the last information updates to our users may change their actions.

The information itself need not change often, but when it changes, you really want users to know it!

Before begin, Let’s deeply look at some real-world test cases before we explain the technical details:

  • Users may click on the last news available rather than shutting down the page.

  • Services / product availability. If you sell products or services rare for this specific client (car-sharing, docks for bike-sharing, promotions with limited stocks…), you want to make sure your prospect knows it is available as soon as possible.

  • Prices of crypto-currency, gold, silver…

  • Social / chat… like Facebook, WhatsApp, Telegram, and so on..!

  • You may just want to display rapidly changing data: game score, trading, dashboard.

I don’t care about your “Server-Sent stuff” I have WebSockets!

Ok, WebSockets are trendy, fast, and easy to implement now but, There are pros and cons for WebSocket and SSE. I suggest you read this blog post and come back here afterward…

I will be waiting for you…

So, Now move on technical side :

The event-stream is a simple stream of text information which must be encoded using UTF-8. Messages in the event-stream are separated by a pair of newline characters (“\n”).

The following field names are defined in the specification:

Event: The event’s type. It will allow you to use the same stream for different content. A client can decide to “listen” only to one type of event or to interpret differently each event type.

**Data: **The data field for the message. You can put consecutive “data” lines.

ID: ID for each event-stream. Useful to track lost messages.

Retry: The time to use before the browser attempts a new connection after all connections are lost (in milliseconds). The re-connection process is automatic and is set by default at three seconds. During this re-connection process, the last ID received will be automatically sent to the server…

The Server Implementation :

To run the demo application using node.js simply run the following command from the project’s root directory:

node server.js
Enter fullscreen mode Exit fullscreen mode

Here is the server implementation in JavaScript:

var http = require('http');
var fs = require('fs');

/*
 * send interval in millis
 */
var sendInterval = 5000;

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

 var sseId = (new Date()).toLocaleTimeString();

 setInterval(function() {
 writeServerSendEvent(res, sseId, (new Date()).toLocaleTimeString());
 }, sendInterval);

 writeServerSendEvent(res, sseId, (new Date()).toLocaleTimeString());
}

function writeServerSendEvent(res, sseId, data) {
 res.write('id: ' + sseId + '\n');
 res.write("data: new server event " + data + '\n\n');
}

http.createServer(function(req, res) {
 if (req.headers.accept && req.headers.accept == 'text/event-stream') {
 if (req.url == '/talk') {
 sendServerSendEvent(req, res);
 } else {
 res.writeHead(404);
 res.end();
 }
 } else {
 res.writeHead(200, {
 'Content-Type' : 'text/html'
 });
 res.write(fs.readFileSync(__dirname + '/index.html'));
 res.end();
 }
}).listen(8080);
Enter fullscreen mode Exit fullscreen mode

The Client Implementation :

For Server Send Events (SSE) is quite easy .. simply create a new EventSource object that is bound to the URL where the events are propagated.

In the next step just add an event listener to the source object — the function is called each time that a SSE is received.

Finally an event is bound to a button to stop listening to SSEs using the Event Source's close method.

<!DOCTYPE html>
<html>
   <head>
      <meta charset="utf-8" />
   </head>
   <body>
      <input type="button" id="stopButton" value="Stop Listening"/>
      <hr/>
      <div id="content"></div>
      <script>
         var source = new EventSource('/talk');
         source.addEventListener('open', function(e) {
         document.getElementById('content').innerHTML += 'Connections to the server established..<br/>';
         }, false);
         source.onmessage = function(e) {
         document.getElementById('content').innerHTML += e.data + '<br/>';
         };
         document.getElementById('stopButton').onclick=function(){
         document.getElementById('content').innerHTML += 'Listening to server events stopped..<br/>';
         source.close();
         }
      </script>
   </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Afterwards, you should be able to open http://localhost:8080 in your browser and watch the events. Pressing the button should stop listening to the server send events.

That’s all about the tutorial of how to implement SSE in Node.js.

When an app/website needs some information updated in real-time, and there is not a need for upward data flow, Server-Sent Events should be considered first.

Congratulations

We are at the end! Hope you enjoyed reading this article and learnt something new today.

PS: I’ll keep on adding and improving the content of this article as I learn more about these concepts!

If you disagree, please comment on this article below and we will happily reply.

Resources used:

  1. digitalocean

  2. stackoverflow

    For more blog-post: **link**

Thank you for reading!!

  • By Bhavy Kapadiya (Programmer Analyst | DhiWise)

Top comments (0)