Server-Sent Events for One-Way Streaming
Use EventSource to receive a stream of server-sent events, parse event types and data, and reconnect automatically on network interruptions.
Server-Sent Events for One-Way Streaming is a free Frontend Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Frontend Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Are Server-Sent Events?
SSE is a standard HTTP-based protocol for the server to push events to the browser over a single long-lived connection. One-way: server → client only. Simpler than WebSockets when you don't need to send back.
EventSource API
The browser's EventSource connects to a URL and listens for events. Standard, built-in, no library needed.
const es = new EventSource('/api/events');
es.addEventListener('message', (event) => {
console.log('Received:', event.data);
});
es.addEventListener('error', () => {
console.error('Connection error');
});Server Response Format
The server sends a plain-text stream with Content-Type: text/event-stream. Each message starts with data: and ends with a blank line.
// Server response:
Content-Type: text/event-stream
Cache-Control: no-cache
data: hello\n\n
data: another message\n\n
data: {"type":"chat","text":"Hi"}\n\nNamed Events
The server can name events with event:. The browser fires them with that name.
// Server:
event: chat
data: {"user":"Alice","text":"Hi"}\n\n
event: user-joined
data: {"name":"Bob"}\n\n
// Client:
es.addEventListener('chat', (e) => { /* ... */ });
es.addEventListener('user-joined', (e) => { /* ... */ });Auto-Reconnect
EventSource reconnects automatically on disconnect (after about 3 seconds). The server can suggest a delay with retry: 5000.
// Server:
retry: 5000\n
data: hello\n\nEvent IDs and Resumption
The server sends id: with each event. After reconnect, the browser sends the last received ID in Last-Event-ID header — the server can resume from there.
// Server:
id: 42
event: chat
data: {"text":"Hi"}\n\n
id: 43
event: chat
data: {"text":"How are you?"}\n\n
// Client reconnect sends: Last-Event-ID: 43Parsing JSON
event.data is always a string. Parse JSON yourself.
es.addEventListener('chat', (e) => {
const msg = JSON.parse(e.data);
console.log(msg.user, msg.text);
});Closing the Connection
Call es.close() to stop. Browsers also close on tab close.
es.close();
// In React, close in useEffect cleanup:
useEffect(() => {
const es = new EventSource('/events');
es.onmessage = (e) => setData(d => [...d, e.data]);
return () => es.close();
}, []);Use Cases
Live dashboards (metrics, monitoring). Notifications (new emails, alerts). Stock tickers. AI chat completions (each token = an event). Live sports scores. Status updates from long-running jobs.
Real Example: AI Streaming
OpenAI/Anthropic completions stream as SSE. Each token arrives as a data event — render progressively for a typing effect.
const es = new EventSource('/api/chat?prompt=hello');
let text = '';
es.addEventListener('message', (e) => {
if (e.data === '[DONE]') {
es.close();
return;
}
const { delta } = JSON.parse(e.data);
text += delta;
setMessage(text);
});SSE vs WebSocket vs Polling
SSE: HTTP-based, server-to-client only, auto-reconnect, simple. WebSocket: full duplex, lower overhead per message, more complex. Polling: simplest, highest latency and load. Choose SSE for one-way streaming; WS for chat-like two-way.
Browser Limits and Proxies
Browsers limit concurrent SSE connections per origin (around 6). Some corporate proxies and old load balancers buffer responses, breaking SSE — test in target environments. Use HTTPS to bypass most proxy buffering.
CORS for SSE
EventSource respects CORS. The server must send Access-Control-Allow-Origin. For credentials, pass { withCredentials: true } to the EventSource constructor and set Access-Control-Allow-Credentials: true on the server.
Quick Check
What's the key difference between Server-Sent Events and WebSockets?
Recap: Server-Sent Events
EventSource opens an HTTP stream of text/event-stream events. Server sends 'data:' messages with optional event: name and id:. Auto-reconnect with Last-Event-ID resumption. One-way (server → client). Great for live dashboards, AI streaming, notifications. Simpler than WebSocket when you don't need two-way. Watch concurrent connection limits and proxy buffering.
Frequently asked questions
Is the “Server-Sent Events for One-Way Streaming” lesson free?
Yes — the full text of “Server-Sent Events for One-Way Streaming” is free to read here on the web, and the Frontend Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Frontend Academy course, upgrade to CoddyKit PRO.
What will I learn in “Server-Sent Events for One-Way Streaming”?
Use EventSource to receive a stream of server-sent events, parse event types and data, and reconnect automatically on network interruptions. You practise Frontend Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Frontend Academy?
No prior experience is required. Frontend Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Server-Sent Events for One-Way Streaming” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Frontend Academy lesson?
Yes. Every Frontend Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- WebSocket API: open message close error
- Socket.io Client Integration
- Server-Sent Events for One-Way Streaming
- Real-time UI Patterns