Server-sent events (SSE) are similar to instant messaging between a server and a web application. Imagine you are sitting in front of a vending machine that dispenses candy. You tell the vending machine that you want a piece of candy by pressing a button. The vending machine sees this and sends you a piece of candy. SSE works in the same way.
In SSE, your computer sends a message to a server asking for information (like updates for a website) and the server agrees to send you that information automatically whenever there is a change. You could ask a server for information every few seconds, but this would create a lot of traffic and could slow down the server. SSE only sends new information when something changes, and this makes it very efficient.
A good example of SSE is a chat application. A user sends a message to their friend, and the friend’s computer receives the message in real-time, thanks to SSE. When the server recognizes a new message, it sends the update immediately, meaning the friend’s computer knows there is a new message when it is sent.
SSE works through a technology called “Event Stream.” The server creates a connection to the web page, and it begins to stream data to the page as soon as there is a new update. The server then sends the update, followed by two line breaks. This process continues until the connection is closed or there are no more updates.
SSE is useful when you need to have instant updates or want to build a real-time application, where users can interact with each other. Instead of constantly polling the server for updates, SSE allows you to reduce the number of requests to the server and get instant updates when there has been a change.