DEV Community

sagar sonawane
sagar sonawane

Posted on

Real-Time Updates in MERN Applications with Server-Sent Events

In the fast-paced world of web development, providing real-time updates to users has become increasingly important. Whether it's updating a chat interface, displaying live sports scores, or tracking changes in a collaborative document , real-time updates enhance user experience and engagement. Traditionally, achieving real-time updates involved technologies like WebSockets or long-polling. However, there's another approach gaining traction: Server Sent Events (SSE).

Understanding Server-Sent Events

Server-Sent Events (SSE) is a standard mechanism for pushing real-time updates from a server to a client over an HTTP connection.Unlike WebSockets, which provide full-duplex communication channels, SSE is unidirectional, allowing servers to send data to clients but not vice versa. SSE is particularly useful for scenarios where only the server needs to initiate communication, such as broadcasting updates or notifications to clients.

Setting Up a Node.js Server with Express.js and express-sse

1.Server Implementation


const express = require('express');
const SSE = require('express-sse');
const app = express();
const sse = new SSE();

// Route to handle client connections
app.get('/events', sse.init);

// Function to broadcast data to clients
function sendUpdateToClients(data) {
  sse.send(data);
}

// Example usage: Broadcasting updates when devices send data to the server
SomeDataEmitter.on('dataReceived', (data) => {
  sendUpdateToClients(data);
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode
  1. client implementation
const eventSource = new EventSource('/events');

eventSource.onmessage = function (event) {
  console.log('Received update:', event.data);
  // Update UI with received data
};

Enter fullscreen mode Exit fullscreen mode

Project: Real-Time Updates in a MERN Application

Let's consider a use case where we want to display real-time updates on the frontend whenever devices send data to our server. This could be applicable in scenarios such as IoT applications where multiple devices are constantly sending sensor data to be displayed in a dashboard.

Please checkout following Project.

SSE-backend-architechture

Frontend :

Frontend speedometer

Github : https://github.com/ssonawane511/iot-sse

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.