How do you receive server-sent event notifications in JavaScript?


The server-sent event is a unidirectional way to communicate between the server and the client. When we only require to send data from server to client, but not from client to server, we can use the server-sent events.

We can use the server-sent events by establishing the connection between the client and server. Here, the server sends the data, and the client receives the data and handles the data to show on the web page. The server can be anything, such as Node, PHP, or Ruby applications.

So, when the server sends the data, the ‘message’ event fires on the client-side JavaScript, and data can be handled via event listeners.

Here is an example that demonstrates how we receive event notifications by server-sent events.

Example

  • Step 1 − First, we require to send the request to the server to establish a connection between the client and server from the client side.

  • Step 2 − Create an index.html file. In the <script> tag, initialize the new eventSource object using the ‘EventSource’ constructor.

const source = new EventSource('URL');

In the above syntax, the URL is a server's API endpoint where we must request JavaScript to establish a connection.

  • Step 3 − Add an event listener for the ‘message’ event. So, whenever the server sends the message to the client, the callback function of the event listener can handle the message data.

  • Step 4 − Add the below code in the index.html file.

<html>
<body>
   <h2>Using the <i> Server-sent events </i> for unidirectional communication in JavaScript.</h2>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      const source = new EventSource('http://localhost:5000/subscribe');
      source.addEventListener('message', message => {
         output.innerHTML += "Updated message is: " + message.data + "<br>";
      });
   </script>
</body>
</html>
  • Step 5 − Now, we require to create a Node application to use as a server. Run the below command in the project directory to create a new node application.

npm init -y
  • Step 6 − Next, run the below command to install the ‘express’ and ‘cors’ NPM packages. Here, ‘express’ is used to build a server, and ‘cors’ is used to allow access to all origins.

npm i cors express
  • Step 7 − Initialize the application server using the express, and make sure the app uses the cors.

  • Step 8 − Create a ‘subscribe’ API endpoint which can call the ‘subscribeClient()’ function.

  • Step 8.1 − The subScribeClient() function takes two parameters. First is the request, and the second is the response.

  • Step 8.2 − Create headers and add them to the response of the function.

  • Step 8.3 − Add a client object to the ‘allConnectedClient’ array using the push() method, which stores all connected and active clients.

  • Step 8.4 − Create an array of the string data. Now, use the infinite while loop, which waits for 5 seconds after every iteration, chooses the random data, and sends it to the client.

  • Step 9 − Add the below code to the app.js file of the node application.

const express = require("express");
const cors = require("cors");
const app = express();
// use cors
app.use(cors());
const PORT = 5000;

// array to store all connected clients
let allConnectedClients = [];

// add the client to the list
async function subscribeClient(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}`);
   let cnt = 0;
   
   //  Create data of strings and choose a random string
   let data = [
      "Hello",
      "World",
      "How",
      "Are",
      "You",
      "Today",
      "I",
      "Am",
      "Fine",
   ];
   while (true) {
   
      // wait for 5 seconds
      await new Promise((resolve) => setTimeout(resolve, 5000));
      console.log("Data updated", ++cnt);
      
      // send data to the client
      res.write(`data: ${data[Math.floor(Math.random() * data.length)]}

`); } } // adding endpoints app.get("/subscribe", subscribeClient); // run the server app.listen(PORT, () => { console.log(`App listening on port ${PORT}`); });
  • Step 10 − Use the below command in the current project directory to run the node application.

node app.js

Output

After running the node application server, open or refresh the index.html file in the web browser. Users can observe that it prints the data after every 5 seconds.

Users learned to use the server-sent event to get notified in JavaScript. Here, we send data after every 5 seconds from the server, but developers can send data only when data gets updated.

So, in this way, we can get a notification in the client-side JavaScript whenever server-side data gets updated using the server-sent events.

The server-side event is similar to the poling technique. In polling, the client sends a request to the server after every interval and asks for the update, which increases the server's load as it makes requests even if the server doesn’t have an update. But the server-sent event sends data to the clients when data gets updated, and the client doesn’t need to request an update to the server.

Updated on: 24-Apr-2023

538 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements