Staying ahead in the ever-changing field of web development entails embracing technologies that enable real-time communication between clients and servers. Server-Sent Events (SSE) is one such technology that has gained traction. When used in conjunction with Node.js, SSE opens up a new world of possibilities for developing responsive, interactive, and data-driven online apps. In this blog post, we will dive into SSE with nodejs using express
What is SSE?
SSE is a straightforward and efficient technique for transmitting real-time changes from the server to the client using a single HTTP connection.
SSE enables the server to deliver changes to the client as soon as they become available, reducing the need for constant polling or complicated WebSocket configurations. This technology is suitable for providing real-time updates, such as news feeds, sports scores, or monitoring systems.
We can delete the short polling strategy (making requests from the front end at regular intervals).
SSE Format
- Event— The” event ” field is optional and used to specify the type of event being sent.
- Data— The “ data ” field consists of the payload of the event. Multiple “data” lines, each representing a different piece of data, can be inserted within a single SSE message.
- Id— The “ id ” field is optional and can be used to assign a unique identifier to the event. This can assist clients in keeping track of which events they have received.
- Retry— The “retry” field is also optional and specifies the reconnection time (in milliseconds) that the client should wait before attempting to reconnect if the connection is lost.
event: myEvent
data: This is some data
data: More data for the event
id: 123
Server Side Implementation
Create a server.js file in your root directory.
const express = require('express')
const app = express()
const cors = require("cors")
app.use(cors())
app.use(express.json())
function serverSentEevnts(req, res) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
})
let sseId = new Date().toLocaleDateString()
//in regular interval it needs to be sent
setInterval(() => {
writeServerSendEvent(res, sseId, (new Date()).toLocaleTimeString());
}, 5000)
writeServerSendEvent(res, sseId, (new Date()).toLocaleTimeString());
}
function writeServerSendEvent(res, sseId, data) {
res.write('id: ' + sseId + '\n');
res.write("data: new server event " + data + '\n\n');
}
app.get("/talk", (req, res) => {
serverSentEevnts(req, res)
})
app.listen(5000, () => {
console.log("starting port on 5000")
})
Client Side Implementation
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<input type="button" id="stopButton" value="Stop Listening"/>
<hr/>
<div id="content"></div>
<script>
var source = new EventSource('http://localhost:5000/talk');
source.addEventListener('open', function(e) {
document.getElementById('content').innerHTML += 'Connections to the server established..<br/>';
}, false);
source. {
document.getElementById('content').innerHTML += e.data + '<br/>';
};
document.getElementById('stopButton').
document.getElementById('content').innerHTML += 'Listening to server events stopped..<br/>';
source.close();
}
</script>
</body>
</html>
Mention this in the package.json file to run it locally.
"scripts": {
"start": "http-server -p 8080"
},
You should be able to open http://localhost:8080 in your browser and watch the events. Pressing the button should stop listening to the server send events.
By now you will be able to see a successful working model of SSE in nodejs
I’ll keep on adding more topics as I learn.Thankyou
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