Skip to content

Server-Sent Events (SSE) Complete Guide: One-Way Real-Time Data Streaming

In this tutorial, you'll learn about Server-Sent Events (SSE): a one-way push technology that enables servers to stream data to clients over a single HTTP connection, ideal for real-time notifications and live feeds.

Server-Sent Events (SSE) is a unidirectional push technology enabling servers to stream data to web clients over a single persistent HTTP connection with built-in reconnection.

What You'll Learn

  • SSE event stream format and EventSource browser API
  • SSE implementation in Express and Python
  • Named event types and data-only events
  • Auto-reconnection and last-event-id
  • SSE vs Websocket tradeoffs and use cases

Why SSE Matters

For use cases where the server needs to push updates to clients but clients don't need to send data back (notifications, stock tickers, log streams), WebSocket is overkill. SSE uses standard HTTP, has built-in browser reconnection, and is simpler to implement. DodaTech's Durga Antivirus Pro uses SSE to push scan result notifications to user dashboards — the browser automatically reconnects if the connection drops, and no client-side WebSocket library is needed.

flowchart LR
    A["Browser\n(EventSource API)"] -->|"HTTP GET /events"| B["SSE Server\n(Express / FastAPI)"]
    B -->|"data: {\"scan\": \"complete\"}\n\n"| A
    B -->|"data: {\"threat\": \"detected\"}\n\n"| A
    B -->|"event: error\ndata: ...\n\n"| A
    C["EventSource:\nonmessage, onevent"] --> D["Auto-reconnect\non error"]
    style B fill:#dbeafe,stroke:#2563eb
    style A fill:#fef3c7,stroke:#d97706
â„šī¸ Info

Prerequisites: Basic HTTP and JavaScript knowledge. Node.js or Python familiarity for server-side examples.

SSE vs WebSocket

Feature SSE WebSocket
Direction Server to client only Bidirectional
Protocol HTTP ws:// / wss://
Auto-reconnect Built-in Must implement
Binary data No (text only) Yes
Browser API EventSource WebSocket
Max concurrent 6 per domain (HTTP/1.1) Unlimited
Complexity Low Medium-High

Common Mistakes

1. Forgetting the Trailing Newlines

Each SSE event must end with two newlines (\n\n). One newline means more data is coming. Omitting the trailing newline causes the client to wait indefinitely.

2. Not Setting Correct Headers

SSE requires Content-Type: text/event-stream, Cache-Control: no-cache, and Connection: keep-alive. Missing any of these breaks the event stream.

3. Ignoring Last-Event-Id

When a client reconnects, it sends Last-Event-Id header. Use this to resume from the last received event instead of resending all events.

4. No Keepalive Pings

Some proxies drop idle connections after 30-60 seconds. Send periodic comments (: keepalive\n\n) or empty events to keep the connection alive.

5. Using SSE for Bidirectional Communication

SSE is one-way only. If the client needs to send data back, use WebSocket or combine SSE with regular HTTP POST requests.

Practice Questions

  1. What are the required HTTP headers for SSE?
  2. How does the browser EventSource API handle reconnection?
  3. What is the SSE event stream format?
  4. When should you choose SSE over WebSocket?
  5. How do you implement named event types in SSE?

Answers:

  1. Content-Type: text/event-stream, Cache-Control: no-cache, Connection: keep-alive.
  2. The browser automatically reconnects when the connection drops. It sends the Last-Event-Id header so the server can resume from where it left off.
  3. event: type\ndata: payload\n\n — fields separated by newlines, events terminated by double newline. data is required, event, id, and retry are optional.
  4. SSE is better for one-way updates (notifications, feeds, logs) where server pushes to client. WebSocket is better for bidirectional communication (chat, gaming, collaboration tools).
  5. Use the event: field to specify a named event type. The client registers listeners with eventSource.addEventListener('eventName', handler) instead of onmessage.

Challenge: Build an SSE endpoint for Durga Antivirus Pro that streams real-time scan progress updates. Include named events for scan:started, scan:progress, scan:completed, and scan:error. Implement last-event-id reconnection and an HTML dashboard page that displays scan progress in real time.

FAQ

Is SSE supported in all browsers?

SSE is supported in all modern browsers (Chrome, Firefox, Safari, Edge). Internet Explorer does not support EventSource, but polyfills are available.

Can SSE send binary data?

No — SSE is text-only. The event data field must be a UTF-8 string. For binary data, use WebSocket or encode binary as base64 in the SSE data field.

Why does SSE have a 6-connection limit per domain?

HTTP/1.1 browsers limit concurrent connections per domain to 6. Each SSE connection is a persistent HTTP connection. Use HTTP/2 for unlimited concurrent SSE streams, or consolidate feeds into a single stream.

How do I prevent SSE connections from timing out?

Set a long timeout on the server (30+ minutes), disable proxy timeouts if possible, and send periodic keepalive comments (: heartbeat\n\n) every 15-30 seconds.

Can SSE work with serverless functions?

SSE requires a persistent HTTP connection, which most serverless platforms (AWS Lambda, Vercel) do not support. Use a serverful backend (Express, FastAPI, Spring) or a platform that supports streaming responses.

Try It Yourself

# Test SSE with curl
curl -N -H "Accept: text/event-stream" http://localhost:3000/events

# Output:
# data: {"time": "2026-06-28T12:00:00Z", "value": 42}
# 
# data: {"time": "2026-06-28T12:00:02Z", "value": 43}
#

What's Next

Topic Description
Introduction to SSE First steps with Server-Sent Events
WebSocket Guide Bidirectional real-time communication
Webhooks Guide Server-to-server event notifications
RESTful APIs Compare with request-response APIs
➡ SSE Introduction
âŦ… WebSocket Guide

Published Topics

Sse Auto Reconnect

✓ Live

Sse Cors

✓ Live

Sse Event Source Api

✓ Live

Sse Event Stream Format

✓ Live

Sse Event Types

✓ Live

Sse Express

✓ Live

Sse Intro

✓ Live

Sse Last Event Id

✓ Live

Sse Nodejs

✓ Live

Sse Project

✓ Live

Sse Python

✓ Live

Sse Vs Websocket

✓ Live

SSE Named Event Types — Sending Structured Events with event: Fields

Learn how to use named event types in Server-Sent Events with the event: field, enabling clients to dispatch different event types to different handlers for structured streaming.

✓ Live

SSE JSON Data — Sending Structured Data in Server-Sent Events

Learn how to format and send JSON data in Server-Sent Events using the data: field, enabling structured data transfer for complex real-time applications.

✓ Live

SSE Event IDs and last-event-id — Tracking Events and Recovering from Disconnections

Learn how to use the id: field in Server-Sent Events to assign unique identifiers to events, enabling clients to resume streams from the last received event after disconnection.

✓ Live

SSE Retry Mechanism — Complete Guide to Auto-Reconnection

SSE retry mechanism controls how long the browser waits before reconnecting after a dropped connection, using the retry field in the event stream and exponential backoff.

✓ Live

SSE Multiplexing — Complete Guide to Multiple Event Streams

SSE multiplexing manages multiple event streams over a single HTTP connection using named events, separate endpoints, or HTTP/2 multiplexing for efficient real-time data delivery.

✓ Live

SSE Browser Support — Complete Guide to Compatibility

SSE browser support covers native EventSource API availability across browsers, fallback strategies for unsupported browsers, and polyfill solutions for complete coverage.

✓ Live

SSE and HTTP/2 — Complete Guide to Modern Streaming

SSE over HTTP/2 eliminates the browser connection limit per origin, enables multiplexed streams over a single TCP connection, and improves performance for real-time data delivery.

✓ Live

SSE with Nginx — Complete Guide to Production Deployment

SSE with nginx requires disabling buffering, enabling HTTP/2, and configuring proxy settings to ensure the event stream reaches clients without delay or truncation.

✓ Live

SSE with Django — Complete Guide to Server-Sent Events

SSE with Django implements real-time server-to-client streaming using StreamingHttpResponse, async views, and Django channels for scalable event delivery in Python web apps.

✓ Live

SSE with Spring Boot — Complete Guide to Reactive Streaming

SSE with Spring Boot uses SseEmitter and WebFlux to stream server-sent events from Java applications, supporting async processing and backpressure for scalable real-time data.

✓ Live

SSE Performance — Complete Guide to Optimization

SSE performance optimization covers connection pooling, message batching, compression, efficient event serialization, and server tuning to handle thousands of concurrent SSE connections.

✓ Live

SSE Production Deployment — Complete Guide to Going Live

SSE production deployment covers reverse proxy configuration, load balancing, monitoring, connection limits, and graceful shutdown for running server-sent events reliably at scale.

✓ Live

SSE Logging — Complete Guide to Stream Observability

SSE logging captures connection events, message delivery, errors, and performance metrics in structured format for debugging, monitoring, and auditing event streams.

✓ Live

SSE Authentication — Complete Guide to Securing Streams

SSE authentication verifies client identity using URL tokens, cookies, or custom headers during the initial request, ensuring only authorized clients receive event streams.

✓ Live

SSE Rate Limiting — Complete Guide to Connection Control

SSE rate limiting controls the number of concurrent connections per client and the frequency of events sent, preventing resource exhaustion and ensuring fair access.

✓ Live

SSE Scalability — Complete Guide to Horizontal Scaling

SSE scalability covers distributing connections across multiple servers using Redis pub/sub, load balancers, and sticky sessions for handling thousands of concurrent streams.

✓ Live

SSE Debugging — Complete Guide to Troubleshooting Streams

SSE debugging covers common connection issues, browser DevTools inspection, network analysis, and server-side logging to identify and fix streaming problems.

✓ Live

SSE Express Integration — Complete Guide to Production Streaming

SSE with Express.js covers advanced patterns including middleware integration, connection pooling, graceful shutdown, and cluster mode for production streaming.

✓ Live

SSE Python Integration — Complete Guide to Async Streaming

SSE with Python covers async generators, aiohttp, FastAPI StreamingResponse, and Flask StreamingHttpResponse for real-time event streaming.

✓ Live

SSE EventSource API Deep Dive — Complete Guide to Client-Side Streaming

SSE EventSource API deep dive covers advanced client features including custom event handlers, connection states, error recovery, and polyfill alternatives.

✓ Live

SSE Alternatives — Complete Guide to Real-Time Options

SSE alternatives compares Server-Sent Events with WebSocket, long polling, Server-Sent Events over HTTP/2, and gRPC streaming for choosing the right real-time technology.

✓ Live

SSE Node.js Advanced — Complete Guide to Cluster Streaming

SSE with Node.js advanced covers cluster mode, Redis pub/sub for cross-process communication, and connection pooling for high-scale streaming.

✓ Live

SSE chunked transfer — Complete Guide

SSE chunked transfer is a key concept in server-sent events for real-time streaming.

✓ Live

SSE comment events — Complete Guide

SSE comment events is a key concept in server-sent events for real-time streaming.

✓ Live

SSE cors policy — Complete Guide

Learn SSE cors policy. Step-by-step tutorial with practical examples.

✓ Live

SSE custom events — Complete Guide

SSE custom events is a key concept in server-sent events for real-time streaming.

✓ Live

SSE data formats — Complete Guide

SSE data formats is a key concept in server-sent events for real-time streaming.

✓ Live

SSE named events — Complete Guide

SSE named events is a key concept in server-sent events for real-time streaming.

✓ Live

SSE reconnection — Complete Guide

SSE reconnection is a key concept in server-sent events for real-time streaming.

✓ Live

SSE security considerations — Complete Guide

Server-Sent Events security considerations covers real-time streaming patterns for web applications.

✓ Live

SSE stream format — Complete Guide

SSE stream format is a key concept in server-sent events for real-time streaming.

✓ Live

SSE Connection Pooling — Complete Guide to Resource Management

SSE connection pooling manages multiple EventSource connections efficiently, reusing TCP connections and reducing overhead for scalable real-time applications.

✓ Live

All 44 topics in Server-Sent Events (SSE) Complete Guide: One-Way Real-Time Data Streaming are published.