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

Subham DashSubham Dash
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

0
Subscribe to my newsletter

Read articles from Subham Dash directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Subham Dash
Subham Dash

๐Ÿ‘‹ Hey there! I'm Subham Dash, a front-end developer passionate about crafting intuitive user experiences with React. With a solid foundation in JavaScript and TypeScript, I have expertise in building dynamic and responsive web applications. ๐Ÿ› ๏ธ In my toolkit, you'll find a diverse set of skills and technologies. I possess hands-on experience ranging from backend development using Express and Node.js, to containerization utilizing Docker. Additionally, I have worked on CircleCI and AWS. โšก๏ธ When it comes to testing, I'm all about ensuring quality and reliability. I dive into automation testing with Selenium and Cypress, ensuring seamless user experiences across all platforms. ๐Ÿ’ป Outside of coding, I enjoy exploring the world of databases with SQL, and MongoDB and mastering version control with Git. Continuously learning and growing is my mantra, and I'm always excited to dive into new challenges and technologies. ๐ŸŒŸ Let's connect and share our experiences in frontend development, React, and beyond. Feel free to reach out for discussions, collaborations, or just to geek out about tech. Happy coding! ๐Ÿš€๐Ÿ˜Š๐Ÿš€