How can I handle Server-Sent Events in HTML5?

Server-Sent Events (SSE) in HTML5 allow web pages to receive automatic updates from a server. This creates a persistent connection where the server can push data to the client in real-time.

What are Server-Sent Events?

Server-Sent Events provide a way for a server to send data to a web page automatically. Unlike WebSockets, SSE is unidirectional - only the server can send data to the client.

Creating an EventSource Connection

Use the EventSource object to establish a connection to the server:

<!DOCTYPE html>
<html>
<head>
    <title>Server-Sent Events Demo</title>
</head>
<body>
    <div id="messages"></div>
    <div id="status">Connecting...</div>
    
    <script>
        // Check if browser supports SSE
        if (typeof(EventSource) !== "undefined") {
            // Create EventSource connection
            const eventSource = new EventSource('/events');
            
            // Handle incoming messages
            eventSource.onmessage = function(event) {
                const messagesDiv = document.getElementById('messages');
                messagesDiv.innerHTML += '<p>' + event.data + '</p>';
            };
            
            // Handle connection opened
            eventSource.onopen = function() {
                document.getElementById('status').innerHTML = 'Connected';
            };
            
            // Handle errors
            eventSource.onerror = function() {
                document.getElementById('status').innerHTML = 'Connection error';
            };
        } else {
            document.getElementById('status').innerHTML = 'SSE not supported';
        }
    </script>
</body>
</html>

Handling Custom Events

You can listen for custom event types sent by the server:

<!DOCTYPE html>
<html>
<body>
    <div id="time-display">[TIME]</div>
    <div id="notification-area"></div>
    
    <script>
        const eventSource = new EventSource('/server-events');
        
        // Listen for custom 'server-time' events
        eventSource.addEventListener('server-time', function(event) {
            document.getElementById('time-display').innerHTML = event.data;
        });
        
        // Listen for custom 'notification' events
        eventSource.addEventListener('notification', function(event) {
            const notificationArea = document.getElementById('notification-area');
            notificationArea.innerHTML = '<div class="alert">' + event.data + '</div>';
        });
        
        // Handle connection errors
        eventSource.onerror = function() {
            console.log('EventSource connection error');
        };
    </script>
</body>
</html>

EventSource Methods and Properties

Property/Method Description
readyState Connection state (0=CONNECTING, 1=OPEN, 2=CLOSED)
url The URL of the event source
close() Closes the connection
onopen Event handler for connection opened
onmessage Event handler for incoming messages
onerror Event handler for errors

Closing the Connection

Always close SSE connections when no longer needed:

<script>
    const eventSource = new EventSource('/events');
    
    // Close connection after 30 seconds
    setTimeout(function() {
        eventSource.close();
        console.log('EventSource connection closed');
    }, 30000);
    
    // Close on page unload
    window.addEventListener('beforeunload', function() {
        eventSource.close();
    });
</script>

Server-Side Requirements

The server must send data in SSE format with proper headers:

// Server response headers
Content-Type: text/event-stream
Cache-Control: no-cache
Connection: keep-alive

// Data format
data: Hello World
event: notification
data: This is a custom event

Browser Compatibility

Server-Sent Events are supported in all modern browsers. Always check for support before using:

<script>
    if (typeof(EventSource) !== "undefined") {
        // SSE is supported
        console.log("Browser supports Server-Sent Events");
    } else {
        // Fallback for older browsers
        console.log("SSE not supported, use polling instead");
    }
</script>

Conclusion

Server-Sent Events provide an efficient way to receive real-time updates from a server. Use the EventSource object to establish connections and handle incoming data with event listeners.

Updated on: 2026-03-15T23:18:59+05:30

217 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements