Server Sent Events (SSE): A Comprehensive Conceptual Deep Dive

Server Sent Events (SSE): A Comprehensive Conceptual Deep Dive

Unlock the Power of Real-Time Communication in Web Development with SSE - Learn How It Works from Start to Finish"

ยท

3 min read

What is Server Sent Events (SSE)?

A Server Sent Event is when a web page automatically gets updates from a server. Traditionally, a web page has to send a request to the server to receive new data, then the server will send the response to the client. With server sent events, a server can send new data to a web page at any time, by pushing messages to the web page

If we are implementing JavaScript Server Sent Event, we should keep the following two things in mind:

  • A long-lived unidirectional communication exists (the communication happens between the server and the client)

  • An HTTP connection only

server sent even image

The communication flow between Server and Client using Server Sent Events. (Image Source: PubNub)

An HTTP request has been made. As long as we do not explicitly close this connection by doing some actions, such as changing the tab, this request will never terminate or close.

Every time there is new data, the server passes it on a regular interval over the same HTTP network, which is open.

Implementation

  1. The connection should be live

  2. The format in which data comes is event-stream

Example

We will understand the working of Server Sent Events using an example. Suppose, we have a stock price listing platform where our stock prices are to be updated continuously. Now for this, we only need a unidirectional connection i.e. server to client, where our server would send the new prices to our clients whenever they are updated on our server.

  • We will create a normal HTML file and run the script in the script tag, where we will call (/see) and render the latest stock prices whenever the server updates them.

      <!DOCTYPE html>
      <html lang="en">
      <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>SSE Test App</title>
      </head>
      <body>
        <h1>In SSE App</h1>
        <section style="height: 100px; width: 300px; background-color: antiquewhite;">
        <ul style="list-style-type:disc">
          <li> Stock1 Price : <span id="first-element"></span></li>
          <li >Stock2 Price : <span id="second-element"></span></li>
        </ul>
        <div id="time"></div>
    
        </section>
    
        <script>
          const eventSource = new EventSource('/sse')
          eventSource.onmessage = (event)=>{
            const resObject = JSON.parse(event.data)
            const firstElement = document.getElementById('first-element')
            firstElement.innerText = `${resObject.stock1Rate}`
            const secondElement = document.getElementById('second-element')
            secondElement.innerText = `${resObject.stock2Rate}`
            const timeElement = document.getElementById('time')
            timeElement.innerText = `${resObject.currentTime}`
          }
        </script>
      </body>
      </html>
    
    ๐Ÿ’ก
    Note: I am adding the Backend code for better understanding

Let us implement a simple Backend API to serve us stock prices at an interval of 5 seconds.

const express = require("express");
const {join} = require('node:path')

const PORT = 3010
const app = express()

app.use(express.static("public"));

app.get("/sse",(req, res)=>{
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Connection','keep-live');
  res.setHeader('Cache-Control', 'no-cache');

  const intervalId = setInterval(() => {
    const stock1Rate = Math.floor(Math.random() * 30000);
    const stock2Rate = Math.floor(Math.random() * 40000);
    const currentTime = new Date().toLocaleTimeString()
    res.write(`data: ${JSON.stringify({currentTime,stock1Rate, stock2Rate})} \n\n`)
  }, 5000);

  req.on('close', ()=>{
    clearInterval(intervalId)
  })

})

app.get("/", (req, res) => {
  res.sendFile(join(__filename, "/index.html"));
});

app.listen(PORT,()=>{
  console.log(`App is connected to ${PORT}`)
})

In the UI the stock prices will change after each 5sec -

stock price listing application

You can see how the response is received in the browser-

response received from server

Challenges that we may face while implementing

  1. Browser compatibility

  2. Connection limit

  3. Connection timeout

  4. Background tab behavior

  5. Resource utilization

  6. Load balancer

  7. Sticky connection

  8. Proxy/Firewall

I have tried to explain all the details of Server Sent Event that I know.

Thanks For Reading, Follow Me For More

ย