You are viewing...

Today I Learned about Server Sent Events

Updated on November 09, 2020 at the 23th hour
Posted under:

DISCLAIMER: Expressed views on this blog are my own.

Started making a "real time" API for my productivity software. I wanted to figure out what is a good way to notify a user's browser that something happened or new popped up so that it would update the UI appropriately. Automations occur on the backend without user input, so the UI needs to know about those updates so it can give the user the latest information.

Two ways to go about it: Websockets or Server Sent Events. I have lots of experience with Websockets. It is bi-directional and requires a little more to get right. I have zero experience with Server Sent Events. it is unidirectional as in data flows from the server and requires little setup and easier to get going.

I know I do not need bidirectional flow of data since HTTP is used for user input. If I used Websockets then I would not have bothered with HTTP APIs. RPC over Websockets is not a bad thing to do. I digressed. SSE is structured from the get go (emit certain fields) while Websockets is more of a do whatever you want when it comes to incoming and outgoing data.

I'm honestly surprised how easy it is to setup SSE though. https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events

On the client side you got this EventSource class that you enter in your SSE url. On the server side, you have a library that plugs into your webserver and when a user connects via http on a the SSE route you can easily figure out who the user is and easily tailor the stream to that user without any complex code.

I use fastify as my web server which means I have fastify-sse-v2 (published to my own node package storage instead). On the route, subscribe to channel for user on EventEmitter and incoming events from EventEmitter to send events to the SSE connection. Really that simple.

You just read "Today I Learned about Server Sent Events". Please share if you liked it!
You can read more recent posts here.