Intro
There is this thing called Server Sent Events I didn’t know existed before. Everyone knows WebSockets that we use if we want some data stream between the client and the server, but what if we needed a unidirectional data flow with the client automatically reconnecting to the server in case the network had gone and got back up again? Will take some hassle with Websockets, wouldn’t it? That’s pretty much where SSE wins the day.
Basically, on the client side, it is all about the EventSource object. It provides the number of event handlers to subscribe to in order to control the data stream it receives from the server.
On the server side, it is the way you set up your API, response headers, and the data, which has to be in a certain format in order to work.
Briefly, THAT’S IT. Simple as that.
What’s EventSource?
EventSource - is an object that creates a persistent connection to the HTTP server and automatically tries to reconnect if the network drops.
The EventSource provides the following API to work with:
- Events:
- open – fires an event when the connection to the server is established
- message - fires event when a message is received from the server
- error - fires an event when something went wrong on the server and a message could not be sent (or something bad happened)
- Properties:
- url - return the current url of the server we’re connected to
- readyState - the connection status number. There are only three of them:
- 0 meaning CONNECTING
- 1 meaning OPEN
- 2 meaning CLOSED
- withCreadentials - a boolean value that turns to true if CORS credentials were passed in, and false if not.
- Method
close()that closes the established connection to the server. Data stream fetching ends here.
That’s it. Now we’re ready to write some client code.
Client
The client code would look something like this:
useEffect(() => {
// First, we need to create an instance of EventSource and pass the data stream URL as a
// parameter in its constructor
const es = new EventSource("/api/sse");
// Whenever the connection is established between the server and the client we'll get notified
es.onopen = () => console.log(">>> Connection opened!");
// Made a mistake, or something bad happened on the server? We get notified here
es.onerror = (e) => console.log("ERROR!", e);
// This is where we get the messages. The event is an object and we're interested in its `data` property
es.onmessage = (e) => {
console.log(">>>", e.data);
};
// Whenever we're done with the data stream we must close the connection
return () => es.close();
}, []);
The client job is done. Easy as this. Now, what’s happening on the server?
Server
As for the server side, there are several important rules to follow:
- Server headers must contain text/event-stream content type. This is required for the SSE to work
- Server must keep the connection alive. The
keep-alive'connection header is required. - Make sure your encoding headers are what the client wants. At leave the Chrome browser expects the content with content encoding gzip. So, we must either gzip the content ourselves or disable the content encoding with corresponding headers -
'Content-Encoding': 'none'
Check the code snippet below. For my example, I used Node.js (in the context of Next.js. Because it’s easy), but this can be equally easily implemented in any language.
import { NextApiRequest, NextApiResponse } from "next"
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
res.writeHead(200, {
//For this example, lets allow access to all the origins, since we;re not sending any credentials
'Access-Control-Allow-Origin': '*',
// This is important. We must keep the connection alive to let data stream do its thing
'Connection': 'keep-alive',
// Another important line. The 'text/event-stream' content type is mandatory for SSE to work
'Content-Type': 'text/event-stream; charset=utf-8',
// No use for caching since we're continuously getting new data
'Cache-Control': 'no-cache',
// By default, browsers compress the contents with `gzip` and we either have to gzip our content
// ourselves or not do any encoding at all. I chose the latter, our payload is light anyway.
'Content-Encoding': 'none',
})
// Here we see the specific data format, that supports passing in the data and some connection options.
// The message must end with \n\n, each property is separated by \n
const getData = () => `retry: 5000\ndata: Current date is ${Date.now()}\n\n`
let timer: ReturnType<typeof setInterval>
res.write(getData())
timer = setInterval(() => res.write(getData()), 3000)
}
Data Format
Apart from the data itself, there are some options we can send from the server as part of the event payload.
retry- the amount of time in ms to start reconnecting. In the code snipped above the reconnection attempt will start every 5 seconds.
event- Custom event name. Useful if we want to send different data with multiple events which we have to name in some way. It is important to remember that with the named events we should use
addEventListenerto listen to their events, unlike theonmessagehandler which delivers data if there are no named events sent from the server.
- Custom event name. Useful if we want to send different data with multiple events which we have to name in some way. It is important to remember that with the named events we should use
With named events, the data string will look something like this:
const getData = () => `event: custom\ndata: Current date is ${Date.now()}\n\n`
And we would subscribe to it like this:
es.addEventListener("custom", (e) => console.log(e.data));
id- The unique event id. Appears as the last event id in the
EventSource.
- The unique event id. Appears as the last event id in the
NOTE: It is also fine to use JSON as a data payload. You then regularly JSON.parse it on the client to get the object.
// Server
res.write(`event: custom\ndata: {"date": "${Date.now()}", "randomDigit": "${Math.random()}"}\n\n`)
// Client
es.addEventListener("custom", (e) => {
console.log(JSON.parse(e.data));
});
Pros and cons
SSE is great for:
- Unidirectional data flow from the server to the client
- Automatic reconnect mechanism in case the network went down. No efforts required
- Easy to get it working
- Client API is simple and easy to work with
- Data is sent over a standard HTTP protocol
- Great browsers support
SSE also has some weak spots:
- The amount of opened connections (if using regular HTTP) is limited to crazy low 6 connections per browser. This essentially means that this number is even lower if you have to support the app opened in multiple tabs
- Obviously is not suitable for building bi-directional communication channels between the client and the server
- Only supports UTF-8 charactes. Does not support binary data
Conclusion
Server Sent Events is a great way to solve the problem the easy way, with no hassle and unnecessary complications. With the minimum required configuration, it allows to create a unidirectional data stream between the server and the client via the standard HTTP protocol and automatically restore the lost connection. It’ll be a great choice for simple string data transfer.
Bonus
I created some playground to see how this tech works. The query interval is limited to only 10 quries to not abuse a free API server with data.