DEV Community

Dharan Ganesan
Dharan Ganesan

Posted on

Day 80: Server-Sent Events

What are Server-Sent Events? πŸ’‘

Server-Sent Events is a technology that enables servers to push data to web clients over a single HTTP connection. It's a simple and efficient way to send real-time updates from the server to the browser. SSE is often compared to WebSockets, but it has some unique features that make it suitable for certain use cases.

How SSE Works πŸ”„

SSE uses a simple text-based protocol. The server sends a stream of text data to the client over a single HTTP connection. The client opens a connection to the server and keeps it open, allowing the server to send updates whenever they're available. The server specifies a content type of text/event-stream in the response, and the data is sent as a series of events.

Here's an example of an SSE event:

data: Hello, world!
id: 1
Enter fullscreen mode Exit fullscreen mode
  • The data field contains the actual message.
  • The id field is optional but can be used for event identification or resynchronization.

Implementing SSE

Server-Side Implementation (Node.js)

Let's look at how to implement SSE on the server side using Node.js and Express:

import express from 'express';
const app = express();
const port = 3111;

app.get('/events', (req, res) => {
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');

  const sendEvent = (data) => {
    res.write("data: "+ data + "\\n\\n");
  };

  // Simulate real-time updates
  setInterval(() => {
    const timestamp = new Date().toLocaleTimeString();
    sendEvent("Server time: " + timestamp );
  }, 1000);
});

app.get('/', (req, res) => {
    res.send('Welcome to SSE! πŸ₯³');
});

app.listen(port, () => {
    console.log(\`App is live at http://localhost:\${port}\`);
});
Enter fullscreen mode Exit fullscreen mode

Client-Side Implementation

The client can establish a connection using the EventSource API:

const eventSource = new EventSource('/events');

eventSource.onmessage = (event) => {
  console.log('Received:', event.data);

  // Handle the received data
  // Update the UI or perform any other action
};
Enter fullscreen mode Exit fullscreen mode

In this code snippet, we create a new EventSource instance that connects to the server's SSE endpoint. When the server sends an event, the onmessage callback is triggered, and you can handle the data as needed.

Use Cases 🌐

SSE is an excellent choice for several use cases:

  1. Real-time Feeds: You can use SSE to implement real-time news feeds, social media updates, or sports scores.

  2. Notifications: It's great for sending instant notifications to clients, such as chat messages or new email alerts.

  3. Live Updates: SSE can be used to provide live updates of data, like stock prices or weather information.

  4. Long-Polling Alternative: SSE is a more efficient alternative to long-polling, where the client repeatedly polls the server for updates.

Tips πŸ’‘

Here are some tips for working with SSE:

  1. Error Handling: Handle errors and reconnect to the server if the connection is lost.

  2. Retry Mechanism: Implement a retry mechanism to handle temporary network issues.

  3. Keep-Alive: Use the ping field to keep the connection alive and detect when it's lost.

  4. Event IDs: Use the id field to keep track of events for resynchronization or deduplication.

  5. Security: Be cautious of security issues. Ensure that your SSE endpoint is secure and properly authenticated.

Top comments (1)

Collapse
 
dhrn profile image
Dharan Ganesan • Edited