Server-Sent Events (SSE) is a technology that allows a server to push real-time updates to the browser over a single, long-lived HTTP connection. Unlike traditional HTTP, where the client must repeatedly request updates (polling), SSE enables the server to send new data to the client whenever it becomes available.
- The client (browser) creates an
EventSource
connection to a specific server endpoint. - The server responds with the
Content-Type: text/event-stream
header and keeps the connection open. - The server can send messages to the client at any time, using a simple text-based protocol.
- The browser receives these messages as
message
events.
Feature | SSE (Server-Sent Events) | WebSockets |
---|---|---|
Protocol | HTTP (unidirectional) | Custom (bidirectional) |
Direction | Server → Client only | Server ↔ Client (full duplex) |
Browser Support | Most modern browsers | All modern browsers |
Complexity | Simple (built-in EventSource) | More complex (WebSocket API) |
Reconnection | Automatic (built-in) | Manual (must handle yourself) |
Use Cases | Live feeds, notifications, logs | Chat, games, collaborative apps |
Binary Data | No (text only) | Yes (text and binary) |
HTTP/2 Support | Yes | Not natively (needs upgrade) |
Firewalls/Proxies | Works well (HTTP) | Sometimes blocked |
Summary:
- SSE is ideal for real-time, server-to-client updates (e.g., notifications, live dashboards).
- WebSockets are better for interactive, two-way communication (e.g., chat, games).
- Install dependencies:
npm install express
- Start the server:
node index.js
- Open your browser's developer console (F12).
- Run the following code:
let sse = new EventSource("http://localhost:8080/stream"); sse.onmessage = console.log;
- You will see a new message logged every second from the server.