Backend to Frontend communication with Server-Sent Events

Maxi Stahl - May 4 '23 - - Dev Community

Server-Sent Events (SSE) is a web technology that allows servers to send updates asynchronously to clients in real time. This means that the server can send data to clients without them having to constantly request it. This is a good way to avoid polling the server for updates.

Server-Sent Events at high level

SSE is a way for a web page to receive automatic updates from a server via a HTTP connection. It is a one-way communication from the server to the client. This means that the client can only receive data from the server, but it cannot send data to the server. This is the main difference between SSE and WebSockets (WebSockets is a two-way communication between the client and the server).

When to use Server-Sent Events?

A common use case for Server-Sent Events is to display real-time updates on a website. For example:

  • a delivery tracking website could use SSE to display real-time updates on the status of a delivery.
  • to display real-time updates (in an online game maybe? :D)
  • to display updates from a news website.

How does it work?

The client opens an HTTP connection to the server and this sends data to the client via this connection. The client can receive data from the server as long as the connection is open. When the connection is closed, the client stops receiving data from the server.

Server to client infographic

One of the main advantages of SSE is that it is very easy to implement. You don't need to install any additional libraries or frameworks. You can use SSE with any programming language and any web framework.

How to implement Server-Sent Events in Node.js

I will show you how to implement SSE in Node.js using plain Javascript. Hold on tight, it's going to be fast!

Backend (Our node.js server)




const http = require('http');

http.createServer((req, res) => {
  // Set the response headers
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive',
    'Access-Control-Allow-Origin': '*'
  });

  // Send a message to the client every 5 seconds
  const interval = setInterval(() => {
    console.log('sending message');
    res.write('data: ' + new Date().toLocaleTimeString() + '\n\n');
  }, 5000);

  req.on('close', () => {
    console.log('client closed connection');
    clearInterval(interval); // Stop sending messages after user closes connection
  });
}).listen(3000);



Enter fullscreen mode Exit fullscreen mode

In this example, we create an HTTP server that sends a message to the client every 5 seconds using the setInterval() function. The message includes the current time using the toLocaleTimeString() function. It is important to set the response headers in this way so the client can correctly process the data.

Frontend (Our client)




const eventSource = new EventSource('http://localhost:3000');

eventSource.onmessage = (event) => {
  console.log(event.data);
};



Enter fullscreen mode Exit fullscreen mode

Here we created an EventSource object on the client side and passed the server URL that is sending the events to it. After that we added an onmessage event handler that is executed every time the server sends an event. In this example, we simply print the event data to the browser's console.

Conclusion

Pretty easy, right? It is very simple to implement and it works with any programming language and any web framework. I hope this is helpful to you. If you have any questions or comments, please leave them below.

Thank you for reading!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player