Server Sent Events (SSE) Streams with Node and Koa

David Barral
Aug 17 · 4 min read
Image for post
Image for post
Photo by Mathew Schwartz on Unsplash

When you want to have real time updates on a web application, you can rely on old-fashioned periodic polling or try to use some push capable modern technology. Your first impulse may be using WebSockets. However, if you just want to receive data from the server you can use Server Sent Events.

Traditionally, a web page has to send a request to the server to receive new data; that is, the page requests data from the server. 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.

You can check this post to see the difference between SSE and Websocket and make your own opinion of when to use one or the other. For my use case, receiving updates from the server periodically, I will stick to SSE.

SSE basics with Koa

  • It will have a catch all route that responds with a 200 status.
  • It will have a /sse endpoint that, upon receiving a request, will make sure our connection stays open by adjusting some socket params and return the appropriate HTTP headers to start a new SSE stream.
  • We will create a new PassThrough stream (a stream that simply passes the input bytes across to the output) and pass it as our response body.
  • Lastly we will generate a data feed using a simple interval that will periodically write the current timestamp to the stream; therefore, pushing that data across the open connection to the client.

Notice two things: first, the output data must conform to the SSE format. Second it’s mandatory to return a stream as the body response to ensure that Koa does not close the connection. You can dig in the Koa source code (check this method) to see how Koa handles the response. If you take a look you’ll see that Koa will send the body content to the HTTP response stream unless you use another stream as the body. In that case it will pipe the streams; therefore, the response stream won’t be closed until we close our PassThrough stream.

To test our SSE stream in the browser we should use the EventSource API.

Visit http://localhost:8080 in your browser, open a console and drop the following snippet to consume the server messages.

Closing the stream

We have to be careful when dealing with closures, in this case our stream. Our interval does not know that it has to stop feeding data to the stream.

To solve it, we can attach ourselves to the stream close event and “unsubscribe” from the data feed.

Broadcasting data

We can add a simple EventEmitter and move the data generation outside of the connection code to see how this could work.

Formatting the stream data

  • The transformer (line 5) will convert objects into SSE text format.To simplify the example, we will just handle data only messages (line 13).
  • Our data feed will emit a data object with a timestamp key (line 22).
  • Our event listeners will write the raw data to the transformer (line 46).

We also have to make a minor adjustment to our client to process the new JSON formatted data.

Summing up

As I mentioned at the beginning of this story, when dealing with server to client unidirectional communication you can choose between websockets and Server Sent Events. Each one has pros and cons. Learn both of them and choose the one that fits your problem.

Trabe

We are a development studio.

Thanks to Roman Coedo and Ceci García García

David Barral

Written by

Co-founder @Trabe. Developer drowning in a sea of pointless code.

Trabe

Trabe

We are a development studio. We use Java, Rails, and JavaScript. This is where we write about the technologies we use at Trabe.

David Barral

Written by

Co-founder @Trabe. Developer drowning in a sea of pointless code.

Trabe

Trabe

We are a development studio. We use Java, Rails, and JavaScript. This is where we write about the technologies we use at Trabe.

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