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 SSE, 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
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
- Connection should be live
- 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 -
You can see how the response is received in the browser-
Challenges that we may face while implementing
- Browser compatibility
- Connection limit
- Connection timeout
- Background tab behavior
- Resource utilization
- Load balancer
- Sticky connection
- Proxy/Firewall
I have tried to explain all the details of SSE that I know.
Thanks For Reading, Follow Me For More
Top comments (1)
Great write up! Does anyone use Server-Sent Events in their projects? If yes, for which use cases? This video dives into the main building blocks of Server-Sent Events in Go.
youtu.be/nvijc5J-JAQ