Server-Sent Event
Introduction

With server-sent events, it's possible for a server to send new data to a web page at any time, by pushing messages to the web page. These incoming messages can be treated as Events + data inside the web page.
It is similar with web socket, but 1-way direction, from server to client
You'll need a bit of code on the server to stream events to the front-end, but the client side code works almost identically to websockets in part of handling incoming events.
Implementation
Backend
app.get('/', (req, res) => {
// Content Type must defined as text/event-stream
res.setHeader('Content-Type', 'text/event-stream');
let counter = 0;
const intervalId = setInterval(() => {
counter++;
// Write the event stream format
// the text must follow the below, including numbers of \n
res.write(`event:message\n data: Message ${counter}\n\n`);
}, 2000);
// When client closes connection, stop sending events
req.on('close', () => {
clearInterval(intervalId);
res.end();
});
});
Frontend
// declare the server source
const evtSource = new EventSource({apiUrl}, {
withCredentials: true,
});
// listen to the server message
evtSource.onmessage = (event) => {
const newElement = document.createElement("li");
const eventList = document.getElementById("list");
newElement.textContent = `message: ${event.data}`;
eventList.appendChild(newElement);
};
Reference
Last updated
Was this helpful?