๐—” ๐—ฅ๐—ฒ๐—ฎ๐—น-๐—ง๐—ถ๐—บ๐—ฒ ๐—™๐—ฒ๐—ฎ๐˜๐˜‚๐—ฟ๐—ฒ ๐—œ ๐—•๐˜‚๐—ถ๐—น๐˜ ๐—ง๐˜„๐—ถ๐—ฐ๐—ฒ

I built the same feature two times.

The first time, I used WebSockets. I wanted a dashboard to update without a page refresh. I followed the common advice. WebSockets are the standard for real-time updates.

But WebSockets required a lot of extra work. I had to write code for:

It worked, but it felt fragile.

Then I found EventSource.

EventSource is much simpler. The server keeps an HTTP response open. The browser treats it as a stream of events.

The browser handles the hard parts for me:

My hundreds of lines of WebSocket code became five lines of code.

I learned a hard lesson about choosing tools. Before you start, ask yourself one question:

Which direction is the data flowing?

If the server only needs to send updates to the client, do not use WebSockets. WebSockets are for two-way communication like chat apps or multiplayer games.

If you only need one-way updates like notifications or logs, use EventSource.

Stop building complex systems for simple problems. Spend ten minutes thinking about your data flow before you write a single line of code.

Source: https://dev.to/dip_032d2fe1959e1990ddbb1/a-real-time-feature-i-built-twice-4l6d