Sse Intro
title: "Introduction to Server-Sent Events" description: "Learn what Server-Sent Events (SSE) are, how they enable server-to-client streaming, and when to use them over WebSocket for real-time data." weight: 11 date: 2026-06-28 lastmod: 2026-06-28 tags: ["apis", "sse"]
Server-Sent Events (SSE) is a standard that allows servers to push data to web clients over HTTP. Unlike WebSocket, SSE is unidirectional (server to client) and uses standard HTTP, making it simpler for many use cases.
## What You'll Learn
- What SSE is and how it works
- SSE vs WebSocket differences
- Common SSE use cases
- Browser support and EventSource API
- Simple SSE server implementation
## Why It Matters
SSE is the simplest way to add real-time updates to web applications. It works over standard HTTP, requires no special proxies or handshakes, and automatically handles reconnection.
## Real-World Use
A news website uses SSE to push breaking news alerts to readers. When a story breaks, the server sends an event, and all connected browsers display the alert within milliseconds without any polling.
## Flow Chart
```mermaid
flowchart LR
A[Server] -->|HTTP Connection| B[Client]
A -->|Event: data| B
A -->|Event: data| B
A -->|Event: data| B
B -->|Auto-reconnect| A
Note: Unidirectional server-to-client
Code Examples
Example 1: Basic SSE Server in Node.js
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/events') {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': '*',
});
// Send events every 2 seconds
const intervalId = setInterval(() => {
const data = JSON.stringify({
time: new Date().toISOString(),
message: 'Hello from SSE',
});
res.write(`data: ${data}\n\n`);
}, 2000);
// Clean up on connection close
req.on('close', () => {
clearInterval(intervalId);
});
} else {
res.writeHead(404);
res.end();
}
});
server.listen(3000, () => {
console.log('SSE server on http://localhost:3000/events');
});
Expected output: Server sends a JSON event every 2 seconds to all connected SSE clients.
Example 2: Browser EventSource Client
<!DOCTYPE html>
<html>
<head>
<title>SSE Demo</title>
</head>
<body>
<h1>Server-Sent Events</h1>
<div id="events"></div>
<script>
const eventDiv = document.getElementById('events');
if (typeof EventSource !== 'undefined') {
const source = new EventSource('/events');
source.onopen = () => {
console.log('Connection opened');
};
source.onmessage = (event) => {
const data = JSON.parse(event.data);
const p = document.createElement('p');
p.textContent = `[${data.time}] ${data.message}`;
eventDiv.appendChild(p);
};
source.onerror = (error) => {
console.error('EventSource error:', error);
};
} else {
eventDiv.textContent = 'EventSource not supported';
}
</script>
</body>
</html>
Expected output: Browser connects to SSE endpoint and displays each received event as a paragraph.
Example 3: SSE with Named Events
// Server with named events
res.write(`event: user-connected\ndata: {"userId": 123}\n\n`);
res.write(`event: message\ndata: {"text": "Hello"}\n\n`);
res.write(`event: user-disconnected\ndata: {"userId": 123}\n\n`);
// Client listening for named events
const source = new EventSource('/events');
source.addEventListener('user-connected', (event) => {
const data = JSON.parse(event.data);
console.log('User connected:', data.userId);
});
source.addEventListener('message', (event) => {
const data = JSON.parse(event.data);
console.log('Message:', data.text);
});
source.addEventListener('user-disconnected', (event) => {
const data = JSON.parse(event.data);
console.log('User disconnected:', data.userId);
});
Expected output: Client dispatches named events to different handlers based on the event type.
Common Mistakes
| Mistake | Explanation |
|---|---|
| Forgetting Content-Type header | SSE requires Content-Type: text/event-stream or the browser will not parse events |
| Adding Cache-Control | Set Cache-Control: no-cache to prevent browsers from caching the event stream |
| Not handling connection close | Always clean up server resources when the client disconnects |
| Using SSE for bidirectional communication | SSE is server-to-client only; use WebSocket for bidirectional needs |
| Missing trailing newlines | Each SSE event must end with \n\n (double newline) |
Practice Questions
- What is the difference between SSE and WebSocket?
- What HTTP headers are required for SSE?
- How does the EventSource API handle reconnection?
- What are named events in SSE?
- What browsers support EventSource?
Challenge
Build an SSE server that streams system metrics (CPU, memory, uptime) to a browser dashboard. The client should display each metric in real-time with live-updating values.
FAQ
Mini Project
Build a live sports scoreboard using SSE. The server pushes game scores and events to all connected browsers. Include named events for score changes, game status updates, and player statistics.
What's Next
Compare SSE and WebSocket in detail
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro