HTML SSE (Server-Sent Events)

Subject: html

πŸ”„ HTML Server-Sent Events (SSE)

Server-Sent Events (SSE) allow a server to push real-time updates to the browser over a single, long-lived HTTP connection. This is part of the HTML5 specification.

Useful for:

  • βœ… News tickers
  • βœ… Live notifications
  • βœ… Real-time dashboards
  • βœ… Stock/weather updates
  • βœ… Social media feeds

πŸ“‘ How SSE Works

  • The browser creates a connection using the EventSource API
  • The server keeps the connection open and pushes data as needed
  • Data is sent in text/event-stream format
  • One-way only (server β†’ client)

πŸ’‘ When to Use SSE

Use SSE when:

  • Only the server needs to send updates
  • You want simplicity over full-duplex (like WebSockets)
  • You’re building real-time UIs that listen for backend events

🧱 Basic Client-Side Syntax


πŸ“„ HTML + JavaScript Example


πŸ“œ Server Response Format

The server script (server.php) should return content in this format:


πŸ”§ Important HTTP Headers

HeaderPurpose
Content-TypeMust be text/event-stream
Cache-ControlUse no-cache to prevent caching
ConnectionUse keep-alive to maintain open connection

βœ… Advantages of SSE

  • Simpler than WebSockets for server-to-client only
  • Built-in reconnect and retry mechanism
  • Lightweight: no polling needed
  • Text-based (easy to debug and test)

⚠️ Limitations of SSE

  • ❌ Only supports one-way communication
  • ❌ Not supported in Internet Explorer
  • ❌ Officially tied to HTTP/1 (though workarounds exist for HTTP/2)

🧠 Key Takeaway

  • SSE is ideal for real-time updates from the server to the client
  • Simple to implement using EventSource
  • Great for dashboards, alerts, feeds, and live content
  • Supported in all major browsers (except IE)
  • Use when you don’t need full duplex (bi-directional) communication