HTML Server-Sent Events (SSE)

Real-time data streaming from server to client

📡 What are Server-Sent Events?

Server-Sent Events (SSE) allow a server to push data to a web page in real-time. Perfect for live updates, notifications, and streaming data.


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

// Listen for messages
eventSource.onmessage = function(event) {
    console.log('New message:', event.data);
    document.getElementById('messages').innerHTML += event.data + '<br>';
};
                                    

Try it:

SSE Features

🔄

Real-time Updates

Receive live data from server

eventSource.onmessage = (e) => {
    updateUI(e.data);
};
🔌

Auto Reconnection

Automatically reconnects if connection drops

eventSource.onerror = () => {
    console.log('Reconnecting...');
};
🏷️

Event Types

Handle different types of events

eventSource.addEventListener('update', 
    (e) => handleUpdate(e.data)
);
💡

Simple Protocol

Easy to implement on server side

data: Hello World
event: message

🔹 Basic SSE Implementation

Here's how to set up Server-Sent Events:

// Client-side JavaScript
const eventSource = new EventSource('/stream');

// Handle incoming messages
eventSource.onmessage = function(event) {
    const data = JSON.parse(event.data);
    displayMessage(data);
};

// Handle connection opened
eventSource.onopen = function() {
    console.log('Connection opened');
};

// Handle errors
eventSource.onerror = function(event) {
    console.log('Error occurred:', event);
};

// Close connection when needed
function closeConnection() {
    eventSource.close();
}

Server Response Format:

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

data: {"message": "Hello World", "timestamp": "2024-01-01T12:00:00Z"}

data: {"message": "Another update", "timestamp": "2024-01-01T12:01:00Z"}

🔹 Live Chat Example

Let's create a simple live chat using Server-Sent Events:

<!-- HTML -->
<div id="chat-container">
    <div id="messages"></div>
    <input type="text" id="messageInput" placeholder="Type a message...">
    <button onclick="sendMessage()">Send</button>
</div>
// JavaScript
let eventSource;

function startChat() {
    eventSource = new EventSource('/chat-stream');
    
    eventSource.onmessage = function(event) {
        const message = JSON.parse(event.data);
        displayMessage(message);
    };
}

function displayMessage(message) {
    const messagesDiv = document.getElementById('messages');
    messagesDiv.innerHTML += `
        <div class="message">
            <strong>${message.user}:</strong> ${message.text}
            <span class="timestamp">${message.time}</span>
        </div>
    `;
    messagesDiv.scrollTop = messagesDiv.scrollHeight;
}

Try it:

🔹 Event Types and Custom Events

SSE supports different event types for better organization:

// Listen for specific event types
eventSource.addEventListener('notification', function(event) {
    showNotification(event.data);
});

eventSource.addEventListener('update', function(event) {
    updateContent(event.data);
});

eventSource.addEventListener('heartbeat', function(event) {
    console.log('Server is alive');
});

Server Event Format:

event: notification
data: {"type": "info", "message": "New user joined"}

event: update
data: {"content": "Page content updated"}

event: heartbeat
data: {"status": "ok", "time": "2024-01-01T12:00:00Z"}

🧠 Test Your Knowledge

What is the main advantage of Server-Sent Events over regular AJAX polling?