Building with server-sent events with React and Node.js
Tags: webdev, node, react, javascript
Published: 2020-06-09 04:17:03

**This post is a mirror of a post I wrote on my own blog. If you would like python or native javascript examples of the code I presented below, feel free to [check it out here ](https://docs.shub.club/web-tips/server-sent-events)** 

Building real-time applications on the web has never been easier. In this post, I'll explain how you can use **server-sent events**, or **SSE** for short, to get real-time data for your web applications. 

At the end of this article you should know:

* What a server-sent event is
* How to listen to server-sent events on the browser
* How to send server-sent events from your server

This tutorial is for those who have some familiarity with developing on the web as well as some knowledge in either python or nodejs.

![A light-hearted illustration of how SSE events work](https://shub.sfo2.digitaloceanspaces.com/docs/web-tips/server-sent-events/sse-demo.gif)

## The gist
Server-sent events (SSE) are a client initiated, unidirectional, server controlled messages. When you visit a website that queries an SSE-enabled endpoint, the server can send your browser unlimited amounts of information until you leave that page. SSE urls are always accessed via an asynchronous request from your browser. You can visit a url that serves an SSE endpoint from your browser but there is no standard on what you will experience.

```javascript
const source = new EventSource('/an-endpoint');

source.onmessage = function logEvents(event) {
   console.log(JSON.parse(data));
}
```

In this code snippet, I create a new `EventSource` object that listens on the url  `/an-endpoint`. `EventSource` is a helper class that does the heavy lifting of listening to server-sent-events for us. All we need to do  now is to attach a function, in this case `logEvents`, to the `onmessage` handler. 

Any time our server sends us a message, `source.onmessage` will be fired.

Let's look at a more realistic example. The code below listens on a server at the url `https://ds.shub.dev/e/temperatures`. Every 5 seconds, the server returns a server-sent event with the temperature of my living room.

```jsx

// @codepen-link:https://codepen.io/4shub/pen/QWjorRp
import React, { useState, useEffect } from 'react';
import { render } from "react-dom";

const useEventSource = (url) => {
    const [data, updateData] = useState(null);
    
    useEffect(() => {
        const source = new EventSource(url);
    
        source.onmessage = function logEvents(event) {      
            updateData(JSON.parse(event.data));     
        }
    }, [])

    return data;
}

function App() {
  const data = useEventSource('https://ds.shub.dev/e/temperatures');
  if (!data) {
    return <div />;
  }

  return <div>The current temperature in my living room is {data.temperature} as of {data.updatedAt}</div>;
}

render(<App />, document.getElementById("root"));
```


### What's happening behind the scenes?
![A diagram showing the steps of an event source request](https://shub.sfo2.digitaloceanspaces.com/docs/web-tips/server-sent-events/sse-diagram.png)

Let's look at these two properties of EventSource:
* `url` - The url that we want to listen on for changes
* `readyState` - The state of the connection. This can be `(0) CONNECTING`, `(1) OPEN` and `(2) CLOSED`. Initially this value is `CONNECTING`.

When EventSource is invoked, the browser creates a request with the header `Accept: text/event-stream` to the `url` that was passed through. 

The browser will then verify if the request returns a `200 OK` response and a header containing `Content-Type`: `text/event-stream`. If successful, our `readyState` will be set to `OPEN` and trigger the method `onopen`. 

The data from that response will then be [parsed](https://html.spec.whatwg.org/multipage/server-sent-events.html#parsing-an-event-stream) and an event will be fired that triggers `onmessage`.

Finally, the server we pinged can send us an unlimited amount of `event-stream` content until:
 * We close our page
 * We fire the `close()` method on event source
 * The server sends us an invalid response

When we finally close our connection, the `EventSource` object's `readyState` will fire a task that sets `readyState` to `CLOSED` and trigger the `onclose` event.

In case of a network interruption, the browser will try to reconnect until the effort is deemed "futile," as determined by the browser (unfortunately, there are no standards on what constitutes "futile").

## Sending events on the server
Sending server-sent events is just as easy as listening to them. Below, I've written a few different implementations of sending server-sent events to your client.


```javascript
// @repl-it-link:https://repl.it/@4shub/server-sent-events-node
const express = require('express');

const server = express();
const port = 3000;

// create helper middleware so we can reuse server-sent events
const useServerSentEventsMiddleware = (req, res, next) => {
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');

    // only if you want anyone to access this endpoint
    res.setHeader('Access-Control-Allow-Origin', '*');

    res.flushHeaders();

    const sendEventStreamData = (data) => {
        const sseFormattedResponse = `data: ${JSON.stringify(data)}\n\n`;
        res.write(sseFormattedResponse);
    }

    // we are attaching sendEventStreamData to res, so we can use it later
    Object.assign(res, {
        sendEventStreamData
    });

    next();
}

const streamRandomNumbers = (req, res) => {
    // We are sending anyone who connects to /stream-random-numbers
    // a random number that's encapsulated in an object
    let interval = setInterval(function generateAndSendRandomNumber(){
        const data = {
            value: Math.random(),
        };

        res.sendEventStreamData(data);
    }, 1000);

    // close
    res.on('close', () => {
        clearInterval(interval);
        res.end();
    });
}

server.get('/stream-random-numbers', useServerSentEventsMiddleware, 
    streamRandomNumbers)


server.listen(port, () => console.log(`Example app listening at 
    http://localhost:${port}`));
```

In the example above, I created a server with an event-stream that sends users a random number every second.

## Conclusion
Many companies use server-sent events to pipe data to their users in real time. LinkedIn uses server sent events for their [messaging service](https://engineering.linkedin.com/blog/2016/10/instant-messaging-at-linkedin--scaling-to-hundreds-of-thousands-), Mapbox uses SSE to [display live map data](https://www.mapbox.com/solutions/real-time-maps), and many analytics tools use SSE to show real-time user reports. SSE will only become more prominent as monitoring tools and real-time events become more relevant to users. 

Let me know if you try it out — I'd love to see what you come up with!