by Timur Dautov

Understanding Server-Sent Events (SSE)

Server-Sent Events, a standard for unidirectional communication between a server and a web client over HTTP.

It allows servers to push updates to clients in real-time, making it ideal for applications like live notifications, real-time feeds, and updates.

Key Points of SSE#

  • Server-Sent Events are unidirectional, meaning the server can send data to the client, but the client cannot send data back to the server.
  • It uses standard HTTP instead of a custom protocol, making it simpler than alternatives like WebSocket. The server sends data with the "text/event-stream" content type.
  • SSE automatically reconnects if the connection is lost, making it reliable for real-time communication.
  • SSE sends data as a stream of events, which can be parsed on the client-side using JavaScript.

Common Use Cases#

  • Live Notifications: Notify users about new messages, updates, or events in real-time.
  • Real-time Feeds: Display real-time feeds like social media updates, news, or stock prices.
  • Updates and Alerts: Send updates and alerts to clients without the need for polling or manual refresh.

Example#

In this example, the server sends a JSON object with the current time every second. The client listens for messages and logs the received data to the console.

Server (Node.js)#

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

    // Send data periodically
    const intervalId = setInterval(() => {
        res.write(`data: ${JSON.stringify({ time: new Date() })}\n\n`);
    }, 1000);

    // Clean up on client disconnect
    req.on('close', () => {
        clearInterval(intervalId);
    });
});

Client (JavaScript)#

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

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

Comparison with WebSockets#

| Feature | SSE | WebSockets | | ------------------- | -------------------------- | ----------------------- | | Communication | One-way (server -> client) | Two-way (full-duplex) | | Protocol | HTTP | Custom TCP protocol | | Complexity | Simple | More complex | | Reconnection | Built-in | Needs to be implemented | | Binary Data Support | No | Yes |

Summary#

Server-Sent Events provide a simple and efficient way to push real-time updates from the server to the client. It is a lightweight alternative to WebSockets for applications that require unidirectional communication.

By using SSE, you can create real-time features like live notifications, feeds, and updates without the complexity of bidirectional communication.

References#