Server-Sent Events (SSE)
Tags: webdev
Published: 2022-12-17 18:39:39

When working on real-time projects, it is often necessary to send messages or updates from the server to the client. There are three main ways to achieve this: client polling, WebSockets, and Server-Sent Events (SSE). Each of these methods has its own advantages and disadvantages, and the best choice will depend on the specific needs of the project. Client polling involves the client repeatedly requesting updates from the server at regular intervals, while WebSockets and SSE allow the server to send updates to the client as they become available.
<br/>
## **So, what is Server-Sent Events design pattern?**


Server-Sent Events (SSE) is a way for a server to send notifications, messages, or events to a client (or multiple clients) over an HTTP connection. It involves the use of the JavaScript EventSource API, which allows a client to request a stream of data from a specific URL. The server can then send updates or continuous streams of data to the client through this connection. SSE is often used to send real-time updates or data to a web browser.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qjhw9f59scdkszodf1lo.png)

<br/>
## Getting started with Server-Sent Events

In this section, we will explore how to use Server-Sent Events (SSE) by setting up a simple server using the Express framework and connecting to it from a browser using the EventSource API. We will experiment with SSEs and see how they work in practice.



#### Creating SSE Server 


```ts
const express = require("express");
const app = express();
const port = 5003;

function send (res, counter) {
    res.write("data: " + `message ---- [${counter}]\n\n`);
    setTimeout(() => send(res, counter+1), 2000);
}

app.get("/stream", (req,res) => {
    res.setHeader("Content-Type", "text/event-stream");
    var counter = 0;
    send(res, counter);
})

app.listen(port,() => {
    console.log(`Listening on ${port}`)
})
```

This code sets up an HTTP server using the Express framework. The server listens for incoming HTTP requests on port 5003 and responds to requests for the "/stream" route by sending a series of messages to the client.

The server uses the "Content-Type" header to specify that it is sending an event stream to the client, and the "send" function is used to send a message to the client at regular intervals (every 2 seconds). The message contains a counter value that is incremented each time a message is sent.
<br/>
##Using SSE In The Browser


```ts
const sse = new EventSource("http://localhost:5003/stream");

sse.addEventListener('message', event => {
    console.log(event.data);
});
```

This code creates a new EventSource object and connects it to the "/stream" route on the server at "http://localhost:5003". The EventSource object establishes a connection with the server and listens for events sent by the server.

The code also registers an event listener for the "message" event, which is triggered when a message is received from the server. The event listener logs the message data to the console.

In this case, the server is expected to send a series of messages to the client at regular intervals, and the event listener will be triggered for each message received. The client will log the message data to the console, allowing you to see the messages being sent by the server.

Now Let's take a look at the console 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ukdqkj6qfj6c60agclq5.png)


**Bingo!!**
As expected we are receiving the stream from our sse server (no polling is required). 
<br/>

##Server-Sent Events Advantages: 

Server-Sent Events (SSE) can be used in browsers that do not natively support them by using a JavaScript polyfill, which can be useful for maintaining backwards compatibility. Additionally, SSE connections will automatically reconnect after being lost, saving developers the effort of implementing this behavior themselves. Lastly, SSEs are less likely to be blocked by corporate firewalls, making them a good choice for use in enterprise settings.
<br/>

##Server-Sent Events Disadvantages: 

Server-Sent Events (SSE) have some limitations that may make them less suitable for certain types of applications. These limitations include:

- Data format: SSE can only transport UTF-8 messages, and does not support binary data.


- Concurrent connections: A browser can only have a limited number of concurrent SSE connections (usually six) at any one time due to the behavior of http1 protocol. This can be a problem when you want to open multiple tabs with SSE connections. However, you can overcome this problem by using SSE design pattern over http2 instead of http1.


- Directionality: SSE is a one-way communication channel, meaning that you can only send messages from the server to the client. While this is useful for creating read-only real-time apps like stock tickers, it can be limiting for other types of real-time applications that require bidirectional communication.