HTML SSE


Server-Sent Events, or SSE, allow your webpage to receive automatic real-time updates from the server without refreshing the page and without constantly sending new requests. The server keeps a connection open and pushes new messages as soon as something changes. This is useful for live notifications, chat updates, stock prices, dashboard data, live scores and event tracking. In this chapter, you’ll learn what SSE is, how it works, how to create an SSE connection in HTML and JavaScript, how to read incoming messages and how to build real examples.

What Are Server-Sent Events?

Server-Sent Events provide a one-way communication channel. The server sends updates to the browser whenever new data is available. The browser does not need to ask again. This keeps traffic light and communication smooth.

SSE uses a simple HTTP connection. The server sends data in a special text format, and the browser receives it through an EventSource object.

Key points:

  • SSE is one-way (server → browser).

  • The page automatically receives updates.

  • There is no need to reload or poll repeatedly.

  • It uses simple text-based messages.

  • Supported in most modern browsers.

If you want fast, lightweight real-time updates, SSE is a great option.

Why Use SSE Instead of Other Technologies?

There are multiple ways to get live data, but SSE fits well for many use cases. Here’s why:

Benefits of SSE

  • simpler than WebSockets

  • automatic reconnection if the connection drops

  • built-in support in modern browsers

  • ideal for read-only or push-based updates

  • less code compared to WebSockets

When SSE is better than WebSockets

Use SSE when:

  • updates flow mostly from server to client

  • the browser doesn’t need to send frequent messages

  • you need a simple, lightweight real-time feature

Examples:

  • live notifications

  • server logs

  • stock price ticker

  • match scores

  • live weather updates

  • dashboard refresh

  • progress updates during long tasks

If your app needs two-way communication (like chat where both sides send messages), WebSockets may be better. But for most push-only scenarios, SSE is easier.

How SSE Works

  1. The browser creates an EventSource connection to a special URL.

  2. The server keeps that connection open.

  3. Whenever new data is ready, the server sends it as a text event.

  4. The browser receives it and triggers an event handler.

SSE uses a simple text format like:

data: your message here

Each message ends with a blank line. The browser listens continuously.

Setting Up a Basic SSE Example

To use SSE, you need:

  • an HTML file

  • a JavaScript block

  • a server script that sends SSE messages

The server script must output the correct headers and message format.

Step 1: HTML + JavaScript

<!DOCTYPE html>
<html>
<body>

<h2>Server-Sent Events Example</h2>

<div id="output">Waiting for updates...</div>

<script>
    if (typeof(EventSource) !== "undefined") {
        let source = new EventSource("server.php");

        source.onmessage = function(event) {
            document.getElementById("output").textContent = event.data;
        };
    } else {
        document.getElementById("output").textContent = "SSE not supported";
    }
</script>

</body>
</html>

Here, the script connects to server.php.

Step 2: Server Script (PHP example)

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

echo "data: The time is " . date("h:i:s") . "\n\n";
flush();

Every time the browser loads, it receives the current time from the server.

Continuous Updates with SSE

To send repeated updates, the server must keep sending messages at intervals.

PHP example with continuous updates

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

while (true) {
    echo "data: " . date("h:i:s") . "\n\n";
    ob_flush();
    flush();
    sleep(1);
}

The browser now receives a message every second.

Listening to Custom Events

SSE supports custom event types. You can send named events, and the browser can listen for them.

Server script

event: score
data: India 120/3

JavaScript

source.addEventListener("score", function(e) {
    console.log("Live score:", e.data);
});

This is useful for dashboards, analytics and live sports.

Handling Connection Open and Error Events

EventSource provides ways to handle connection status.

source.onopen = function() {
    console.log("Connection opened");
};

source.onerror = function() {
    console.log("Error occurred or connection closed");
};

This helps you debug or show connection status to users.

Sending Multiple Lines of Data

Messages can contain multiple lines:

data: Line 1
data: Line 2
data: Line 3

The browser receives them as a single event with newline characters.

Understanding Retry and Auto-Reconnect

SSE automatically reconnects when the connection drops.
You can also specify the retry time from the server.

retry: 3000
data: Reconnecting in 3 seconds

The browser waits before reconnecting.

You don't need to write extra code for reconnection. It’s built in.

Adding IDs to Messages

Events can have IDs.
If the connection closes and reopens, the browser sends the last ID received.

id: 20
data: new update

This prevents missing messages during reconnection.

Example: Live Notification System

server.php

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$messages = ["New user registered", "Payment received", "Comment added"];

while (true) {
    $i = array_rand($messages);
    echo "data: " . $messages[$i] . "\n\n";
    flush();
    sleep(3);
}

JavaScript

source.onmessage = function(e) {
    console.log("Notification:", e.data);
};

A random message is sent every few seconds.

Example: Live Stock Price Updates

server script

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

while (true) {
    $price = rand(1500, 1600);
    echo "data: Stock price: ₹$price\n\n";
    flush();
    sleep(1);
}

SSE is perfect for real-time finance dashboards.

Example: Live Order Tracking

You can use SSE to update delivery status:

data: Order received
data: Packed
data: Out for delivery
data: Delivered

The browser updates the UI whenever the server sends a new status.

When Not to Use SSE

Avoid SSE when:

  • you need full two-way communication

  • you need binary data

  • the server doesn’t support long-lived connections

  • you want to send large files

In these cases, WebSockets or API polling might be better.

Summary of HTML SSE

HTML SSE (Server-Sent Events) offer a simple, efficient way to receive real-time updates from the server. You learned how EventSource works, how the server sends messages, how reconnection happens automatically and how to create custom events. SSE is ideal for notifications, dashboards, stock prices, logs, timers and live updates where the data flows mainly from server to client. With the right setup, SSE can make your webpage feel fast, dynamic and truly live.


Practice Questions

Q1. Create an HTML page that listens to server-sent events and displays messages live.

Q2. Implement a Node.js server sending SSE messages every 2 seconds.

Q3. Handle SSE errors with onerror event on client-side.

Q4. Stop receiving events after a certain count using JavaScript.

Q5. Display live stock prices or news feed using SSE.

Q6. Send custom events with event names using event: prefix.

Q7. Implement reconnect logic for SSE connection loss.

Q8. Use SSE to update a live chat window from server messages.

Q9. Customize message format using multi-line messages.

Q10. Compare SSE with WebSockets for use cases.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top