Implementing Server Sent Events in ReactJS

Helena Natanael
Oct 5 · 4 min read
Image for post
Image for post

Have you ever heard about Server Sent Events (SSE)? I first tried it when I was assigned to work on a project which required files processing in Tokopedia. After looking at the few first pages on Google to learn more about SSE, I realize that it’s the most suitable way to cater to Tokopedia users’ needs.

This article explains how to implement SSE using JavaScript in the Front-End. To have a fully working SSE, you will need to setup the Back-End that can be read in this article.

Case Overview

Image for post
Image for post
Communication flow between Server and Client using Server Sent Events. (Image Source: PubNub)

How to implement it?

const sse = new EventSource('[SSE_URL]', { withCredentials: true });

Event Source has some handlers: onerror, onmessage, and onopen. You can read more about it on the MDN website. In our use case, we only use onerror and onmessage.

The onerror handler is used to validate or log what causes error, then closes the connection using sse.onclose() method to prevent more errors and guide user to do actions that needed, e.g. retry to upload.

sse.onerror = () => {
// error log here
// after logging, close the connection
sse.close();
}

The onmessage handler is the heart of SSE usage. We can read the streams from Backend via this handler. As this handler needs some validations when reading and parsing data, I use a separate function to process the data I get and put it in the component’s state so I can render it or use it further in other functions.

function getRealtimeData(data) {
// process the data here
// pass it to state to be rendered
}
sse.onmessage = e => getRealtimeData(JSON.parse(e.data));

Last but not the least, don’t forget to invoke sse.close() for cleaning up the connection to Backend in your component to prevent memory leaks.

Here’s the complete code:

useEffect(() => {  const sse = new EventSource('[YOUR_SSE_ENDPOINT_URL]',
{ withCredentials: true });
function getRealtimeData(data) {
// process the data here,
// then pass it to state to be rendered
}
sse.onmessage = e => getRealtimeData(JSON.parse(e.data)); sse.onerror = () => {
// error log here

sse.close();
}
return () => {
sse.close();
};
}, [YOUR_DEPENDENCIES_HERE]);

Bonus: Here’s a preview of the progress bar that I implement in the Bulk Add page using SSE; you are welcome to try it if you have a shop in Tokopedia. 😄

Image for post
Image for post

Besides the progress bar, SSE can also be implemented in notification counter, a chat app, or any other use case that might need a realtime update from the server. Hopefully, you find this article useful and practical to implement SSE in your React Apps!

Tokopedia Engineering

Story from people who build Tokopedia

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store