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.


Go Back Top