HTML SSE


Server-Sent Events (SSE) allow a web page to receive automatic updates from a server via an HTTP connection. Unlike WebSockets, SSE is unidirectional — data flows from the server to the client only.

SSE is useful for real-time notifications, news feeds, or live updates where the server pushes data to the browser continuously.


🔹 How SSE Works

  • The client opens a persistent HTTP connection to the server using an EventSource object in JavaScript.

  • The server keeps the connection open and sends messages whenever new data is available.

  • The client listens for messages using event handlers.


💻 Basic Example

Server-side (Node.js example)
const http = require('http');

http.createServer((req, res) => {
  if (req.url === '/events') {
    res.writeHead(200, {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive'
    });

    let counter = 0;
    const interval = setInterval(() => {
      counter++;
      res.write(`data: Message number ${counter}\n\n`);
      if (counter === 5) {
        clearInterval(interval);
        res.end();
      }
    }, 1000);

  } else {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end(`<html><body>
      <script>
        const evtSource = new EventSource('/events');
        evtSource.onmessage = function(event) {
          document.body.innerHTML += '<p>' + event.data + '</p>';
        };
      </script>
    </body></html>`);
  }
}).listen(3000);

🔹 Client-side JavaScript for SSE

const eventSource = new EventSource('path_to_server');

eventSource.onmessage = function(event) {
  console.log('New message:', event.data);
};

eventSource.onerror = function(event) {
  console.error('EventSource failed:', event);
};

🔹 SSE Important Notes

  • SSE uses the text/event-stream content type.

  • Each message must be prefixed with data: and end with two newlines (\n\n).

  • SSE works over HTTP/HTTPS but requires a persistent connection.

  • Supported by most modern browsers (except IE).

  • SSE is simpler than WebSocket but only supports server-to-client streaming.


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.


HTML SSE Quiz

Q1: What protocol do Server-Sent Events use?

A. WebSocket
B. HTTP/HTTPS
C. FTP
D. TCP

Q2: Which JavaScript object is used to receive SSE messages?

A. WebSocket
B. EventSource
C. XMLHttpRequest
D. Fetch

Q3: How is each SSE message formatted?

A. data: message followed by two newlines
B. JSON string
C. Plain text only
D. Encrypted string

Q4: SSE is:

A. Bidirectional
B. Unidirectional from client to server
C. Unidirectional from server to client
D. Not a network protocol

Q5: Which HTTP content-type is used for SSE?

A. text/plain
B. application/json
C. text/event-stream
D. application/xml

Q6: Which event handler listens for incoming messages?

A. onreceive
B. onmessage
C. ondata
D. onload

Q7: How does SSE handle connection interruptions?

A. It automatically reconnects
B. Connection closes permanently
C. User must refresh page
D. It uses WebSocket fallback

Q8: What is the maximum number of event streams a client can open?

A. One per page
B. Unlimited
C. Limited by browser (usually 6)
D. Exactly two

Q9: Which is NOT true about SSE?

A. Works over HTTP/HTTPS
B. Server can push updates anytime
C. Supports two-way communication
D. Uses text/event-stream content type

Go Back Top