Simplify Real-Time Data Streaming with EventSource API

Simplify Real-Time Data Streaming with EventSource API

Ever wanted to send real-time updates to users without bombarding them with constant page refreshes? Whether it’s live sports scores, stock market data, or fresh comments on a blog post, users expect instant updates. Enter the EventSource API, a powerful yet simple tool for pushing live data from the server to the browser.

Unlike WebSockets, which allow for two-way communication, EventSource (or Server-Sent Events, SSE) is one-way: the server sends messages to the client. It’s like having a continuous stream of data flowing to the browser—perfect for scenarios like live feeds or notifications.

Why Choose EventSource?

If you need real-time updates but don’t require the complexity of WebSockets, EventSource might be just what you need. It’s lightweight, built into modern browsers, and it only requires basic setup to get started.

Let’s explore how you can use it with a real-world example, like a live stock ticker that updates every few seconds.

Real-World Example: A Stock Ticker

Imagine you’re building a stock-tracking application. Instead of having users refresh their page every minute to get the latest stock prices, you can use EventSource to keep them updated in real-time. The stock prices will automatically stream in as soon as they change on the server.

How It Works:

  1. Client Side: The browser (client) opens a persistent connection to the server via EventSource.

  2. Server Side: The server sends updates over that connection, and the client listens for those updates to display in real-time.

Let’s Code It!

We’ll use Node.js on the server and basic JavaScript on the client side. Here’s the breakdown:

1. Initialise Node.js Project & Install Express

npm init -y && npm install express

2. Server-Side (Node.js + Express)

The server needs to send real-time updates to the client. We’ll set up an endpoint that streams data every second.

// server.js
const express = require('express');
const app = express();

// Simulate stock prices
let stockPrices = {
  'AAPL': 145.30,
  'GOOG': 2735.21,
  'AMZN': 3451.48,
};

app.get('/events', (req, res) => {
  // Set headers to tell the browser we're sending events
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.flushHeaders();  // Send headers immediately

  // Every 2 seconds, simulate a stock price update
  setInterval(() => {
    // Randomly update stock prices
    for (let symbol in stockPrices) {
      stockPrices[symbol] += (Math.random() - 0.5) * 5; // small random change
    }

    // Send updated stock prices to the client
    res.write(`data: ${JSON.stringify(stockPrices)}\n\n`);
  }, 2000); // Every 2 seconds
});

app.listen(3000, () => console.log('Server running on port 3000'));

3. Client-Side (HTML + JavaScript)

On the client side, we’ll create an EventSource object that connects to the /events endpoint and listens for new stock data.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Live Stock Ticker</title>
</head>
<body>
  <h1>Live Stock Prices</h1>
  <div id="stocks"></div>

  <script>
    // Connect to the server-side event stream
    const eventSource = new EventSource('http://localhost:3000/events');

    eventSource.onmessage = function(event) {
      // Parse the incoming stock prices and display them
      const stockPrices = JSON.parse(event.data);
      let displayText = "<ul>";
      for (let symbol in stockPrices) {
        displayText += `<li>${symbol}: $${stockPrices[symbol].toFixed(2)}</li>`;
      }
      displayText += "</ul>";
      document.getElementById('stocks').innerHTML = displayText;
    };
  </script>
</body>
</html>

Why Use EventSource Instead of WebSockets?

While WebSockets are great for two-way communication, EventSource offers some advantages when you only need one-way communication, like live feeds or notifications. Here’s why:

  • Simplicity: EventSource is easier to set up than WebSockets. The API is simple, and you don’t need to worry about handshakes, closing connections, or managing message protocols.

  • Automatic Reconnection: If the connection drops, EventSource automatically tries to reconnect. This saves you from having to manually handle connection retries, which is a common task in WebSocket applications.

  • Efficient for One-Way Communication: EventSource is optimized for sending a continuous stream of data from the server to the client. It’s less resource-intensive than WebSockets, especially for use cases like live updates where you don’t need to send data back to the server.

  • Built-in Browser Support: Modern browsers support EventSource natively, so you don’t need to worry about compatibility issues. WebSocket support is widespread, but older browsers might require a polyfill.

When to Use EventSource vs. WebSockets

  • Use EventSource: When you need one-way communication from the server to the client (e.g., live updates, notifications, live scores).

  • Use WebSockets: When you need two-way communication (e.g., multiplayer games, chat applications).

Final Thoughts

EventSource might not be the perfect fit for every real-time app, but it’s an excellent choice for scenarios where you want to stream updates to users without the overhead of complex WebSocket connections. By using EventSource, you can build lightweight, real-time applications that deliver fresh data with minimal effort.

Try out the example above for a simple live stock ticker. It’s a great way to get started with EventSource and see how it can power real-time updates in your web apps!