JAVASCRIPT

Consume Real-time Data with Server-Sent Events (SSE)

Implement a client-side solution to receive continuous, real-time data streams from an API using Server-Sent Events for live updates and notifications.

function subscribeToSSE(url, onMessageCallback, onErrorCallback) {
  if (!window.EventSource) {
    console.error('Server-Sent Events are not supported in this browser.');
    onErrorCallback('Browser does not support SSE.');
    return;
  }

  const eventSource = new EventSource(url);

  eventSource.onopen = () => {
    console.log('SSE connection opened.');
  };

  eventSource.onmessage = (event) => {
    // The data property contains the message content as a string
    try {
      const data = JSON.parse(event.data);
      onMessageCallback(data);
    } catch (e) {
      console.warn('Could not parse SSE message as JSON:', event.data);
      onMessageCallback(event.data); // Pass raw string if not JSON
    }
  };

  eventSource.onerror = (error) => {
    console.error('SSE Error:', error);
    onErrorCallback(error);
    eventSource.close(); // Close connection on error or if no auto-reconnect needed
  };

  // Optional: Listen for custom events defined by the server
  // eventSource.addEventListener('customEventName', (event) => {
  //   console.log('Custom event received:', JSON.parse(event.data));
  // });

  return eventSource; // Return the EventSource instance for closing later if needed
}

// Example usage:
const sseSource = subscribeToSSE(
  'https://api.example.com/stream-updates', // Replace with your SSE endpoint
  (data) => {
    console.log('Received real-time update:', data);
    // Update your UI with the new data
  },
  (error) => {
    console.error('SSE subscription error:', error);
  }
);

// To close the connection later (e.g., when a component unmounts):
// setTimeout(() => {
//   sseSource.close();
//   console.log('SSE connection closed after 30 seconds.');
// }, 30000);
How it works: This JavaScript snippet shows how to subscribe to a Server-Sent Events (SSE) stream using the `EventSource` API. SSE provides a unidirectional, persistent connection from a server to a client, ideal for pushing real-time updates like notifications or live data feeds without the overhead of WebSockets. The `onmessage` handler processes incoming data, typically JSON, while `onopen` and `onerror` manage connection lifecycle events.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs