What is server-sent events in JavaScript?


What is Server-sent Events in JavaScript?

In JavaScript, server-sent events (SSE) enable the server to send data to the client. The client require to establish a connection with the server to get data from the server.

The server-sent events are similar to the WebSocket as it also establishes a connection between the client and server, and it is useful to send data on both sides. But server-sent events allow unidirectional communication, which means the server can send data to the client, but the client can’t send data to the server.

Let’s build a real-time React and Node application to use the server-sent events. Here React is our frontend, and Node is our backend.

Example

Users need to follow the steps below to use server-sent events with the real-time application.

  • Step 1 − Create a React application.

  • Step 2 − In the application's project directory, run the below command to install the ‘axios’ NPM package in the project.

npm i axios
  • Step 3 − In the App() component, use the ‘useState’ hooks to update the messages we receive from the server.

  • Step 3.1 − Use the useEffect() hooks to establish a connection between the client and server. Here, we require to use the EventSource() constructor to establish a connection with the server by passing the URL of the server.

  • Step 3.2 − Also, add the ‘message’ event listener on the event source, and whenever the client receives a message from the server, it calls the handleMessage() function.

  • Step 3.3 − Next, create an object which removes the ‘message’ event and closes the connection between the client and server, and returns it.

  • Step 4 − In the handleMessage() function, get the data we received from the server, and push it to ‘messageData’ hooks.

  • Step 5 − Add an HTML code showing all messages we received from the server.

  • Step 5.1 − Add the ‘getMessage’ button, which calls the ‘sendMessage()’ function.

  • Step 5.2 − The sendMessage() function chooses any random message from the array of strings and sends it to the server using ‘axios’. The server receives the message and sends it to the client again via server-sent events.

  • Step 6 − Add the below code to the app.js file.

import React from "react";
import { useState, useEffect } from "react";
import axios from "axios";

const App = () => {
   const [messageData, setMessageData] = useState([]);

   useEffect(() => {
      // add the client to the server
      const newConnection = new EventSource("http://localhost:5000/addClient");
      newConnection.addEventListener("message", handleMessage);
      return () => {
         // close the event listener
         newConnection.removeEventListener("message", handleMessage);
         newConnection.close();
      };
   }, []);

   // getting message from server
   const handleMessage = (evt) => {
      const eventData = JSON.parse(evt.data);
      setMessageData((messages) => messages.concat(eventData));
   };

   // Send a random message to the server, which the server will send to the client via server-sent events
   const sendMessage = () => {
      let messages = [
         "JavaScript",
         "React",
         "Node",
         "Express",
         "MongoDB",
         "MySQL",
         "Python",
         "Django",
         "Flask",
         "Java",
         "Spring",
         "Spring Boot",
         "Spring MVC",
         "Spring Security",
         "Spring Data",
      ];
      const random = Math.floor(Math.random() * messages.length);
      axios.post("http://localhost:5000/message", {
         message: messages[random],
      });
   };

   return (
      <div>
         <h2> Server Sent Events </h2>
         <div>
            <h4> Click the below button to get a message from the server </h4>
            <button onClick = {sendMessage}> Get message </button>
         </div>
         <div>
            <h4> All messages </h4>
            <p> Total messages: {messageData.length} </p>
            {messageData.map((item, index) => (
               <div key={index}> {item.message} </div>
            ))}
         </div>
      </div>
   );
};

export default App;
  • Step 7 − Use the below command to run the server.

npm start

Now, users require to create a node application to set up the server.

  • Step 8 − Execute the below commands in the Node application’s project directory to install the NPM packages.

npm i cors body-parser express
  • Step 9 − Import the required NPM packages and set up the server for the application.

  • Step 10 − Create an API endpoint to receive the requests from the client.

  • Step 11 − When the server gets a request from ‘addClient’, it will invoke the ‘addClient()’ function.

  • Step 11.1 − Create headers inside the addClient() function. After that, create a client object, add id and ‘res’ into that and push to the ‘allConnectedClients’ array.

  • Step 11.2 − Listen to the ‘close’ event, and remove the client from the ‘allConnectedClients’ array when content between the server and client ends.

  • Step 12 − In the sendMessage() function, get a message from the client and add it into the ‘res’. After that, call the sendToClient() function, which sends the same message to all clients via server-side events.

  • Step 13 − Add the below code into the app.js file.

const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
const PORT = 5000;
// array to store all connected clients
let allConnectedClients = [];

// add the client to the list
const addClient = (req, res) => {

   // Set headers
   const headers = {
      "Content-Type": "text/event-stream",
      Connection: "keep-alive",
   };
   
   // adding 200 response code
   res.writeHead(200, headers);

   // create a client object and add it to the list
   const id = Date.now();
   const client = {
      id,
      res,
   };
   allConnectedClients.push(client);
   console.log(`Client is connected Successfully and its id is: ${id}`);
   req.on("close", () => {
      console.log(`Client is disconnected Successfully and its id is: ${id}`);
      
      // remove the client from the list when it gets disconnected
      allConnectedClients = allConnectedClients.filter(
         (client) => client.id !== id
      );
   });
};
const sendToClient = (msg) => {

   // iterate over all clients and send the message
   allConnectedClients.forEach((singleClient) =>
      singleClient.res.write(`data: ${JSON.stringify(msg)}

`) ); }; const sendMessage = (req, res) => { // Get the message from the request body const msg = req.body; // add message to response res.json(msg); return sendToClient(msg); }; // use cors and body parser app.use(cors()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); // adding endpoints app.get("/addClient", addClient); app.post("/message", sendMessage); // run the server app.listen(PORT, () => { console.log(`App listening on port ${PORT}`); });
  • Step 14 − Use the below command to run the code of the Node application.

node app.js

Note − Users need to make sure the server and client are running on a different host and need to change API endpoints in the client according to the server’s port.

Output

When clients connect successfully, users will see the below output in the node application's terminal.

For the frontend part, users will see the below output.

The Flow of the Above Application

After running both servers successfully, when users open the front-end part, it will request the ‘addClient’ endpoint that will establish a connection between the server and the client.

After that, when the user clicks the ‘get the message’ button, it will send a POST request to the ‘message’ endpoint with a particular message. The server receives a message and sends it back to the client via server-sent events.

The client receives the message, stores the message data and shows it on the browser. Here, we send data from the client for testing purposes. However, if we use the database and any data updates in the database, we can directly send updated data to the server.

Updated on: 24-Apr-2023

983 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements