How Server-Sent Events Works in HTML5?

Server-Sent Events (SSE) is an HTML5 technology that allows a web server to push data to a client automatically. Unlike traditional polling methods, SSE maintains a persistent connection where the server continuously sends updates to the client without requiring repeated requests.

How Server-Sent Events Work

Server-Sent Events establish a one-way communication channel from server to client. The client opens a connection to the server using the EventSource API, and the server keeps this connection alive to send real-time updates. This is particularly useful for live feeds, notifications, chat messages, and real-time data updates.

Server-Sent Events Flow Client (Browser) Server (PHP/Node) 1. Open EventSource connection 2. Continuous data stream 3. Real-time updates EventSource API text/event-stream

EventSource API Syntax

In modern HTML5, Server-Sent Events use the EventSource JavaScript API, not the deprecated <eventsource> element. Following is the correct syntax −

var eventSource = new EventSource('url');
eventSource.onmessage = function(event) {
    // Handle incoming data
    console.log(event.data);
};

The server must respond with the MIME type text/event-stream and format data according to the SSE specification.

Basic Server-Sent Events Implementation

Client-Side JavaScript Example

Following example demonstrates the proper way to implement Server-Sent Events using the EventSource API −

<!DOCTYPE html>
<html>
<head>
   <title>Server-Sent Events Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Live Server Time</h2>
   <div id="time-display" style="padding: 10px; border: 1px solid #ccc; background: #f9f9f9;">
      Connecting to server...
   </div>
   <button onclick="startSSE()" style="margin: 10px 5px 0 0;">Start</button>
   <button onclick="stopSSE()" style="margin: 10px 0 0 0;">Stop</button>

   <script>
      var eventSource;

      function startSSE() {
         if (eventSource) {
            eventSource.close();
         }
         
         // Note: This URL would need to point to your actual SSE endpoint
         eventSource = new EventSource('/sse-time.php');
         
         eventSource.onmessage = function(event) {
            document.getElementById('time-display').innerHTML = event.data;
         };
         
         eventSource.onerror = function(event) {
            document.getElementById('time-display').innerHTML = 'Connection error occurred';
         };
         
         eventSource.onopen = function(event) {
            document.getElementById('time-display').innerHTML = 'Connected to server';
         };
      }

      function stopSSE() {
         if (eventSource) {
            eventSource.close();
            document.getElementById('time-display').innerHTML = 'Connection closed';
         }
      }
   </script>
</body>
</html>

The example creates an EventSource connection to receive real-time server updates. The onmessage event handler processes incoming data, while onerror and onopen handle connection states.

Server-Side PHP Implementation

Following is a PHP script that sends server time every 2 seconds using the proper SSE format −

<?php
// sse-time.php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Access-Control-Allow-Origin: *');

while (true) {
    $time = date('Y-m-d H:i:s');
    
    // SSE format: data: [content]<br><br>
    echo "data: Current server time: $time<br><br>";
    
    // Flush output to client
    ob_flush();
    flush();
    
    // Wait 2 seconds before next update
    sleep(2);
    
    // Check if client disconnected
    if (connection_aborted()) {
        break;
    }
}
?>

Custom Event Types

Server-Sent Events support custom event types beyond the default message event. This allows different types of data to be handled by specific event listeners.

Example − Multiple Event Types

<!DOCTYPE html>
<html>
<head>
   <title>Custom SSE Events</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Multi-Event Server Updates</h2>
   <div id="notifications" style="padding: 10px; border: 1px solid #ccc; background: #f9f9f9; height: 200px; overflow-y: auto;">
      Waiting for events...
   </div>

   <script>
      var eventSource = new EventSource('/sse-multi.php');
      var notificationDiv = document.getElementById('notifications');
      
      // Handle time updates
      eventSource.addEventListener('time', function(event) {
         addNotification('Time: ' + event.data, '#007bff');
      });
      
      // Handle user notifications
      eventSource.addEventListener('notification', function(event) {
         addNotification('Alert: ' + event.data, '#dc3545');
      });
      
      // Handle system status
      eventSource.addEventListener('status', function(event) {
         addNotification('Status: ' + event.data, '#28a745');
      });

      function addNotification(message, color) {
         var p = document.createElement('p');
         p.style.color = color;
         p.style.margin = '5px 0';
         p.textContent = new Date().toLocaleTimeString() + ' - ' + message;
         notificationDiv.appendChild(p);
         notificationDiv.scrollTop = notificationDiv.scrollHeight;
      }
   </script>
</body>
</html>

This example listens for three different event types: time, notification, and status. Each event type is handled by a separate event listener and displayed with different colors.

Server-Side Multi-Event PHP Script

<?php
// sse-multi.php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$counter = 0;

while (true) {
    $counter++;
    
    // Send time update every iteration
    $time = date('H:i:s');
    echo "event: time<br>";
    echo "data: $time<br><br>";
    
    // Send notification every 5 iterations
    if ($counter % 5 == 0) {
        echo "event: notification<br>";
        echo "data: You have a new message!<br><br>";
    }
    
    // Send status every 10 iterations
    if ($counter % 10 == 0) {
        echo "event: status<br>";
        echo "data: System running normally<br><br>";
    }
    
    ob_flush();
    flush();
    sleep(2);
    
    if (connection_aborted()) {
        break;
    }
}
?>

SSE Event Format Specification

Server-Sent Events follow a specific text format. Each event consists of one or more fields, separated by newlines −

event: event-name
data: message content
id: unique-id
retry: reconnection-time-ms

Key points about the SSE format −

  • data: Contains the actual message content

  • event: Specifies custom event type (optional, defaults to "message")

  • id: Unique identifier for the event (optional)

  • retry: Reconnection timeout in milliseconds (optional)

  • Double newline (

    ):
    Marks the end of an event

Browser Compatibility and Features

Server-Sent Events are widely supported in modern browsers. Key features include −

Feature Description
Automatic Reconnection Browser automatically reconnects if connection drops
Event ID Tracking Resumes from last received event using Last-Event-ID header
Cross-Origin Support Works with CORS headers for cross-domain requests
UTF-8 Encoding Supports Unicode text in event data
Connection States Provides onopen, onmessage, onerror event handlers

Conclusion

Server-Sent Events provide an efficient way to stream real-time data from server to client using the EventSource API. Unlike WebSockets, SSE is unidirectional (server-to-client only) and automatically handles reconnection, making it ideal for live feeds, notifications, and real-time updates. The technology uses a simple text-based protocol with the text/event-stream MIME type.

Updated on: 2026-03-16T21:38:53+05:30

502 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements