What are the events available for server sent events in JavaScript?


The server-sent events allow developers to open a connection between the server and the client and send data from the server to the client. Basically, it is a one-way communication, which means we can send data from the server to the client but not from the client to the server.

Here, we will discuss all events available for the server-sent events in JavaScript.

Events Available for Server-sent Events in JavaScript

There is a total of 4 different events available for server-sent events in JavaScript.

  • ‘onopen’ − The ‘open’ event fires when the connection between the client and server is established successfully. We can use an ‘open’ event to make sure the connection is successful.

newEvent.onopen = () => {
   // perform some action
}
  • ‘onmessage’ − The ‘message’ event trigger whenever the server sends any message or data to the client. We can use the ‘message’ event to get updated data from the server and handle it on the client side.

newEvent.onmessage = message => {
   // handle the message data
};
  • ‘onerror’ − Whenever some issue occurs while connecting the server and client, the ‘error’ event gets fired. We can use the ‘error’ event to catch the error and retry the connection after every interval of time until the connection is established successfully.

newEvent.onerror = event => {
   // handle error 
}
  • ‘onclose’ − The ‘close’ event gets fired when the connection between the client and server gets closed either by the server or the client. When the ‘close’ event triggers, we can clear the browser cache and other data.

newEvent.onclose = event => {
   // clear the data
}

All four events can be used on the client side. Here, we will learn to use the above events on the client side via the example below.

Example

First, users require to create an index.html file and add the below code to that.

In the example below, we have created the ‘newEvent’ object using the EventSource() constructor. After that, we added the ‘onopen’ event to the code, and when it gets fired, we print a simple message.

Next, we have added the ‘onmessage’ event, which gets fired when the client receives a message from the server, and we handle data when it gets triggered.

Filename – index.html

<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 newEvent = new EventSource('http://localhost:3000/connect');
      // open event is fired when the connection is established.
      newEvent.onopen = () => {
         output.innerHTML += 'Connection to the server is successfully established. <br>';
      }
      
      // message event is fired when the server sends the data to the client.
      newEvent.onmessage = message => {
         output.innerHTML += "Updated message data is: " + message.data + "<br>";
      };
      
      // error event is fired when the connection is closed.
      newEvent.onerror = event => {
         output.innerHTML += `Error in the server-sent event: ${event}`;
      }
      
      // close event is fired when the connection is closed.
      newEvent.onclose = event => {
         output.innerHTML += 'Connection of the client with the server is closed.';
      }
   </script>
</body>
</html>

Now, users require to create a node application and need to install the ‘express’ and ‘cors’ NPM packages by the below command.

npm i express cors

After that, create a server.js file in the node application, and add the below code in the file.

In the below code, we have created the ‘connect’ API endpoint, which calls the manageClient() function. In the manageClient() function, we add a required header to the response. Also, we add clients to the response.

Next, we used the for loop to send the 5 updates to the client using the server-sent notifications.

const express = require("express");
const cors = require("cors");

const app = express();
// use cors
app.use(cors());
const PORT = 3000;

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

// add the client to the list
async function manageClient(req, res) {

   // set headers
   const requiredHeaders = {
      "Content-Type": "text/event-stream",
      Connection: "keep-alive",
   };
   
   //  adding 200 response code
   res.writeHead(200, requiredHeaders);
   
   // create a client object and add it to the list
   const client = {
      id: Math.random(),
      res,
   };
   clients.push(client);
   console.log(`Client is connected Successfully`);
   for (let i = 0; i < 5; i++) {
   
      // send data to the client
      res.write(`data: test${i}

`); } } // adding endpoints app.get("/connect", manageClient); // run the server app.listen(PORT, () => { console.log(`App listening on port ${PORT}`); });

Now run the server of the node application using the below command.

node server.js

Output

When users refresh the index.html file in the browser, it establishes the connection between the server and the client. Also, it prints the message that the connection was established successfully as an ‘onopen’ event gets fired.

After that, it prints the data when ‘on message’ events get fired. Users can observe the output below.

Users learned to use all four events of server-sent events on the client side. The first event is ‘open’, which ensures the connection is established. The second is the ‘message’ event allowing us to handle data we get from the server. The third event is ‘error’ to handle errors, and the last event is ‘close’ to get to know when the connection is terminated.

Updated on: 24-Apr-2023

168 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements