Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction 
2.
Purpose of Introducing an SSE API in HTML
3.
How does an SSE API work in HTML?
4.
Implementation using SSE API
5.
Events received from Server
6.
Events sent from Server
7.
Handling the Errors
8.
How do we use SSE API in HTML?
9.
Challenges faced using SSE API in HTML
10.
Frequently asked questions
11.
Key takeaways
Last Updated: Mar 27, 2024

Server-Sent Events(SSEs) in HTML

Author aniket verma
2 upvotes

Introduction 

This blog will discuss an advanced feature that is the Server-Sent Events(SSEs) in HTML. 

Let us consider a situation when we are chatting and texting with another person. Have you ever thought about what happens when we send a text message and how we can send the messages?

The Server-Sent Event(SSEs) API in HTML makes this possible. It allows the server to automatically send an event to the web browser if any updates are available. For example, in stock prices updates, we see that the web page gets updated automatically.

Many browsers support this API, and details of some are as follows:

Opera supported this API after version 11.5 Chrome supported this API after version 6.0 Safari supported this API after version 5.0 Firefox supported this API after version 6.0 Edge supported this API after version 79.

 

Credits: Link


This API is supported by mostly all browsers except Internet Explorer and Deno.

Purpose of Introducing an SSE API in HTML

The main purpose of introducing an SSE API in HTML is that earlier for any updates, the web page would ask the server if there is any update. When SSE API is introduced in HTML, the server automatically sends the updates to the web page using the continuous event data streams.  

How does an SSE API work in HTML?

An SSE connection is established once the client initiates the communication with the server. The SSE API uses a JavaScript EventSource Object to which a URL of an endpoint is passed to the server using a regular HTTP request like GET, POST, etc.

Then the client receives the messages using the data streams over regular intervals of time. 

(NOTE: You can see the messages during the server-client communication by pressing Ctrl + F12 key on your system ).

But ever wondered what would happen if the client doesn’t communicate and the server is trying to communicate with the client for a long period of time even though the connection is stable? In such a case, the SSE API will decide to leave the HTTP response as it has been open for a long time. It can also be closed if the client explicitly closes it. 

Implementation using SSE API

The SSE API uses an EventSource interface with all the features/methods defined inside it, such as connecting to the servers, sending data, handling errors, termination of the connection, etc.

Let’s look at how the events are sent and received from the server using SSE API.

Events received from Server

New EventSource object is created to establish a persistent connection to which a script URL is passed using which events will be generated. 

The messages can now be received using an eventHandler

CODE

Description: The code demonstrates how SSE API is used in HTML and automatically sends or updates the events on the client’s page.  
 

<!DOCTYPE html>
<html>
<body>
<head>
    <title>SSE_API_Receiving_Server_Events</title>
</head>
<h1 style="background-color: red;">Receiving Server Events</h1>
<div id="result"></div>

<script>
// if the browser supports the EventSource interface in the SSE
// API
if(typeof(EventSource) !== "undefined") {

 // instantiating an object of EventSource which will sent the
 // updates
 var source = new EventSource("demo_sse.php");
  //onmessage Event will occur when any update/message is received
 source.onmessage = function(event) {
   // update the result innerHTML
   document.getElementById("result").innerHTML += event.data + "<br>";
 };
} else {
 document.getElementById("result").innerHTML = "Bad Luck! Your browser Doesn't support the SSE API";
}
</script>

</body>
</html>


The output of the above code:
 

 

The above code can be summarised as:

  1. Check if the browser supports the EventSource interface.
  2. Instantiating the EventSource object bypassing the server script URL
  3. Define the event handler to receive the server message and update it on the client’s page.

Events sent from Server

The server-side script sends events in the form of text/event-stream. Each notification sent is enclosed between 2 newline characters.

If you read the above code carefully, we have passed the URL demo_sse.php inside the EventSource object instantiated. Let’s see how this file is implemented and how events are sent from the Server.

 

<!DOCTYPE html>
<html>
<body>
<head>
    <title>SSE_API_Receiving_Server_Events</title>
</head>
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>

</body>
</html>


The above code is explained as follows:

  1. First, we mention the header-type, i.e. text/event-stream, and set the cache control to ‘no-cache’ as the page shouldn’t cache.
  2. If you see the output on the page of the previous code, you will see the line starting from “data:”. We have explicitly mentioned in our file to echo date.
  3. Finally, flush out the data onto the webpage. 

Handling the Errors

In case of any errors, for example, network issues, network timeouts, access control issues, etc. They are handled by using an onerror call back on the EventSource object.

​​source.onerror = function(error) {
  console.error("EventSource failed:", err);
};
You can also try this code with Online Javascript Compiler
Run Code

How do we use SSE API in HTML?

SSE API is used in the following scenarios:

  1. When we want a communication protocol that allows unidirectional communication without adding additional load over the server.
  2. When we want to use real-time streaming of data using HTTP-based methods.

SSE API is used in the following:

  1. It’s being used to update the live scores/points/tables regularly.
  2. To refresh the feed of an application like Facebook, Twitter, etc.
  3. News updates
  4. Stock Price Updations

Challenges faced using SSE API in HTML

Some of the challenges faced are:

  1. It's a unidirectional way of using the SSE API, with no way of sending messages from a client to a server except at the time of connection.
  2. It doesn’t allow the server to know immediately if the connection is lost at the client-side.  

Frequently asked questions

Question) Are SSE’s suitable in bidirectional communications?

Answer) Different protocols are used which serve different purposes according to the nature of real-time messaging and streaming data. Hence Web sockets are generally used for bidirectional communication.


Question) What is an Event Stream?

Answer) It’s a stream of text data encoded in UTF-8, and messages in the event stream are separated using 2 newline characters. 


Question) Why is the SSE API useful?

Answer) An SSE API uses the event streams by subscribing to the Javascript datastreams to update the DOM objects on the client's web page and automatically sends events to the client’s browser.

Key takeaways

In a nutshell, in this blog, we covered the topic of Server-Sent Events(SSEs) in HTML in depth. We touched on various topics like the working of Server-Sent Events(SSEs) in HTML and when it should be used, with its limitations, and understood all of it using sample code. We also discussed its uses and what can be done and what can’t be done.

I hope you all could gain in-depth knowledge about the Server-Sent Events(SSEs) in HTML and understand the topic clearly. If you want to learn more exciting stuff, you can enroll in our top-tier courses taught by the best faculty to unleash your learning potential.

Happy Leaning Ninja!

Live masterclass